renovate 44.210.2 → 44.211.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/config/options/index.js +1 -1
- package/dist/config/options/index.js.map +1 -1
- package/dist/config/utils.js +2 -1
- package/dist/config/utils.js.map +1 -1
- package/dist/config/validation-helpers/regex-glob-matchers.js.map +1 -1
- package/dist/config/validation-helpers/utils.js +5 -1
- package/dist/config/validation-helpers/utils.js.map +1 -1
- package/dist/config/validation.js +8 -2
- package/dist/config/validation.js.map +1 -1
- package/dist/config-validator.js +1 -1
- package/dist/config-validator.js.map +1 -1
- package/dist/global-config-option-defaults.generated.js +1 -1
- package/dist/global-config-option-defaults.generated.js.map +1 -1
- package/dist/instrumentation/index.js +3 -2
- package/dist/instrumentation/index.js.map +1 -1
- package/dist/logger/bunyan.js +3 -2
- package/dist/logger/bunyan.js.map +1 -1
- package/dist/logger/pretty-stdout.js +2 -1
- package/dist/logger/pretty-stdout.js.map +1 -1
- package/dist/modules/datasource/apk/index.js +2 -2
- package/dist/modules/datasource/apk/index.js.map +1 -1
- package/dist/modules/datasource/artifactory/index.js +2 -3
- package/dist/modules/datasource/artifactory/index.js.map +1 -1
- package/dist/modules/datasource/bazel/index.js +2 -1
- package/dist/modules/datasource/bazel/index.js.map +1 -1
- package/dist/modules/datasource/cdnjs/index.js +2 -1
- package/dist/modules/datasource/cdnjs/index.js.map +1 -1
- package/dist/modules/datasource/conda/index.js +2 -1
- package/dist/modules/datasource/conda/index.js.map +1 -1
- package/dist/modules/datasource/crate/index.js +2 -1
- package/dist/modules/datasource/crate/index.js.map +1 -1
- package/dist/modules/datasource/dart-version/index.js +2 -1
- package/dist/modules/datasource/dart-version/index.js.map +1 -1
- package/dist/modules/datasource/datasource.js +2 -2
- package/dist/modules/datasource/datasource.js.map +1 -1
- package/dist/modules/datasource/deb/url.js +3 -1
- package/dist/modules/datasource/deb/url.js.map +1 -1
- package/dist/modules/datasource/devbox/index.js +2 -1
- package/dist/modules/datasource/devbox/index.js.map +1 -1
- package/dist/modules/datasource/docker/common.js +10 -8
- package/dist/modules/datasource/docker/common.js.map +1 -1
- package/dist/modules/datasource/docker/ecr.js +2 -1
- package/dist/modules/datasource/docker/ecr.js.map +1 -1
- package/dist/modules/datasource/docker/index.js +20 -17
- package/dist/modules/datasource/docker/index.js.map +1 -1
- package/dist/modules/datasource/gitea-tags/base.js +2 -3
- package/dist/modules/datasource/gitea-tags/base.js.map +1 -1
- package/dist/modules/datasource/github-tags/index.js +2 -1
- package/dist/modules/datasource/github-tags/index.js.map +1 -1
- package/dist/modules/datasource/gitlab-tags/index.js +2 -3
- package/dist/modules/datasource/gitlab-tags/index.js.map +1 -1
- package/dist/modules/datasource/go/base.js +1 -1
- package/dist/modules/datasource/go/base.js.map +1 -1
- package/dist/modules/datasource/go/common.js +8 -2
- package/dist/modules/datasource/go/common.js.map +1 -1
- package/dist/modules/datasource/go/env.js +2 -1
- package/dist/modules/datasource/go/env.js.map +1 -1
- package/dist/modules/datasource/go/releases-goproxy.js +7 -5
- package/dist/modules/datasource/go/releases-goproxy.js.map +1 -1
- package/dist/modules/datasource/helm/index.js +2 -1
- package/dist/modules/datasource/helm/index.js.map +1 -1
- package/dist/modules/datasource/hexpm-bob/index.js +2 -1
- package/dist/modules/datasource/hexpm-bob/index.js.map +1 -1
- package/dist/modules/datasource/index.js +4 -3
- package/dist/modules/datasource/index.js.map +1 -1
- package/dist/modules/datasource/java-version/adoptium.js +3 -2
- package/dist/modules/datasource/java-version/adoptium.js.map +1 -1
- package/dist/modules/datasource/java-version/graalvm.js +2 -1
- package/dist/modules/datasource/java-version/graalvm.js.map +1 -1
- package/dist/modules/datasource/maven/index.js.map +1 -1
- package/dist/modules/datasource/maven/util.js +7 -10
- package/dist/modules/datasource/maven/util.js.map +1 -1
- package/dist/modules/datasource/npm/npmrc.js +2 -2
- package/dist/modules/datasource/npm/npmrc.js.map +1 -1
- package/dist/modules/datasource/nuget/v3.js +3 -5
- package/dist/modules/datasource/nuget/v3.js.map +1 -1
- package/dist/modules/datasource/packagist/index.js +4 -5
- package/dist/modules/datasource/packagist/index.js.map +1 -1
- package/dist/modules/datasource/pod/index.js +4 -4
- package/dist/modules/datasource/pod/index.js.map +1 -1
- package/dist/modules/datasource/pypi/index.js +19 -11
- package/dist/modules/datasource/pypi/index.js.map +1 -1
- package/dist/modules/datasource/python-version/index.js +2 -3
- package/dist/modules/datasource/python-version/index.js.map +1 -1
- package/dist/modules/datasource/repology/index.js +4 -3
- package/dist/modules/datasource/repology/index.js.map +1 -1
- package/dist/modules/datasource/rpm/providers/common.js +3 -1
- package/dist/modules/datasource/rpm/providers/common.js.map +1 -1
- package/dist/modules/datasource/rubygems/index.js +2 -5
- package/dist/modules/datasource/rubygems/index.js.map +1 -1
- package/dist/modules/datasource/rubygems/versions-endpoint-cache.js +13 -18
- package/dist/modules/datasource/rubygems/versions-endpoint-cache.js.map +1 -1
- package/dist/modules/datasource/terraform-module/base.js +2 -1
- package/dist/modules/datasource/terraform-module/base.js.map +1 -1
- package/dist/modules/datasource/terraform-provider/index.js +2 -3
- package/dist/modules/datasource/terraform-provider/index.js.map +1 -1
- package/dist/modules/manager/bazel-module/parser/context.js +0 -1
- package/dist/modules/manager/bazel-module/parser/context.js.map +1 -1
- package/dist/modules/manager/bundler/host-rules.js +4 -1
- package/dist/modules/manager/bundler/host-rules.js.map +1 -1
- package/dist/modules/manager/composer/range.js +1 -1
- package/dist/modules/manager/composer/range.js.map +1 -1
- package/dist/modules/manager/custom/utils.js +3 -1
- package/dist/modules/manager/custom/utils.js.map +1 -1
- package/dist/modules/manager/devbox/schema.js +2 -1
- package/dist/modules/manager/devbox/schema.js.map +1 -1
- package/dist/modules/manager/dockerfile/extract.js +10 -2
- package/dist/modules/manager/dockerfile/extract.js.map +1 -1
- package/dist/modules/manager/fingerprint.generated.js +1 -1
- package/dist/modules/manager/fingerprint.generated.js.map +1 -1
- package/dist/modules/manager/github-actions/parse.js +2 -1
- package/dist/modules/manager/github-actions/parse.js.map +1 -1
- package/dist/modules/manager/gomod/artifacts.js +5 -2
- package/dist/modules/manager/gomod/artifacts.js.map +1 -1
- package/dist/modules/manager/gradle/artifacts.js +5 -2
- package/dist/modules/manager/gradle/artifacts.js.map +1 -1
- package/dist/modules/manager/gradle/utils.js +2 -1
- package/dist/modules/manager/gradle/utils.js.map +1 -1
- package/dist/modules/manager/gradle-wrapper/utils.js +9 -5
- package/dist/modules/manager/gradle-wrapper/utils.js.map +1 -1
- package/dist/modules/manager/helm-values/util.js +1 -1
- package/dist/modules/manager/helm-values/util.js.map +1 -1
- package/dist/modules/manager/helmfile/artifacts.js +1 -1
- package/dist/modules/manager/helmfile/artifacts.js.map +1 -1
- package/dist/modules/manager/helmv3/artifacts.js +1 -1
- package/dist/modules/manager/helmv3/artifacts.js.map +1 -1
- package/dist/modules/manager/maven/extract.js +5 -2
- package/dist/modules/manager/maven/extract.js.map +1 -1
- package/dist/modules/manager/maven-wrapper/artifacts.js +3 -2
- package/dist/modules/manager/maven-wrapper/artifacts.js.map +1 -1
- package/dist/modules/manager/mise/artifacts.js +2 -1
- package/dist/modules/manager/mise/artifacts.js.map +1 -1
- package/dist/modules/manager/mise/extract.js.map +1 -1
- package/dist/modules/manager/npm/artifacts.js +3 -1
- package/dist/modules/manager/npm/artifacts.js.map +1 -1
- package/dist/modules/manager/npm/extract/common/dependency.js +4 -1
- package/dist/modules/manager/npm/extract/common/dependency.js.map +1 -1
- package/dist/modules/manager/npm/extract/common/package-file.js +2 -1
- package/dist/modules/manager/npm/extract/common/package-file.js.map +1 -1
- package/dist/modules/manager/npm/extract/index.js.map +1 -1
- package/dist/modules/manager/npm/extract/post/locked-versions.js.map +1 -1
- package/dist/modules/manager/npm/npmrc.js +2 -1
- package/dist/modules/manager/npm/npmrc.js.map +1 -1
- package/dist/modules/manager/npm/post-update/index.js +2 -1
- package/dist/modules/manager/npm/post-update/index.js.map +1 -1
- package/dist/modules/manager/npm/post-update/npm.js +2 -3
- package/dist/modules/manager/npm/post-update/npm.js.map +1 -1
- package/dist/modules/manager/npm/post-update/yarn.js.map +1 -1
- package/dist/modules/manager/npm/schema.js +6 -2
- package/dist/modules/manager/npm/schema.js.map +1 -1
- package/dist/modules/manager/npm/update/dependency/index.js +3 -2
- package/dist/modules/manager/npm/update/dependency/index.js.map +1 -1
- package/dist/modules/manager/npm/update/locked-dependency/common/parent-version.js +6 -2
- package/dist/modules/manager/npm/update/locked-dependency/common/parent-version.js.map +1 -1
- package/dist/modules/manager/npm/update/locked-dependency/package-lock/get-locked.js +2 -1
- package/dist/modules/manager/npm/update/locked-dependency/package-lock/get-locked.js.map +1 -1
- package/dist/modules/manager/nuget/package-tree.js +2 -1
- package/dist/modules/manager/nuget/package-tree.js.map +1 -1
- package/dist/modules/manager/paket/update-locked.js +4 -1
- package/dist/modules/manager/paket/update-locked.js.map +1 -1
- package/dist/modules/manager/pipenv/extract.js +4 -1
- package/dist/modules/manager/pipenv/extract.js.map +1 -1
- package/dist/modules/platform/azure/azure-helper.js +2 -1
- package/dist/modules/platform/azure/azure-helper.js.map +1 -1
- package/dist/modules/platform/azure/index.js +7 -3
- package/dist/modules/platform/azure/index.js.map +1 -1
- package/dist/modules/platform/bitbucket/index.js +13 -6
- package/dist/modules/platform/bitbucket/index.js.map +1 -1
- package/dist/modules/platform/bitbucket-server/index.js +13 -9
- package/dist/modules/platform/bitbucket-server/index.js.map +1 -1
- package/dist/modules/platform/codecommit/index.js +2 -2
- package/dist/modules/platform/codecommit/index.js.map +1 -1
- package/dist/modules/platform/gerrit/client.js +4 -1
- package/dist/modules/platform/gerrit/client.js.map +1 -1
- package/dist/modules/platform/gerrit/index.js +3 -2
- package/dist/modules/platform/gerrit/index.js.map +1 -1
- package/dist/modules/platform/gitea/gitea-helper.js +5 -4
- package/dist/modules/platform/gitea/gitea-helper.js.map +1 -1
- package/dist/modules/platform/gitea/index.js +11 -4
- package/dist/modules/platform/gitea/index.js.map +1 -1
- package/dist/modules/platform/github/index.js +36 -23
- package/dist/modules/platform/github/index.js.map +1 -1
- package/dist/modules/platform/gitlab/index.js +16 -9
- package/dist/modules/platform/gitlab/index.js.map +1 -1
- package/dist/modules/platform/scm-manager/index.js +4 -1
- package/dist/modules/platform/scm-manager/index.js.map +1 -1
- package/dist/modules/platform/scm-manager/utils.js +2 -1
- package/dist/modules/platform/scm-manager/utils.js.map +1 -1
- package/dist/modules/versioning/cargo/index.js.map +1 -1
- package/dist/modules/versioning/composer/index.js +2 -1
- package/dist/modules/versioning/composer/index.js.map +1 -1
- package/dist/modules/versioning/conan/common.js +4 -1
- package/dist/modules/versioning/conan/common.js.map +1 -1
- package/dist/modules/versioning/debian/index.js +2 -1
- package/dist/modules/versioning/debian/index.js.map +1 -1
- package/dist/modules/versioning/gradle/compare.js +2 -1
- package/dist/modules/versioning/gradle/compare.js.map +1 -1
- package/dist/modules/versioning/hex/index.js +2 -1
- package/dist/modules/versioning/hex/index.js.map +1 -1
- package/dist/modules/versioning/julia/index.js.map +1 -1
- package/dist/modules/versioning/maven/compare.js +17 -7
- package/dist/modules/versioning/maven/compare.js.map +1 -1
- package/dist/modules/versioning/npm/index.js +2 -1
- package/dist/modules/versioning/npm/index.js.map +1 -1
- package/dist/modules/versioning/npm/range.js.map +1 -1
- package/dist/modules/versioning/paket/index.js +2 -1
- package/dist/modules/versioning/paket/index.js.map +1 -1
- package/dist/modules/versioning/paket/range.js +7 -3
- package/dist/modules/versioning/paket/range.js.map +1 -1
- package/dist/modules/versioning/pep440/index.js +2 -1
- package/dist/modules/versioning/pep440/index.js.map +1 -1
- package/dist/modules/versioning/poetry/index.js +2 -1
- package/dist/modules/versioning/poetry/index.js.map +1 -1
- package/dist/modules/versioning/regex/index.js +1 -1
- package/dist/modules/versioning/regex/index.js.map +1 -1
- package/dist/modules/versioning/rez/index.js +2 -1
- package/dist/modules/versioning/rez/index.js.map +1 -1
- package/dist/modules/versioning/vcpkg/index.js +2 -1
- package/dist/modules/versioning/vcpkg/index.js.map +1 -1
- package/dist/util/cache/package/impl/base.js +2 -1
- package/dist/util/cache/package/impl/base.js.map +1 -1
- package/dist/util/cache/package/with-cache.js +2 -1
- package/dist/util/cache/package/with-cache.js.map +1 -1
- package/dist/util/check-token.js +7 -4
- package/dist/util/check-token.js.map +1 -1
- package/dist/util/exec/utils.js +4 -1
- package/dist/util/exec/utils.js.map +1 -1
- package/dist/util/git/auth.js +5 -1
- package/dist/util/git/auth.js.map +1 -1
- package/dist/util/git/error.js.map +1 -1
- package/dist/util/host-rules.js +5 -3
- package/dist/util/host-rules.js.map +1 -1
- package/dist/util/http/cache/abstract-http-cache-provider.js +3 -2
- package/dist/util/http/cache/abstract-http-cache-provider.js.map +1 -1
- package/dist/util/http/cache/package-http-cache-provider.js +2 -1
- package/dist/util/http/cache/package-http-cache-provider.js.map +1 -1
- package/dist/util/http/github.js +15 -11
- package/dist/util/http/github.js.map +1 -1
- package/dist/util/http/gitlab.js +5 -4
- package/dist/util/http/gitlab.js.map +1 -1
- package/dist/util/http/http.js +2 -1
- package/dist/util/http/http.js.map +1 -1
- package/dist/util/http/jwt.js +2 -1
- package/dist/util/http/jwt.js.map +1 -1
- package/dist/util/http/retry-after.js +2 -1
- package/dist/util/http/retry-after.js.map +1 -1
- package/dist/util/http/status.js +95 -0
- package/dist/util/http/status.js.map +1 -0
- package/dist/util/merge-confidence/index.js +3 -2
- package/dist/util/merge-confidence/index.js.map +1 -1
- package/dist/util/package-rules/current-version.js +4 -1
- package/dist/util/package-rules/current-version.js.map +1 -1
- package/dist/util/package-rules/index.js +7 -3
- package/dist/util/package-rules/index.js.map +1 -1
- package/dist/util/schema-utils/index.js +5 -0
- package/dist/util/schema-utils/index.js.map +1 -1
- package/dist/workers/global/config/parse/host-rules-from-env.js +2 -1
- package/dist/workers/global/config/parse/host-rules-from-env.js.map +1 -1
- package/dist/workers/repository/common.js +4 -1
- package/dist/workers/repository/common.js.map +1 -1
- package/dist/workers/repository/config-migration/branch/index.js +2 -1
- package/dist/workers/repository/config-migration/branch/index.js.map +1 -1
- package/dist/workers/repository/dependency-dashboard.js +6 -2
- package/dist/workers/repository/dependency-dashboard.js.map +1 -1
- package/dist/workers/repository/finalize/repository-statistics.js +4 -1
- package/dist/workers/repository/finalize/repository-statistics.js.map +1 -1
- package/dist/workers/repository/init/merge.js +13 -3
- package/dist/workers/repository/init/merge.js.map +1 -1
- package/dist/workers/repository/onboarding/branch/check.js +2 -1
- package/dist/workers/repository/onboarding/branch/check.js.map +1 -1
- package/dist/workers/repository/onboarding/pr/pr-list.js +4 -2
- package/dist/workers/repository/onboarding/pr/pr-list.js.map +1 -1
- package/dist/workers/repository/process/extract-update.js +4 -1
- package/dist/workers/repository/process/extract-update.js.map +1 -1
- package/dist/workers/repository/process/lookup/digest.js +2 -1
- package/dist/workers/repository/process/lookup/digest.js.map +1 -1
- package/dist/workers/repository/process/lookup/generate.js +1 -1
- package/dist/workers/repository/process/lookup/generate.js.map +1 -1
- package/dist/workers/repository/process/lookup/index.js +4 -1
- package/dist/workers/repository/process/lookup/index.js.map +1 -1
- package/dist/workers/repository/process/lookup/utils.js +7 -1
- package/dist/workers/repository/process/lookup/utils.js.map +1 -1
- package/dist/workers/repository/process/vulnerabilities.js +10 -3
- package/dist/workers/repository/process/vulnerabilities.js.map +1 -1
- package/dist/workers/repository/reconfigure/index.js +2 -1
- package/dist/workers/repository/reconfigure/index.js.map +1 -1
- package/dist/workers/repository/update/branch/auto-replace.js +6 -2
- package/dist/workers/repository/update/branch/auto-replace.js.map +1 -1
- package/dist/workers/repository/update/branch/errors.js +2 -1
- package/dist/workers/repository/update/branch/errors.js.map +1 -1
- package/dist/workers/repository/update/branch/execute-post-upgrade-commands.js +2 -2
- package/dist/workers/repository/update/branch/execute-post-upgrade-commands.js.map +1 -1
- package/dist/workers/repository/update/branch/get-updated.js +1 -2
- package/dist/workers/repository/update/branch/get-updated.js.map +1 -1
- package/dist/workers/repository/update/branch/index.js +2 -1
- package/dist/workers/repository/update/branch/index.js.map +1 -1
- package/dist/workers/repository/update/branch/status-checks.js +2 -1
- package/dist/workers/repository/update/branch/status-checks.js.map +1 -1
- package/dist/workers/repository/update/pr/body/index.js.map +1 -1
- package/dist/workers/repository/update/pr/changelog/release-notes.js +3 -2
- package/dist/workers/repository/update/pr/changelog/release-notes.js.map +1 -1
- package/dist/workers/repository/update/pr/index.js +7 -3
- package/dist/workers/repository/update/pr/index.js.map +1 -1
- package/dist/workers/repository/updates/generate.js +6 -3
- package/dist/workers/repository/updates/generate.js.map +1 -1
- package/package.json +2 -2
- package/renovate-schema.json +2 -2
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"vulnerabilities.js","names":["p.all","getVersioning"],"sources":["../../../../lib/workers/repository/process/vulnerabilities.ts"],"sourcesContent":["// TODO #22198\nimport type { Ecosystem, Osv, OsvOffline } from '@renovatebot/osv-offline';\nimport {\n isEmptyArray,\n isNonEmptyString,\n isNullOrUndefined,\n isTruthy,\n} from '@sindresorhus/is';\nimport type { CvssVector } from 'ae-cvss-calculator';\nimport aeCvss from 'ae-cvss-calculator';\nimport upath from 'upath';\nimport { z } from 'zod/v4';\nimport { GlobalConfig } from '../../../config/global.ts';\nimport { getManagerConfig, mergeChildConfig } from '../../../config/index.ts';\nimport type { PackageRule, RenovateConfig } from '../../../config/types.ts';\nimport { instrument } from '../../../instrumentation/index.ts';\nimport { logger } from '../../../logger/index.ts';\nimport { getDefaultVersioning } from '../../../modules/datasource/common.ts';\nimport type {\n PackageDependency,\n PackageFile,\n} from '../../../modules/manager/types.ts';\nimport type { VersioningApi } from '../../../modules/versioning/index.ts';\nimport { get as getVersioning } from '../../../modules/versioning/index.ts';\nimport { coerceArray } from '../../../util/array.ts';\nimport { sanitizeMarkdown } from '../../../util/markdown.ts';\nimport * as p from '../../../util/promises.ts';\nimport { regEx } from '../../../util/regex.ts';\nimport { titleCase } from '../../../util/string.ts';\nimport { datasourceToOsvEcosystem } from '../../../util/vulnerability/ecosystem.ts';\nimport {\n getFixedVersionConstraint,\n getLastAffectedVersionConstraint,\n} from '../../../util/vulnerability/utils.ts';\nimport type {\n DependencyVulnerabilities,\n SeverityDetails,\n Vulnerability,\n} from './types.ts';\n\nconst { fromVector } = aeCvss;\n\nexport class Vulnerabilities {\n private static osvOffline: Promise<OsvOffline> | undefined;\n\n private osvOffline: OsvOffline;\n\n private static readonly datasourceEcosystemMap = datasourceToOsvEcosystem;\n\n private constructor(osvOffline: OsvOffline) {\n this.osvOffline = osvOffline;\n }\n\n private static initialize(): Promise<OsvOffline> {\n // no async here, so osv promise will only be created once\n Vulnerabilities.osvOffline ??= Vulnerabilities.load();\n return Vulnerabilities.osvOffline;\n }\n\n private static async load(): Promise<OsvOffline> {\n // osv-offline reads its root directory once, when the module is loaded\n if (!isNonEmptyString(process.env.OSV_OFFLINE_ROOT_DIR)) {\n if (process.env.OSV_OFFLINE_DISABLE_DOWNLOAD?.toLowerCase() === 'true') {\n // keep the old default, offline setups may have put the database there\n logger.debug(\n 'OSV_OFFLINE_DISABLE_DOWNLOAD is set, using the osv-offline default directory',\n );\n } else {\n const rootDir = upath.join(GlobalConfig.get('cacheDir'), 'osv-offline');\n logger.debug(`Using osv-offline directory ${rootDir}`);\n process.env.OSV_OFFLINE_ROOT_DIR = rootDir;\n }\n }\n const { OsvOffline } = await import('@renovatebot/osv-offline');\n return OsvOffline.create();\n }\n\n static async create(): Promise<Vulnerabilities> {\n // intialize osv only once\n const osvOffline = await Vulnerabilities.initialize();\n\n const instance = new Vulnerabilities(osvOffline);\n return instance;\n }\n\n /**\n * Closes the shared OSV databases, if they were opened.\n */\n static async cleanup(): Promise<void> {\n const osvOffline = await Vulnerabilities.osvOffline?.catch(() => undefined);\n Vulnerabilities.osvOffline = undefined;\n osvOffline?.[Symbol.dispose]();\n }\n\n async appendVulnerabilityPackageRules(\n config: RenovateConfig,\n packageFiles: Record<string, PackageFile[]>,\n ): Promise<void> {\n const dependencyVulnerabilities = await this.fetchDependencyVulnerabilities(\n config,\n packageFiles,\n );\n\n config.packageRules ??= [];\n for (const {\n vulnerabilities,\n versioningApi,\n } of dependencyVulnerabilities) {\n const groupPackageRules: PackageRule[] = [];\n for (const vulnerability of vulnerabilities) {\n const rule = this.vulnerabilityToPackageRules(vulnerability);\n if (isNullOrUndefined(rule)) {\n continue;\n }\n groupPackageRules.push(rule);\n }\n this.sortByFixedVersion(groupPackageRules, versioningApi);\n\n config.packageRules.push(...groupPackageRules);\n }\n }\n\n async fetchVulnerabilities(\n config: RenovateConfig,\n packageFiles: Record<string, PackageFile[]>,\n ): Promise<Vulnerability[]> {\n const groups = await this.fetchDependencyVulnerabilities(\n config,\n packageFiles,\n );\n return groups.flatMap((group) => group.vulnerabilities);\n }\n\n private async fetchDependencyVulnerabilities(\n config: RenovateConfig,\n packageFiles: Record<string, PackageFile[]>,\n ): Promise<DependencyVulnerabilities[]> {\n const managers = Object.keys(packageFiles);\n const allManagerJobs = managers.map((manager) =>\n this.fetchManagerVulnerabilities(config, packageFiles, manager),\n );\n return (await Promise.all(allManagerJobs)).flat();\n }\n\n private async fetchManagerVulnerabilities(\n config: RenovateConfig,\n packageFiles: Record<string, PackageFile[]>,\n manager: string,\n ): Promise<DependencyVulnerabilities[]> {\n const managerConfig = getManagerConfig(config, manager);\n const queue = packageFiles[manager].map(\n (pFile) => (): Promise<DependencyVulnerabilities[]> =>\n this.fetchManagerPackageFileVulnerabilities(managerConfig, pFile),\n );\n logger.trace(\n { manager, queueLength: queue.length },\n 'fetchManagerVulnerabilities starting',\n );\n const result = (await p.all(queue)).flat();\n logger.trace({ manager }, 'fetchManagerVulnerabilities finished');\n return result;\n }\n\n private async fetchManagerPackageFileVulnerabilities(\n managerConfig: RenovateConfig,\n pFile: PackageFile,\n ): Promise<DependencyVulnerabilities[]> {\n const { packageFile } = pFile;\n const packageFileConfig = mergeChildConfig(managerConfig, pFile);\n const { manager } = packageFileConfig;\n const queue = pFile.deps.map(\n (dep) => (): Promise<DependencyVulnerabilities | null> =>\n this.fetchDependencyVulnerability(packageFileConfig, dep),\n );\n logger.trace(\n { manager, packageFile, queueLength: queue.length },\n 'fetchManagerPackageFileVulnerabilities starting with concurrency',\n );\n\n const result = await p.all(queue);\n logger.trace(\n { packageFile },\n 'fetchManagerPackageFileVulnerabilities finished',\n );\n\n return result.filter(isTruthy);\n }\n\n private async fetchDependencyVulnerability(\n packageFileConfig: RenovateConfig & PackageFile,\n dep: PackageDependency,\n ): Promise<DependencyVulnerabilities | null> {\n const ecosystem = Vulnerabilities.datasourceEcosystemMap[dep.datasource!];\n if (!ecosystem) {\n logger.trace(`Cannot map datasource ${dep.datasource!} to OSV ecosystem`);\n return null;\n }\n\n const packageName = dep.packageName!;\n let osvPackageName = packageName;\n let depType: string | undefined;\n if (ecosystem === 'PyPI') {\n // https://peps.python.org/pep-0503/#normalized-names\n osvPackageName = osvPackageName\n .toLowerCase()\n .replace(regEx(/[_.-]+/g), '-');\n } else if (ecosystem === 'Go' && packageName === 'go') {\n if (dep.depType !== 'toolchain') {\n // The `go` directive is source compatibility, not the build toolchain, so we skip it\n return null;\n }\n osvPackageName = 'stdlib';\n depType = dep.depType;\n }\n\n try {\n const osvVulnerabilities = await instrument(\n 'get OSV vulnerabilities',\n () => this.osvOffline.getVulnerabilities(ecosystem, osvPackageName),\n {\n attributes: {\n osvPackageName,\n ecosystem,\n },\n },\n );\n if (\n isNullOrUndefined(osvVulnerabilities) ||\n isEmptyArray(osvVulnerabilities)\n ) {\n logger.trace(\n `No vulnerabilities found in OSV database for ${packageName}`,\n );\n return null;\n }\n\n const depVersion =\n dep.lockedVersion ?? dep.currentVersion ?? dep.currentValue!;\n\n const versioning = dep.versioning ?? getDefaultVersioning(dep.datasource);\n const versioningApi = getVersioning(versioning);\n\n if (!versioningApi.isVersion(depVersion)) {\n logger.debug(\n `Skipping vulnerability lookup for package ${packageName} due to unsupported version ${depVersion}`,\n );\n return null;\n }\n\n const vulnerabilities: Vulnerability[] = [];\n for (const osvVulnerability of osvVulnerabilities) {\n if (osvVulnerability.withdrawn) {\n logger.trace(\n `Skipping withdrawn vulnerability ${osvVulnerability.id}`,\n );\n continue;\n }\n\n this.skipMaliciousPackages(\n ecosystem,\n osvPackageName,\n depVersion,\n versioningApi,\n dep,\n packageFileConfig.manager,\n packageFileConfig.packageFile,\n osvVulnerability,\n );\n\n for (const affected of coerceArray(osvVulnerability.affected)) {\n const isVulnerable = this.isPackageVulnerable(\n ecosystem,\n osvPackageName,\n depVersion,\n affected,\n versioningApi,\n );\n if (!isVulnerable) {\n continue;\n }\n\n logger.debug(\n `Vulnerability ${osvVulnerability.id} affects ${packageName} ${depVersion}`,\n );\n const fixedVersion = this.getFixedVersion(\n ecosystem,\n depVersion,\n affected,\n versioningApi,\n );\n\n vulnerabilities.push({\n packageName,\n osvPackageName,\n vulnerability: osvVulnerability,\n affected,\n depType,\n depVersion,\n versioning: dep.versioning,\n fixedVersion,\n datasource: dep.datasource!,\n packageFileConfig,\n });\n }\n }\n\n return { vulnerabilities, versioningApi };\n } catch (err) {\n logger.warn(\n { err, packageName },\n 'Error fetching vulnerability information for package',\n );\n return null;\n }\n }\n\n private skipMaliciousPackages(\n ecosystem: Ecosystem,\n osvPackageName: string,\n depVersion: string,\n versioningApi: VersioningApi,\n dep: PackageDependency,\n manager: string | undefined,\n packageFile: string,\n osvVulnerability: Osv.Vulnerability,\n ): void {\n // the OpenSSF's Malicious Packages (https://github.com/ossf/malicious-packages) is a source of advisories through osv.dev, which takes various sources of advisories, and will re-publish them with more specific information about their malicious usage\n if (osvVulnerability.id.startsWith('MAL-')) {\n // is the current dependency vulnerable?\n for (const affected of coerceArray(osvVulnerability.affected)) {\n // is the current dependency vulnerable?\n const isVulnerable = this.isPackageVulnerable(\n ecosystem,\n osvPackageName,\n depVersion,\n affected,\n versioningApi,\n );\n\n if (isVulnerable) {\n logger.debug(\n {\n packageFile: packageFile,\n depName: dep.depName,\n packageName: dep.packageName,\n manager: manager,\n datasource: dep.datasource,\n currentVersion: depVersion,\n },\n `Marking ${dep.depName} as skipReason=malicious-version-in-use, as it is affected by ${osvVulnerability.id}`,\n );\n dep.skipReason = 'malicious-version-in-use';\n dep.skipStage = 'lookup';\n }\n\n // or are any of the updates vulnerable?\n for (const update of coerceArray(dep.updates)) {\n const newVersion = update.newVersion ?? update.newValue!;\n\n const isUpdateVulnerable = this.isPackageVulnerable(\n ecosystem,\n osvPackageName,\n newVersion,\n affected,\n versioningApi,\n );\n\n if (isUpdateVulnerable) {\n logger.debug(\n {\n packageFile: packageFile,\n depName: dep.depName,\n packageName: dep.packageName,\n manager: manager,\n datasource: dep.datasource,\n currentVersion: depVersion,\n newVersion,\n },\n `Marking ${dep.depName}'s update to ${newVersion} as skipReason=malicious-update-proposed, as it is affected by ${osvVulnerability.id}`,\n );\n dep.skipReason = 'malicious-update-proposed';\n dep.skipStage = 'lookup';\n }\n }\n }\n }\n }\n\n private sortByFixedVersion(\n packageRules: PackageRule[],\n versioningApi: VersioningApi,\n ): void {\n const versionsCleaned: Record<string, string> = {};\n for (const rule of packageRules) {\n const version = rule.allowedVersions!;\n versionsCleaned[version] = version.replace(regEx(/[(),=> ]+/g), '');\n }\n packageRules.sort((a, b) =>\n versioningApi.sortVersions(\n versionsCleaned[a.allowedVersions!],\n versionsCleaned[b.allowedVersions!],\n ),\n );\n }\n\n // https://ossf.github.io/osv-schema/#affectedrangesevents-fields\n private sortEvents(\n events: Osv.Event[],\n versioningApi: VersioningApi,\n ): Osv.Event[] {\n const sortedCopy: Osv.Event[] = [];\n let zeroEvent: Osv.Event | null = null;\n\n for (const event of events) {\n if (event.introduced === '0') {\n zeroEvent = event;\n } else if (versioningApi.isVersion(Object.values(event)[0])) {\n sortedCopy.push(event);\n } else {\n logger.debug({ event }, 'Skipping OSV event with invalid version');\n }\n }\n\n sortedCopy.sort((a, b) =>\n // no pre-processing, as there are only very few values to sort\n versioningApi.sortVersions(Object.values(a)[0], Object.values(b)[0]),\n );\n\n if (zeroEvent) {\n sortedCopy.unshift(zeroEvent);\n }\n\n return sortedCopy;\n }\n\n private isPackageAffected(\n ecosystem: Ecosystem,\n osvPackageName: string,\n affected: Osv.Affected,\n ): boolean {\n const pkg = affected.package;\n if (pkg?.name !== osvPackageName) {\n return false;\n }\n\n // Match exact ecosystems and OSV sub-ecosystems (e.g. Packagist:https://packages.drupal.org/8).\n return (\n pkg.ecosystem === ecosystem || pkg.ecosystem.startsWith(`${ecosystem}:`)\n );\n }\n\n private includedInVersions(\n depVersion: string,\n affected: Osv.Affected,\n ): boolean {\n return !!affected.versions?.includes(depVersion);\n }\n\n private includedInRanges(\n depVersion: string,\n affected: Osv.Affected,\n versioningApi: VersioningApi,\n ): boolean {\n for (const range of coerceArray(affected.ranges)) {\n if (range.type === 'GIT') {\n continue;\n }\n\n let vulnerable = false;\n for (const event of this.sortEvents(range.events, versioningApi)) {\n if (\n isNonEmptyString(event.introduced) &&\n (event.introduced === '0' ||\n this.isVersionGtOrEq(depVersion, event.introduced, versioningApi))\n ) {\n vulnerable = true;\n } else if (\n isNonEmptyString(event.fixed) &&\n this.isVersionGtOrEq(depVersion, event.fixed, versioningApi)\n ) {\n vulnerable = false;\n } else if (\n isNonEmptyString(event.last_affected) &&\n this.isVersionGt(depVersion, event.last_affected, versioningApi)\n ) {\n vulnerable = false;\n }\n }\n\n if (vulnerable) {\n return true;\n }\n }\n\n return false;\n }\n\n // https://ossf.github.io/osv-schema/#evaluation\n private isPackageVulnerable(\n ecosystem: Ecosystem,\n osvPackageName: string,\n depVersion: string,\n affected: Osv.Affected,\n versioningApi: VersioningApi,\n ): boolean {\n return (\n this.isPackageAffected(ecosystem, osvPackageName, affected) &&\n (this.includedInVersions(depVersion, affected) ||\n this.includedInRanges(depVersion, affected, versioningApi))\n );\n }\n\n private getFixedVersion(\n ecosystem: Ecosystem,\n depVersion: string,\n affected: Osv.Affected,\n versioningApi: VersioningApi,\n ): string | null {\n const fixedVersions: string[] = [];\n const lastAffectedVersions: string[] = [];\n\n for (const range of coerceArray(affected.ranges)) {\n if (range.type === 'GIT') {\n continue;\n }\n\n for (const event of range.events) {\n if (\n isNonEmptyString(event.fixed) &&\n versioningApi.isVersion(event.fixed)\n ) {\n fixedVersions.push(event.fixed);\n } else if (\n isNonEmptyString(event.last_affected) &&\n versioningApi.isVersion(event.last_affected)\n ) {\n lastAffectedVersions.push(event.last_affected);\n }\n }\n }\n\n fixedVersions.sort((a, b) => versioningApi.sortVersions(a, b));\n const fixedVersion = fixedVersions.find((version) =>\n this.isVersionGt(version, depVersion, versioningApi),\n );\n if (fixedVersion) {\n return this.getFixedVersionByEcosystem(fixedVersion, ecosystem);\n }\n\n lastAffectedVersions.sort((a, b) => versioningApi.sortVersions(a, b));\n const lastAffected = lastAffectedVersions.find((version) =>\n this.isVersionGtOrEq(version, depVersion, versioningApi),\n );\n if (lastAffected) {\n return this.getLastAffectedByEcosystem(lastAffected, ecosystem);\n }\n\n return null;\n }\n\n private getFixedVersionByEcosystem(\n fixedVersion: string,\n ecosystem: Ecosystem,\n ): string {\n return getFixedVersionConstraint(fixedVersion, ecosystem);\n }\n\n private getLastAffectedByEcosystem(\n lastAffected: string,\n ecosystem: Ecosystem,\n ): string {\n return getLastAffectedVersionConstraint(lastAffected, ecosystem);\n }\n\n private isVersionGt(\n version: string,\n other: string,\n versioningApi: VersioningApi,\n ): boolean {\n return (\n versioningApi.isVersion(version) &&\n versioningApi.isVersion(other) &&\n versioningApi.isGreaterThan(version, other)\n );\n }\n\n private isVersionGtOrEq(\n version: string,\n other: string,\n versioningApi: VersioningApi,\n ): boolean {\n return (\n versioningApi.isVersion(version) &&\n versioningApi.isVersion(other) &&\n (versioningApi.equals(version, other) ||\n versioningApi.isGreaterThan(version, other))\n );\n }\n\n private vulnerabilityToPackageRules(vul: Vulnerability): PackageRule | null {\n const {\n vulnerability,\n affected,\n packageName,\n depType,\n depVersion,\n fixedVersion,\n datasource,\n versioning: depVersioning,\n packageFileConfig,\n } = vul;\n if (isNullOrUndefined(fixedVersion)) {\n logger.debug(\n `No fixed version available for vulnerability ${vulnerability.id} in ${packageName} ${depVersion}`,\n );\n return null;\n }\n\n // Prefer the `versioning` already assigned to the dependency by its manager\n const versioning = depVersioning ?? getDefaultVersioning(datasource);\n\n logger.debug(\n {\n datasource,\n versioning,\n },\n\n `Setting allowed version ${fixedVersion} to fix vulnerability ${vulnerability.id} in ${packageName} ${depVersion}`,\n );\n\n const severityDetails = this.extractSeverityDetails(\n vulnerability,\n affected,\n );\n\n return {\n matchDatasources: [datasource],\n matchPackageNames: [packageName],\n ...(depType ? { matchDepTypes: [depType] } : {}),\n matchCurrentVersion: depVersion,\n versioning,\n allowedVersions: fixedVersion,\n isVulnerabilityAlert: true,\n vulnerabilitySeverity: severityDetails.severityLevel,\n prBodyNotes: this.generatePrBodyNotes(vulnerability, affected),\n force: {\n ...packageFileConfig.vulnerabilityAlerts,\n },\n };\n }\n\n static evaluateCvssVector(vector: string): [string, string] {\n const CvssJson = z.object({\n baseScore: z.number().default(0.0),\n baseSeverity: z.string().toUpperCase().default('UNKNOWN'),\n });\n\n try {\n const parsedCvssScore: CvssVector<any> | null = fromVector(vector);\n const res = CvssJson.parse(parsedCvssScore?.createJsonSchema());\n\n return [res.baseScore.toFixed(1), res.baseSeverity];\n } catch {\n logger.debug(`Error processing CVSS vector ${vector}`);\n }\n\n return ['', ''];\n }\n\n private generatePrBodyNotes(\n vulnerability: Osv.Vulnerability,\n affected: Osv.Affected,\n ): string[] {\n let aliases = [vulnerability.id]\n .concat(coerceArray(vulnerability.aliases))\n .sort();\n aliases = aliases.map((id) => {\n if (id.startsWith('CVE-')) {\n return `[${id}](https://nvd.nist.gov/vuln/detail/${id})`;\n }\n if (id.startsWith('GHSA-')) {\n return `[${id}](https://github.com/advisories/${id})`;\n }\n if (id.startsWith('GO-')) {\n return `[${id}](https://pkg.go.dev/vuln/${id})`;\n }\n if (id.startsWith('RUSTSEC-')) {\n return `[${id}](https://rustsec.org/advisories/${id}.html)`;\n }\n\n return id;\n });\n\n let content = '\\n\\n---\\n\\n### ';\n content += vulnerability.summary ? `${vulnerability.summary}\\n` : '';\n content += `${aliases.join(' / ')}\\n`;\n content += `\\n<details>\\n<summary>More information</summary>\\n`;\n\n const details = vulnerability.details?.replace(\n regEx(/^#{1,4} /gm),\n '##### ',\n );\n content += `#### Details\\n${details ?? 'No details.'}\\n`;\n\n content += '#### Severity\\n';\n const severityDetails = this.extractSeverityDetails(\n vulnerability,\n affected,\n );\n\n if (severityDetails.cvssVector) {\n content += `- CVSS Score: ${severityDetails.score}\\n`;\n content += `- Vector String: \\`${severityDetails.cvssVector}\\`\\n`;\n } else {\n content += `${titleCase(severityDetails.severityLevel)}\\n`;\n }\n\n content += `\\n#### References\\n${\n vulnerability.references\n ?.map((ref) => {\n return `- [${ref.url}](${ref.url})`;\n })\n .join('\\n') ?? 'No references.'\n }`;\n\n let attribution = '';\n if (vulnerability.id.startsWith('GHSA-')) {\n attribution = ` and the [GitHub Advisory Database](https://github.com/github/advisory-database) ([CC-BY 4.0](https://github.com/github/advisory-database/blob/main/LICENSE.md))`;\n } else if (vulnerability.id.startsWith('GO-')) {\n attribution = ` and the [Go Vulnerability Database](https://github.com/golang/vulndb) ([CC-BY 4.0](https://github.com/golang/vulndb#license))`;\n } else if (vulnerability.id.startsWith('PYSEC-')) {\n attribution = ` and the [PyPI Advisory Database](https://github.com/pypa/advisory-database) ([CC-BY 4.0](https://github.com/pypa/advisory-database/blob/main/LICENSE))`;\n } else if (vulnerability.id.startsWith('RUSTSEC-')) {\n attribution = ` and the [Rust Advisory Database](https://github.com/RustSec/advisory-db) ([CC0 1.0](https://github.com/rustsec/advisory-db/blob/main/LICENSE.txt))`;\n }\n content += `\\n\\nThis data is provided by [OSV](https://osv.dev/vulnerability/${vulnerability.id})${attribution}.\\n`;\n content += `</details>`;\n\n return [sanitizeMarkdown(content)];\n }\n\n private extractSeverityDetails(\n vulnerability: Osv.Vulnerability,\n affected: Osv.Affected,\n ): SeverityDetails {\n let severityLevel = 'UNKNOWN';\n let score = 'Unknown';\n\n const cvssVector =\n vulnerability.severity?.find((e) => e.type === 'CVSS_V4')?.score ??\n vulnerability.severity?.find((e) => e.type === 'CVSS_V3')?.score ??\n (affected.database_specific?.cvss as string); // RUSTSEC\n\n if (cvssVector) {\n const [baseScore, severity] =\n Vulnerabilities.evaluateCvssVector(cvssVector);\n severityLevel = severity ? severity.toUpperCase() : 'UNKNOWN';\n score = baseScore\n ? `${baseScore} / 10 (${titleCase(severityLevel)})`\n : 'Unknown';\n } else if (\n vulnerability.id.startsWith('GHSA-') &&\n vulnerability.database_specific?.severity\n ) {\n const severity = vulnerability.database_specific.severity as string;\n severityLevel = severity.toUpperCase();\n }\n\n return {\n cvssVector,\n score,\n severityLevel,\n };\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;AAwCA,MAAM,EAAE,eAAe;AAEvB,IAAa,kBAAb,MAAa,gBAAgB;CAC3B,OAAe;CAEf;CAEA,OAAwB,yBAAyB;CAEjD,YAAoB,YAAwB;EAC1C,KAAK,aAAa;CACpB;CAEA,OAAe,aAAkC;EAE/C,gBAAgB,eAAe,gBAAgB,KAAK;EACpD,OAAO,gBAAgB;CACzB;CAEA,aAAqB,OAA4B;EAE/C,IAAI,CAAC,iBAAiB,QAAQ,IAAI,oBAAoB,GAAG;GACvD,IAAI,QAAQ,IAAI,8BAA8B,YAAY,MAAM,QAE9D,OAAO,MACL,8EACF;QACK;IACL,MAAM,UAAU,MAAM,KAAK,aAAa,IAAI,UAAU,GAAG,aAAa;IACtE,OAAO,MAAM,+BAA+B,SAAS;IACrD,QAAQ,IAAI,uBAAuB;GACrC;EACF;EACA,MAAM,EAAE,eAAe,MAAM,OAAO;EACpC,OAAO,WAAW,OAAO;CAC3B;CAEA,aAAa,SAAmC;EAE9C,MAAM,aAAa,MAAM,gBAAgB,WAAW;EAGpD,OAAO,IADc,gBAAgB,UACvB;CAChB;;;;CAKA,aAAa,UAAyB;EACpC,MAAM,aAAa,MAAM,gBAAgB,YAAY,YAAY,KAAA,CAAS;EAC1E,g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AI,IAAI;EACnC,CAAC,CAAC,CACD,KAAK,IAAI,KAAK;EAGnB,IAAI,cAAc;EAClB,IAAI,cAAc,GAAG,WAAW,OAAO,GACrC,cAAc;OACT,IAAI,cAAc,GAAG,WAAW,KAAK,GAC1C,cAAc;OACT,IAAI,cAAc,GAAG,WAAW,QAAQ,GAC7C,cAAc;OACT,IAAI,cAAc,GAAG,WAAW,UAAU,GAC/C,cAAc;EAEhB,WAAW,oEAAoE,cAAc,GAAG,GAAG,YAAY;EAC/G,WAAW;EAEX,OAAO,CAAC,iBAAiB,OAAO,CAAC;CACnC;CAEA,uBACE,eACA,UACiB;EACjB,IAAI,gBAAgB;EACpB,IAAI,QAAQ;EAEZ,MAAM,aACJ,cAAc,UAAU,MAAM,MAAM,EAAE,SAAS,SAAS,CAAC,EAAE,SAC3D,cAAc,UAAU,MAAM,MAAM,EAAE,SAAS,SAAS,CAAC,EAAE,SAC1D,SAAS,mBAAmB;EAE/B,IAAI,YAAY;GACd,MAAM,CAAC,WAAW,YAChB,gBAAgB,mBAAmB,UAAU;GAC/C,gBAAgB,WAAW,SAAS,YAAY,IAAI;GACpD,QAAQ,YACJ,GAAG,UAAU,SAAS,UAAU,aAAa,EAAE,KAC/C;EACN,OAAO,IACL,cAAc,GAAG,WAAW,OAAO,KACnC,cAAc,mBAAmB,UAGjC,gBADiB,cAAc,kBAAkB,SACxB,YAAY;EAGvC,OAAO;GACL;GACA;GACA;EACF;CACF;AACF"}
|
|
1
|
+
{"version":3,"file":"vulnerabilities.js","names":["p.all","getVersioning"],"sources":["../../../../lib/workers/repository/process/vulnerabilities.ts"],"sourcesContent":["// TODO #22198\nimport type { Ecosystem, Osv, OsvOffline } from '@renovatebot/osv-offline';\nimport {\n isEmptyArray,\n isNonEmptyString,\n isNullOrUndefined,\n isTruthy,\n} from '@sindresorhus/is';\nimport type { CvssVector } from 'ae-cvss-calculator';\nimport aeCvss from 'ae-cvss-calculator';\nimport upath from 'upath';\nimport { z } from 'zod/v4';\nimport { GlobalConfig } from '../../../config/global.ts';\nimport { getManagerConfig, mergeChildConfig } from '../../../config/index.ts';\nimport type { PackageRule, RenovateConfig } from '../../../config/types.ts';\nimport { instrument } from '../../../instrumentation/index.ts';\nimport { logger } from '../../../logger/index.ts';\nimport { getDefaultVersioning } from '../../../modules/datasource/common.ts';\nimport type {\n PackageDependency,\n PackageFile,\n} from '../../../modules/manager/types.ts';\nimport type { VersioningApi } from '../../../modules/versioning/index.ts';\nimport { get as getVersioning } from '../../../modules/versioning/index.ts';\nimport { coerceArray } from '../../../util/array.ts';\nimport { sanitizeMarkdown } from '../../../util/markdown.ts';\nimport * as p from '../../../util/promises.ts';\nimport { regEx } from '../../../util/regex.ts';\nimport { titleCase } from '../../../util/string.ts';\nimport { datasourceToOsvEcosystem } from '../../../util/vulnerability/ecosystem.ts';\nimport {\n getFixedVersionConstraint,\n getLastAffectedVersionConstraint,\n} from '../../../util/vulnerability/utils.ts';\nimport type {\n DependencyVulnerabilities,\n SeverityDetails,\n Vulnerability,\n} from './types.ts';\n\nconst { fromVector } = aeCvss;\n\nexport class Vulnerabilities {\n private static osvOffline: Promise<OsvOffline> | undefined;\n\n private osvOffline: OsvOffline;\n\n private static readonly datasourceEcosystemMap = datasourceToOsvEcosystem;\n\n private constructor(osvOffline: OsvOffline) {\n this.osvOffline = osvOffline;\n }\n\n private static initialize(): Promise<OsvOffline> {\n // no async here, so osv promise will only be created once\n Vulnerabilities.osvOffline ??= Vulnerabilities.load();\n return Vulnerabilities.osvOffline;\n }\n\n private static async load(): Promise<OsvOffline> {\n // osv-offline reads its root directory once, when the module is loaded\n if (!isNonEmptyString(process.env.OSV_OFFLINE_ROOT_DIR)) {\n if (process.env.OSV_OFFLINE_DISABLE_DOWNLOAD?.toLowerCase() === 'true') {\n // keep the old default, offline setups may have put the database there\n logger.debug(\n 'OSV_OFFLINE_DISABLE_DOWNLOAD is set, using the osv-offline default directory',\n );\n } else {\n const rootDir = upath.join(GlobalConfig.get('cacheDir'), 'osv-offline');\n logger.debug(`Using osv-offline directory ${rootDir}`);\n process.env.OSV_OFFLINE_ROOT_DIR = rootDir;\n }\n }\n const { OsvOffline } = await import('@renovatebot/osv-offline');\n return OsvOffline.create();\n }\n\n static async create(): Promise<Vulnerabilities> {\n // intialize osv only once\n const osvOffline = await Vulnerabilities.initialize();\n\n const instance = new Vulnerabilities(osvOffline);\n return instance;\n }\n\n /**\n * Closes the shared OSV databases, if they were opened.\n */\n static async cleanup(): Promise<void> {\n const osvOffline = await Vulnerabilities.osvOffline?.catch(() => undefined);\n Vulnerabilities.osvOffline = undefined;\n osvOffline?.[Symbol.dispose]();\n }\n\n async appendVulnerabilityPackageRules(\n config: RenovateConfig,\n packageFiles: Record<string, PackageFile[]>,\n ): Promise<void> {\n const dependencyVulnerabilities = await this.fetchDependencyVulnerabilities(\n config,\n packageFiles,\n );\n\n config.packageRules ??= [];\n for (const {\n vulnerabilities,\n versioningApi,\n } of dependencyVulnerabilities) {\n const groupPackageRules: PackageRule[] = [];\n for (const vulnerability of vulnerabilities) {\n const rule = this.vulnerabilityToPackageRules(vulnerability);\n if (isNullOrUndefined(rule)) {\n continue;\n }\n groupPackageRules.push(rule);\n }\n this.sortByFixedVersion(groupPackageRules, versioningApi);\n\n config.packageRules.push(...groupPackageRules);\n }\n }\n\n async fetchVulnerabilities(\n config: RenovateConfig,\n packageFiles: Record<string, PackageFile[]>,\n ): Promise<Vulnerability[]> {\n const groups = await this.fetchDependencyVulnerabilities(\n config,\n packageFiles,\n );\n return groups.flatMap((group) => group.vulnerabilities);\n }\n\n private async fetchDependencyVulnerabilities(\n config: RenovateConfig,\n packageFiles: Record<string, PackageFile[]>,\n ): Promise<DependencyVulnerabilities[]> {\n const managers = Object.keys(packageFiles);\n const allManagerJobs = managers.map((manager) =>\n this.fetchManagerVulnerabilities(config, packageFiles, manager),\n );\n return (await Promise.all(allManagerJobs)).flat();\n }\n\n private async fetchManagerVulnerabilities(\n config: RenovateConfig,\n packageFiles: Record<string, PackageFile[]>,\n manager: string,\n ): Promise<DependencyVulnerabilities[]> {\n const managerConfig = getManagerConfig(config, manager);\n const queue = packageFiles[manager].map(\n (pFile) => (): Promise<DependencyVulnerabilities[]> =>\n this.fetchManagerPackageFileVulnerabilities(managerConfig, pFile),\n );\n logger.trace(\n { manager, queueLength: queue.length },\n 'fetchManagerVulnerabilities starting',\n );\n const result = (await p.all(queue)).flat();\n logger.trace({ manager }, 'fetchManagerVulnerabilities finished');\n return result;\n }\n\n private async fetchManagerPackageFileVulnerabilities(\n managerConfig: RenovateConfig,\n pFile: PackageFile,\n ): Promise<DependencyVulnerabilities[]> {\n const { packageFile } = pFile;\n const packageFileConfig = mergeChildConfig(managerConfig, pFile);\n const { manager } = packageFileConfig;\n const queue = pFile.deps.map(\n (dep) => (): Promise<DependencyVulnerabilities | null> =>\n this.fetchDependencyVulnerability(packageFileConfig, dep),\n );\n logger.trace(\n { manager, packageFile, queueLength: queue.length },\n 'fetchManagerPackageFileVulnerabilities starting with concurrency',\n );\n\n const result = await p.all(queue);\n logger.trace(\n { packageFile },\n 'fetchManagerPackageFileVulnerabilities finished',\n );\n\n return result.filter(isTruthy);\n }\n\n private async fetchDependencyVulnerability(\n packageFileConfig: RenovateConfig & PackageFile,\n dep: PackageDependency,\n ): Promise<DependencyVulnerabilities | null> {\n const ecosystem = Vulnerabilities.datasourceEcosystemMap[dep.datasource!];\n if (!ecosystem) {\n logger.trace(`Cannot map datasource ${dep.datasource!} to OSV ecosystem`);\n return null;\n }\n\n const packageName = dep.packageName!;\n let osvPackageName = packageName;\n let depType: string | undefined;\n if (ecosystem === 'PyPI') {\n // https://peps.python.org/pep-0503/#normalized-names\n osvPackageName = osvPackageName\n .toLowerCase()\n .replace(regEx(/[_.-]+/g), '-');\n } else if (ecosystem === 'Go' && packageName === 'go') {\n if (dep.depType !== 'toolchain') {\n // The `go` directive is source compatibility, not the build toolchain, so we skip it\n return null;\n }\n osvPackageName = 'stdlib';\n depType = dep.depType;\n }\n\n try {\n const osvVulnerabilities = await instrument(\n 'get OSV vulnerabilities',\n () => this.osvOffline.getVulnerabilities(ecosystem, osvPackageName),\n {\n attributes: {\n osvPackageName,\n ecosystem,\n },\n },\n );\n if (\n isNullOrUndefined(osvVulnerabilities) ||\n isEmptyArray(osvVulnerabilities)\n ) {\n logger.trace(\n `No vulnerabilities found in OSV database for ${packageName}`,\n );\n return null;\n }\n\n const depVersion =\n dep.lockedVersion ?? dep.currentVersion ?? dep.currentValue!;\n\n const versioning = dep.versioning ?? getDefaultVersioning(dep.datasource);\n const versioningApi = getVersioning(versioning);\n\n if (!versioningApi.isVersion(depVersion)) {\n logger.debug(\n `Skipping vulnerability lookup for package ${packageName} due to unsupported version ${depVersion}`,\n );\n return null;\n }\n\n const vulnerabilities: Vulnerability[] = [];\n for (const osvVulnerability of osvVulnerabilities) {\n if (osvVulnerability.withdrawn) {\n logger.trace(\n `Skipping withdrawn vulnerability ${osvVulnerability.id}`,\n );\n continue;\n }\n\n this.skipMaliciousPackages(\n ecosystem,\n osvPackageName,\n depVersion,\n versioningApi,\n dep,\n packageFileConfig.manager,\n packageFileConfig.packageFile,\n osvVulnerability,\n );\n\n for (const affected of coerceArray(osvVulnerability.affected)) {\n const isVulnerable = this.isPackageVulnerable(\n ecosystem,\n osvPackageName,\n depVersion,\n affected,\n versioningApi,\n );\n if (!isVulnerable) {\n continue;\n }\n\n logger.debug(\n `Vulnerability ${osvVulnerability.id} affects ${packageName} ${depVersion}`,\n );\n const fixedVersion = this.getFixedVersion(\n ecosystem,\n depVersion,\n affected,\n versioningApi,\n );\n\n vulnerabilities.push({\n packageName,\n osvPackageName,\n vulnerability: osvVulnerability,\n affected,\n depType,\n depVersion,\n versioning: dep.versioning,\n fixedVersion,\n datasource: dep.datasource!,\n packageFileConfig,\n });\n }\n }\n\n return { vulnerabilities, versioningApi };\n } catch (err) {\n logger.warn(\n { err, packageName },\n 'Error fetching vulnerability information for package',\n );\n return null;\n }\n }\n\n private skipMaliciousPackages(\n ecosystem: Ecosystem,\n osvPackageName: string,\n depVersion: string,\n versioningApi: VersioningApi,\n dep: PackageDependency,\n manager: string | undefined,\n packageFile: string,\n osvVulnerability: Osv.Vulnerability,\n ): void {\n // the OpenSSF's Malicious Packages (https://github.com/ossf/malicious-packages) is a source of advisories through osv.dev, which takes various sources of advisories, and will re-publish them with more specific information about their malicious usage\n if (osvVulnerability.id.startsWith('MAL-')) {\n // is the current dependency vulnerable?\n for (const affected of coerceArray(osvVulnerability.affected)) {\n // is the current dependency vulnerable?\n const isVulnerable = this.isPackageVulnerable(\n ecosystem,\n osvPackageName,\n depVersion,\n affected,\n versioningApi,\n );\n\n if (isVulnerable) {\n logger.debug(\n {\n packageFile: packageFile,\n depName: dep.depName,\n packageName: dep.packageName,\n manager: manager,\n datasource: dep.datasource,\n currentVersion: depVersion,\n },\n `Marking ${dep.depName} as skipReason=malicious-version-in-use, as it is affected by ${osvVulnerability.id}`,\n );\n dep.skipReason = 'malicious-version-in-use';\n dep.skipStage = 'lookup';\n }\n\n // or are any of the updates vulnerable?\n for (const update of coerceArray(dep.updates)) {\n const newVersion = update.newVersion ?? update.newValue!;\n\n const isUpdateVulnerable = this.isPackageVulnerable(\n ecosystem,\n osvPackageName,\n newVersion,\n affected,\n versioningApi,\n );\n\n if (isUpdateVulnerable) {\n logger.debug(\n {\n packageFile: packageFile,\n depName: dep.depName,\n packageName: dep.packageName,\n manager: manager,\n datasource: dep.datasource,\n currentVersion: depVersion,\n newVersion,\n },\n `Marking ${dep.depName}'s update to ${newVersion} as skipReason=malicious-update-proposed, as it is affected by ${osvVulnerability.id}`,\n );\n dep.skipReason = 'malicious-update-proposed';\n dep.skipStage = 'lookup';\n }\n }\n }\n }\n }\n\n private sortByFixedVersion(\n packageRules: PackageRule[],\n versioningApi: VersioningApi,\n ): void {\n const versionsCleaned: Record<string, string> = {};\n for (const rule of packageRules) {\n const version = rule.allowedVersions!;\n versionsCleaned[version] = version.replace(regEx(/[(),=> ]+/g), '');\n }\n packageRules.sort((a, b) =>\n versioningApi.sortVersions(\n versionsCleaned[a.allowedVersions!],\n versionsCleaned[b.allowedVersions!],\n ),\n );\n }\n\n // https://ossf.github.io/osv-schema/#affectedrangesevents-fields\n private sortEvents(\n events: Osv.Event[],\n versioningApi: VersioningApi,\n ): Osv.Event[] {\n const sortedCopy: Osv.Event[] = [];\n let zeroEvent: Osv.Event | null = null;\n\n for (const event of events) {\n if (event.introduced === '0') {\n zeroEvent = event;\n } else if (versioningApi.isVersion(Object.values(event)[0])) {\n sortedCopy.push(event);\n } else {\n logger.debug({ event }, 'Skipping OSV event with invalid version');\n }\n }\n\n sortedCopy.sort((a, b) =>\n // no pre-processing, as there are only very few values to sort\n versioningApi.sortVersions(Object.values(a)[0], Object.values(b)[0]),\n );\n\n if (zeroEvent) {\n sortedCopy.unshift(zeroEvent);\n }\n\n return sortedCopy;\n }\n\n private isPackageAffected(\n ecosystem: Ecosystem,\n osvPackageName: string,\n affected: Osv.Affected,\n ): boolean {\n const pkg = affected.package;\n if (pkg?.name !== osvPackageName) {\n return false;\n }\n\n // Match exact ecosystems and OSV sub-ecosystems (e.g. Packagist:https://packages.drupal.org/8).\n return (\n pkg.ecosystem === ecosystem || pkg.ecosystem.startsWith(`${ecosystem}:`)\n );\n }\n\n private includedInVersions(\n depVersion: string,\n affected: Osv.Affected,\n ): boolean {\n return !!affected.versions?.includes(depVersion);\n }\n\n private includedInRanges(\n depVersion: string,\n affected: Osv.Affected,\n versioningApi: VersioningApi,\n ): boolean {\n for (const range of coerceArray(affected.ranges)) {\n if (range.type === 'GIT') {\n continue;\n }\n\n let vulnerable = false;\n for (const event of this.sortEvents(range.events, versioningApi)) {\n if (\n isNonEmptyString(event.introduced) &&\n this.isIntroducedIn(depVersion, event.introduced, versioningApi)\n ) {\n vulnerable = true;\n } else if (\n isNonEmptyString(event.fixed) &&\n this.isVersionGtOrEq(depVersion, event.fixed, versioningApi)\n ) {\n vulnerable = false;\n } else if (\n isNonEmptyString(event.last_affected) &&\n this.isVersionGt(depVersion, event.last_affected, versioningApi)\n ) {\n vulnerable = false;\n }\n }\n\n if (vulnerable) {\n return true;\n }\n }\n\n return false;\n }\n\n private isIntroducedIn(\n depVersion: string,\n introduced: string,\n versioningApi: VersioningApi,\n ): boolean {\n return (\n introduced === '0' ||\n this.isVersionGtOrEq(depVersion, introduced, versioningApi)\n );\n }\n\n // https://ossf.github.io/osv-schema/#evaluation\n private isPackageVulnerable(\n ecosystem: Ecosystem,\n osvPackageName: string,\n depVersion: string,\n affected: Osv.Affected,\n versioningApi: VersioningApi,\n ): boolean {\n if (!this.isPackageAffected(ecosystem, osvPackageName, affected)) {\n return false;\n }\n return (\n this.includedInVersions(depVersion, affected) ||\n this.includedInRanges(depVersion, affected, versioningApi)\n );\n }\n\n private getFixedVersion(\n ecosystem: Ecosystem,\n depVersion: string,\n affected: Osv.Affected,\n versioningApi: VersioningApi,\n ): string | null {\n const fixedVersions: string[] = [];\n const lastAffectedVersions: string[] = [];\n\n for (const range of coerceArray(affected.ranges)) {\n if (range.type === 'GIT') {\n continue;\n }\n\n for (const event of range.events) {\n if (\n isNonEmptyString(event.fixed) &&\n versioningApi.isVersion(event.fixed)\n ) {\n fixedVersions.push(event.fixed);\n } else if (\n isNonEmptyString(event.last_affected) &&\n versioningApi.isVersion(event.last_affected)\n ) {\n lastAffectedVersions.push(event.last_affected);\n }\n }\n }\n\n fixedVersions.sort((a, b) => versioningApi.sortVersions(a, b));\n const fixedVersion = fixedVersions.find((version) =>\n this.isVersionGt(version, depVersion, versioningApi),\n );\n if (fixedVersion) {\n return this.getFixedVersionByEcosystem(fixedVersion, ecosystem);\n }\n\n lastAffectedVersions.sort((a, b) => versioningApi.sortVersions(a, b));\n const lastAffected = lastAffectedVersions.find((version) =>\n this.isVersionGtOrEq(version, depVersion, versioningApi),\n );\n if (lastAffected) {\n return this.getLastAffectedByEcosystem(lastAffected, ecosystem);\n }\n\n return null;\n }\n\n private getFixedVersionByEcosystem(\n fixedVersion: string,\n ecosystem: Ecosystem,\n ): string {\n return getFixedVersionConstraint(fixedVersion, ecosystem);\n }\n\n private getLastAffectedByEcosystem(\n lastAffected: string,\n ecosystem: Ecosystem,\n ): string {\n return getLastAffectedVersionConstraint(lastAffected, ecosystem);\n }\n\n private isVersionGt(\n version: string,\n other: string,\n versioningApi: VersioningApi,\n ): boolean {\n return (\n versioningApi.isVersion(version) &&\n versioningApi.isVersion(other) &&\n versioningApi.isGreaterThan(version, other)\n );\n }\n\n private isVersionGtOrEq(\n version: string,\n other: string,\n versioningApi: VersioningApi,\n ): boolean {\n return (\n versioningApi.isVersion(version) &&\n versioningApi.isVersion(other) &&\n this.isEqualOrGreater(version, other, versioningApi)\n );\n }\n\n private isEqualOrGreater(\n version: string,\n other: string,\n versioningApi: VersioningApi,\n ): boolean {\n return (\n versioningApi.equals(version, other) ||\n versioningApi.isGreaterThan(version, other)\n );\n }\n\n private vulnerabilityToPackageRules(vul: Vulnerability): PackageRule | null {\n const {\n vulnerability,\n affected,\n packageName,\n depType,\n depVersion,\n fixedVersion,\n datasource,\n versioning: depVersioning,\n packageFileConfig,\n } = vul;\n if (isNullOrUndefined(fixedVersion)) {\n logger.debug(\n `No fixed version available for vulnerability ${vulnerability.id} in ${packageName} ${depVersion}`,\n );\n return null;\n }\n\n // Prefer the `versioning` already assigned to the dependency by its manager\n const versioning = depVersioning ?? getDefaultVersioning(datasource);\n\n logger.debug(\n {\n datasource,\n versioning,\n },\n\n `Setting allowed version ${fixedVersion} to fix vulnerability ${vulnerability.id} in ${packageName} ${depVersion}`,\n );\n\n const severityDetails = this.extractSeverityDetails(\n vulnerability,\n affected,\n );\n\n return {\n matchDatasources: [datasource],\n matchPackageNames: [packageName],\n ...(depType ? { matchDepTypes: [depType] } : {}),\n matchCurrentVersion: depVersion,\n versioning,\n allowedVersions: fixedVersion,\n isVulnerabilityAlert: true,\n vulnerabilitySeverity: severityDetails.severityLevel,\n prBodyNotes: this.generatePrBodyNotes(vulnerability, affected),\n force: {\n ...packageFileConfig.vulnerabilityAlerts,\n },\n };\n }\n\n static evaluateCvssVector(vector: string): [string, string] {\n const CvssJson = z.object({\n baseScore: z.number().default(0.0),\n baseSeverity: z.string().toUpperCase().default('UNKNOWN'),\n });\n\n try {\n const parsedCvssScore: CvssVector<any> | null = fromVector(vector);\n const res = CvssJson.parse(parsedCvssScore?.createJsonSchema());\n\n return [res.baseScore.toFixed(1), res.baseSeverity];\n } catch {\n logger.debug(`Error processing CVSS vector ${vector}`);\n }\n\n return ['', ''];\n }\n\n private generatePrBodyNotes(\n vulnerability: Osv.Vulnerability,\n affected: Osv.Affected,\n ): string[] {\n let aliases = [vulnerability.id]\n .concat(coerceArray(vulnerability.aliases))\n .sort();\n aliases = aliases.map((id) => {\n if (id.startsWith('CVE-')) {\n return `[${id}](https://nvd.nist.gov/vuln/detail/${id})`;\n }\n if (id.startsWith('GHSA-')) {\n return `[${id}](https://github.com/advisories/${id})`;\n }\n if (id.startsWith('GO-')) {\n return `[${id}](https://pkg.go.dev/vuln/${id})`;\n }\n if (id.startsWith('RUSTSEC-')) {\n return `[${id}](https://rustsec.org/advisories/${id}.html)`;\n }\n\n return id;\n });\n\n let content = '\\n\\n---\\n\\n### ';\n content += vulnerability.summary ? `${vulnerability.summary}\\n` : '';\n content += `${aliases.join(' / ')}\\n`;\n content += `\\n<details>\\n<summary>More information</summary>\\n`;\n\n const details = vulnerability.details?.replace(\n regEx(/^#{1,4} /gm),\n '##### ',\n );\n content += `#### Details\\n${details ?? 'No details.'}\\n`;\n\n content += '#### Severity\\n';\n const severityDetails = this.extractSeverityDetails(\n vulnerability,\n affected,\n );\n\n if (severityDetails.cvssVector) {\n content += `- CVSS Score: ${severityDetails.score}\\n`;\n content += `- Vector String: \\`${severityDetails.cvssVector}\\`\\n`;\n } else {\n content += `${titleCase(severityDetails.severityLevel)}\\n`;\n }\n\n content += `\\n#### References\\n${\n vulnerability.references\n ?.map((ref) => {\n return `- [${ref.url}](${ref.url})`;\n })\n .join('\\n') ?? 'No references.'\n }`;\n\n let attribution = '';\n if (vulnerability.id.startsWith('GHSA-')) {\n attribution = ` and the [GitHub Advisory Database](https://github.com/github/advisory-database) ([CC-BY 4.0](https://github.com/github/advisory-database/blob/main/LICENSE.md))`;\n } else if (vulnerability.id.startsWith('GO-')) {\n attribution = ` and the [Go Vulnerability Database](https://github.com/golang/vulndb) ([CC-BY 4.0](https://github.com/golang/vulndb#license))`;\n } else if (vulnerability.id.startsWith('PYSEC-')) {\n attribution = ` and the [PyPI Advisory Database](https://github.com/pypa/advisory-database) ([CC-BY 4.0](https://github.com/pypa/advisory-database/blob/main/LICENSE))`;\n } else if (vulnerability.id.startsWith('RUSTSEC-')) {\n attribution = ` and the [Rust Advisory Database](https://github.com/RustSec/advisory-db) ([CC0 1.0](https://github.com/rustsec/advisory-db/blob/main/LICENSE.txt))`;\n }\n content += `\\n\\nThis data is provided by [OSV](https://osv.dev/vulnerability/${vulnerability.id})${attribution}.\\n`;\n content += `</details>`;\n\n return [sanitizeMarkdown(content)];\n }\n\n private extractSeverityDetails(\n vulnerability: Osv.Vulnerability,\n affected: Osv.Affected,\n ): SeverityDetails {\n let severityLevel = 'UNKNOWN';\n let score = 'Unknown';\n\n const cvssVector =\n vulnerability.severity?.find((e) => e.type === 'CVSS_V4')?.score ??\n vulnerability.severity?.find((e) => e.type === 'CVSS_V3')?.score ??\n (affected.database_specific?.cvss as string); // RUSTSEC\n\n if (cvssVector) {\n const [baseScore, severity] =\n Vulnerabilities.evaluateCvssVector(cvssVector);\n severityLevel = severity ? severity.toUpperCase() : 'UNKNOWN';\n score = baseScore\n ? `${baseScore} / 10 (${titleCase(severityLevel)})`\n : 'Unknown';\n } else if (\n vulnerability.id.startsWith('GHSA-') &&\n vulnerability.database_specific?.severity\n ) {\n const severity = vulnerability.database_specific.severity as string;\n severityLevel = severity.toUpperCase();\n }\n\n return {\n cvssVector,\n score,\n severityLevel,\n };\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;AAwCA,MAAM,E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AW;EAEX,OAAO,CAAC,iBAAiB,OAAO,CAAC;CACnC;CAEA,uBACE,eACA,UACiB;EACjB,IAAI,gBAAgB;EACpB,IAAI,QAAQ;EAEZ,MAAM,aACJ,cAAc,UAAU,MAAM,MAAM,EAAE,SAAS,SAAS,CAAC,EAAE,SAC3D,cAAc,UAAU,MAAM,MAAM,EAAE,SAAS,SAAS,CAAC,EAAE,SAC1D,SAAS,mBAAmB;EAE/B,IAAI,YAAY;GACd,MAAM,CAAC,WAAW,YAChB,gBAAgB,mBAAmB,UAAU;GAC/C,gBAAgB,WAAW,SAAS,YAAY,IAAI;GACpD,QAAQ,YACJ,GAAG,UAAU,SAAS,UAAU,aAAa,EAAE,KAC/C;EACN,OAAO,IACL,cAAc,GAAG,WAAW,OAAO,KACnC,cAAc,mBAAmB,UAGjC,gBADiB,cAAc,kBAAkB,SACxB,YAAY;EAGvC,OAAO;GACL;GACA;GACA;EACF;CACF;AACF"}
|
|
@@ -38,7 +38,8 @@ async function checkReconfigureBranch(config, repoConfig) {
|
|
|
38
38
|
reconfigureCache.extractionSucceeded = true;
|
|
39
39
|
delete reconfigureCache.extractResult;
|
|
40
40
|
}
|
|
41
|
-
|
|
41
|
+
const isCacheUsable = !existingPr || reconfigureCache?.extractionSucceeded;
|
|
42
|
+
if (reconfigureCache?.reconfigureBranchSha === branchSha && isCacheUsable) {
|
|
42
43
|
logger.debug("Skipping validation check as branch sha is unchanged");
|
|
43
44
|
return;
|
|
44
45
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":[],"sources":["../../../../lib/workers/repository/reconfigure/index.ts"],"sourcesContent":["import { GlobalConfig } from '../../../config/global.ts';\nimport { applySecretsAndVariablesToConfig } from '../../../config/secrets.ts';\nimport type { AllConfig, RenovateConfig } from '../../../config/types.ts';\nimport { logger } from '../../../logger/index.ts';\nimport { platform } from '../../../modules/platform/index.ts';\nimport { scm } from '../../../modules/platform/scm.ts';\nimport { getCache } from '../../../util/cache/repository/index.ts';\nimport { getBranchCommit } from '../../../util/git/index.ts';\nimport { mergeInheritedConfig } from '../init/inherited.ts';\nimport { mergeRenovateConfig } from '../init/merge.ts';\nimport type { ExtractResult } from '../process/extract-update.ts';\nimport { extractDependencies } from '../process/index.ts';\nimport { ensureReconfigurePrComment } from './comment.ts';\nimport {\n deleteReconfigureBranchCache,\n setReconfigureBranchCache,\n} from './reconfigure-cache.ts';\nimport {\n getReconfigureBranchName,\n getReconfigureConfig,\n setBranchStatus,\n} from './utils.ts';\nimport { validateReconfigureBranch } from './validate.ts';\n\nexport async function checkReconfigureBranch(\n config: RenovateConfig,\n repoConfig: AllConfig,\n): Promise<void> {\n logger.debug('checkReconfigureBranch()');\n if (GlobalConfig.get('platform') === 'local') {\n logger.debug(\n 'Not attempting to reconfigure when running with local platform',\n );\n return;\n }\n\n const context = config.statusCheckNames?.configValidation;\n const reconfigureBranch = getReconfigureBranchName(config.branchPrefix!);\n const branchExists = await scm.branchExists(reconfigureBranch);\n\n // this is something the user initiates, skip if no branch exists\n if (!branchExists) {\n logger.debug({ reconfigureBranch }, 'No reconfigure branch found');\n deleteReconfigureBranchCache(); // in order to remove cache when the branch has been deleted\n return;\n }\n\n const existingPr = await platform.findPr({\n branchName: reconfigureBranch,\n state: 'open',\n includeOtherAuthors: true,\n targetBranch: config.defaultBranch,\n });\n const branchSha = getBranchCommit(reconfigureBranch)!;\n const cache = getCache();\n const reconfigureCache = cache.reconfigureBranchCache;\n // migrate the extract result persisted by earlier versions\n if (reconfigureCache?.extractResult) {\n reconfigureCache.extractionSucceeded = true;\n delete reconfigureCache.extractResult;\n }\n\n // only use valid cached information\n if (
|
|
1
|
+
{"version":3,"file":"index.js","names":[],"sources":["../../../../lib/workers/repository/reconfigure/index.ts"],"sourcesContent":["import { GlobalConfig } from '../../../config/global.ts';\nimport { applySecretsAndVariablesToConfig } from '../../../config/secrets.ts';\nimport type { AllConfig, RenovateConfig } from '../../../config/types.ts';\nimport { logger } from '../../../logger/index.ts';\nimport { platform } from '../../../modules/platform/index.ts';\nimport { scm } from '../../../modules/platform/scm.ts';\nimport { getCache } from '../../../util/cache/repository/index.ts';\nimport { getBranchCommit } from '../../../util/git/index.ts';\nimport { mergeInheritedConfig } from '../init/inherited.ts';\nimport { mergeRenovateConfig } from '../init/merge.ts';\nimport type { ExtractResult } from '../process/extract-update.ts';\nimport { extractDependencies } from '../process/index.ts';\nimport { ensureReconfigurePrComment } from './comment.ts';\nimport {\n deleteReconfigureBranchCache,\n setReconfigureBranchCache,\n} from './reconfigure-cache.ts';\nimport {\n getReconfigureBranchName,\n getReconfigureConfig,\n setBranchStatus,\n} from './utils.ts';\nimport { validateReconfigureBranch } from './validate.ts';\n\nexport async function checkReconfigureBranch(\n config: RenovateConfig,\n repoConfig: AllConfig,\n): Promise<void> {\n logger.debug('checkReconfigureBranch()');\n if (GlobalConfig.get('platform') === 'local') {\n logger.debug(\n 'Not attempting to reconfigure when running with local platform',\n );\n return;\n }\n\n const context = config.statusCheckNames?.configValidation;\n const reconfigureBranch = getReconfigureBranchName(config.branchPrefix!);\n const branchExists = await scm.branchExists(reconfigureBranch);\n\n // this is something the user initiates, skip if no branch exists\n if (!branchExists) {\n logger.debug({ reconfigureBranch }, 'No reconfigure branch found');\n deleteReconfigureBranchCache(); // in order to remove cache when the branch has been deleted\n return;\n }\n\n const existingPr = await platform.findPr({\n branchName: reconfigureBranch,\n state: 'open',\n includeOtherAuthors: true,\n targetBranch: config.defaultBranch,\n });\n const branchSha = getBranchCommit(reconfigureBranch)!;\n const cache = getCache();\n const reconfigureCache = cache.reconfigureBranchCache;\n // migrate the extract result persisted by earlier versions\n if (reconfigureCache?.extractResult) {\n reconfigureCache.extractionSucceeded = true;\n delete reconfigureCache.extractResult;\n }\n\n // only use valid cached information\n const isCacheUsable = !existingPr || reconfigureCache?.extractionSucceeded;\n if (reconfigureCache?.reconfigureBranchSha === branchSha && isCacheUsable) {\n logger.debug('Skipping validation check as branch sha is unchanged');\n return;\n }\n\n const result = await getReconfigureConfig(reconfigureBranch);\n\n if (!result.ok) {\n await setBranchStatus(reconfigureBranch, result.errMessage, 'red', context);\n setReconfigureBranchCache(branchSha, false);\n await scm.checkoutBranch(config.defaultBranch!);\n return;\n }\n\n const isValidConfig = await validateReconfigureBranch(\n config,\n result.config,\n result.configFileName,\n existingPr,\n );\n\n if (!isValidConfig) {\n logger.debug(\n 'Found errors in reconfigure config. Skipping dependencies extraction',\n );\n await scm.checkoutBranch(config.defaultBranch!);\n return;\n }\n\n if (!existingPr) {\n logger.debug('No reconfigure pr found. Skipping dependencies extraction');\n await scm.checkoutBranch(config.defaultBranch!);\n return;\n }\n\n let extractResult: ExtractResult;\n // Recompute config similar to repo config processing\n // Get non-global config from file config\n // Merge it with inherited and static repo config\n // Finally, merge the reconfigure config\n let newConfig = GlobalConfig.set(\n applySecretsAndVariablesToConfig({\n config: repoConfig,\n }),\n );\n newConfig.defaultBranch = config.defaultBranch;\n newConfig.baseBranch = config.defaultBranch;\n newConfig.repoIsOnboarded = true;\n newConfig.errors = [];\n newConfig.warnings = [];\n\n try {\n newConfig = await mergeInheritedConfig(newConfig);\n newConfig = await mergeRenovateConfig(newConfig, reconfigureBranch);\n await scm.checkoutBranch(config.defaultBranch!);\n extractResult = await extractDependencies(newConfig, false);\n } catch (err) {\n logger.debug(\n { err },\n 'Error while extracting dependencies using the reconfigure config',\n );\n setReconfigureBranchCache(branchSha, true);\n await scm.checkoutBranch(config.defaultBranch!); // being cautious\n return;\n }\n\n const commentEnsured = await ensureReconfigurePrComment(\n newConfig,\n extractResult.packageFiles,\n extractResult.branches,\n reconfigureBranch,\n existingPr,\n );\n\n await setBranchStatus(\n reconfigureBranch,\n 'Validation Successful',\n 'green',\n context,\n );\n // if comment is not added or updated, re-process the reconfigure branch on next run and do not skip\n setReconfigureBranchCache(branchSha, true, commentEnsured);\n await scm.checkoutBranch(config.defaultBranch!); //being cautious\n}\n"],"mappings":";;;;;;;;;;;;;;;AAwBA,eAAsB,uBACpB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;CACjC,UAAU,aAAa,OAAO;CAC9B,UAAU,kBAAkB;CAC5B,UAAU,SAAS,CAAC;CACpB,UAAU,WAAW,CAAC;CAEtB,IAAI;EACF,YAAY,MAAM,qBAAqB,SAAS;EAChD,YAAY,MAAM,oBAAoB,WAAW,iBAAiB;EAClE,MAAM,IAAI,eAAe,OAAO,aAAc;EAC9C,gBAAgB,MAAM,oBAAoB,WAAW,KAAK;CAC5D,SAAS,KAAK;EACZ,OAAO,MACL,EAAE,IAAI,GACN,kEACF;EACA,0BAA0B,WAAW,IAAI;EACzC,MAAM,IAAI,eAAe,OAAO,aAAc;EAC9C;CACF;CAEA,MAAM,iBAAiB,MAAM,2BAC3B,WACA,cAAc,cACd,cAAc,UACd,mBACA,UACF;CAEA,MAAM,gBACJ,mBACA,yBACA,SACA,OACF;CAEA,0BAA0B,WAAW,MAAM,cAAc;CACzD,MAAM,IAAI,eAAe,OAAO,aAAc;AAChD"}
|
|
@@ -85,7 +85,8 @@ async function confirmIfDepUpdated(upgrade, newContent) {
|
|
|
85
85
|
return false;
|
|
86
86
|
}
|
|
87
87
|
}
|
|
88
|
-
|
|
88
|
+
const isPinOrDigestUpdate = upgrade.isPinDigest === true || upgrade.currentDigest;
|
|
89
|
+
if (upgrade.newDigest && isPinOrDigestUpdate && upgrade.newDigest !== newUpgrade.currentDigest) {
|
|
89
90
|
logger.debug({
|
|
90
91
|
depName: upgrade.depName,
|
|
91
92
|
manager,
|
|
@@ -140,12 +141,15 @@ async function checkExistingBranch(upgrade, existingContent) {
|
|
|
140
141
|
logger.debug(`Branch dep ${depName} in ${packageFile} is already updated`);
|
|
141
142
|
return existingContent;
|
|
142
143
|
}
|
|
144
|
+
function isMissingDepName(replaceString, depName) {
|
|
145
|
+
return isUndefined(replaceString) || !replaceString.includes(depName);
|
|
146
|
+
}
|
|
143
147
|
async function doAutoReplace(upgrade, existingContent, reuseExistingBranch, firstUpdate = true) {
|
|
144
148
|
const { packageFile, depName, depNameTemplate, newName, currentValue, currentValueTemplate, newValue, currentDigest, currentDigestShort, newDigest, autoReplaceGlobalMatch, autoReplaceStringTemplate } = upgrade;
|
|
145
149
|
if (reuseExistingBranch) return await checkExistingBranch(upgrade, existingContent);
|
|
146
150
|
const valueChanging = isString(currentValue) && isString(newValue) && currentValue !== newValue;
|
|
147
151
|
const digestChanging = isString(currentDigest) && isString(newDigest) && currentDigest !== newDigest;
|
|
148
|
-
let replaceWithoutReplaceString = isString(newName) && newName !== depName && (
|
|
152
|
+
let replaceWithoutReplaceString = isString(newName) && newName !== depName && isMissingDepName(upgrade.replaceString, depName);
|
|
149
153
|
let replaceString = upgrade.replaceString;
|
|
150
154
|
if (isUndefined(replaceString)) {
|
|
151
155
|
if (valueChanging && digestChanging) {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"auto-replace.js","names":[],"sources":["../../../../../lib/workers/repository/update/branch/auto-replace.ts"],"sourcesContent":["// TODO #22198\nimport { isNumber, isString, isUndefined } from '@sindresorhus/is';\nimport { WORKER_FILE_UPDATE_FAILED } from '../../../../constants/error-messages.ts';\nimport { logger } from '../../../../logger/index.ts';\nimport { extractPackageFile } from '../../../../modules/manager/index.ts';\nimport type { PackageDependency } from '../../../../modules/manager/types.ts';\nimport { writeLocalFile } from '../../../../util/fs/index.ts';\nimport { regEx } from '../../../../util/regex.ts';\nimport { matchAt, replaceAt } from '../../../../util/string.ts';\nimport { compile } from '../../../../util/template/index.ts';\nimport type { BranchUpgradeConfig } from '../../../types.ts';\nimport { normalizeDepNames } from '../../extract/manager-files.ts';\n\nexport async function confirmIfDepUpdated(\n upgrade: BranchUpgradeConfig,\n newContent: string,\n): Promise<boolean> {\n const { manager, packageFile, depIndex } = upgrade;\n let newUpgrade: PackageDependency;\n try {\n const newExtract = await extractPackageFile(\n manager,\n newContent,\n packageFile!,\n upgrade,\n );\n // istanbul ignore if\n if (!newExtract) {\n // TODO: fix types (#22198)\n logger.debug(\n `Could not extract ${packageFile!} (manager=${manager}) after autoreplace. Did the autoreplace make the file unparseable?`,\n );\n logger.trace(\n { packageFile, content: newContent },\n 'packageFile content after autoreplace',\n );\n return false;\n }\n // istanbul ignore if\n if (!newExtract.deps?.length) {\n logger.debug(\n `Extracted ${packageFile!} after autoreplace has no deps array. Did the autoreplace make the file unparseable?`,\n );\n return false;\n }\n // istanbul ignore if\n if (isNumber(depIndex) && depIndex >= newExtract.deps.length) {\n logger.debug(\n `Extracted ${packageFile!} after autoreplace has fewer deps than expected.`,\n );\n return false;\n }\n newUpgrade = newExtract.deps[depIndex!];\n } catch (err) {\n /* istanbul ignore next */\n logger.debug({ manager, packageFile, err }, 'Failed to parse newContent');\n }\n\n if (!newUpgrade!) {\n logger.debug(`No newUpgrade in ${packageFile!}`);\n return false;\n }\n\n if (\n upgrade.depName !== newUpgrade.depName &&\n upgrade.newName !== newUpgrade.depName\n ) {\n logger.debug(\n {\n manager,\n packageFile,\n currentDepName: upgrade.depName,\n newDepName: newUpgrade.depName,\n },\n 'depName mismatch',\n );\n return false;\n }\n\n if (upgrade.newName && upgrade.newName !== newUpgrade.depName) {\n logger.debug(\n {\n manager,\n packageFile,\n currentDepName: upgrade.depName,\n newDepName: newUpgrade.depName,\n },\n 'depName is not updated',\n );\n return false;\n }\n\n if (upgrade.newValue && upgrade.newValue !== newUpgrade.currentValue) {\n // accept reshaped values produced by autoReplaceStringTemplate\n let templateMatchesExtractedValue = false;\n if (upgrade.autoReplaceStringTemplate) {\n try {\n const compiledValue = compile(\n upgrade.autoReplaceStringTemplate,\n upgrade,\n false,\n );\n templateMatchesExtractedValue =\n compiledValue === newUpgrade.currentValue;\n } catch (err) {\n logger.debug(\n { err, manager, packageFile },\n 'Failed to compile autoReplaceStringTemplate in confirmIfDepUpdated',\n );\n }\n }\n if (!templateMatchesExtractedValue) {\n logger.debug(\n {\n depName: upgrade.depName,\n manager,\n packageFile,\n expectedValue: upgrade.newValue,\n foundValue: newUpgrade.currentValue,\n },\n 'Value is not updated',\n );\n return false;\n }\n }\n\n if (\n upgrade.newDigest &&\n (upgrade.isPinDigest === true || upgrade.currentDigest) &&\n upgrade.newDigest !== newUpgrade.currentDigest\n ) {\n logger.debug(\n {\n depName: upgrade.depName,\n manager,\n packageFile,\n expectedValue: upgrade.newDigest,\n foundValue: newUpgrade.currentDigest,\n },\n 'Digest is not updated',\n );\n return false;\n }\n\n return true;\n}\n\nfunction getDepsSignature(deps: PackageDependency[]): string {\n // TODO: types (#22198)\n return deps.map((dep) => `${dep.depName!}${dep.packageName!}`).join(',');\n}\n\nfunction firstIndexOf(\n existingContent: string,\n depName: string,\n currentValue: string,\n position = 0,\n): number {\n const depIndex = existingContent.indexOf(depName, position);\n const valIndex = existingContent.indexOf(currentValue, position);\n const index = depIndex < valIndex ? depIndex : valIndex;\n if (index < 0) {\n return position === 0 ? -1 : existingContent.length;\n }\n return index;\n}\n\nexport async function checkBranchDepsMatchBaseDeps(\n upgrade: BranchUpgradeConfig,\n branchContent: string,\n): Promise<boolean> {\n const { baseDeps, manager, packageFile } = upgrade;\n try {\n const res = await extractPackageFile(\n manager,\n branchContent,\n packageFile!,\n upgrade,\n )!;\n const branchDeps = res!.deps;\n // `baseDeps` were normalized during extraction, so the freshly extracted `branchDeps` need the same treatment before their signatures can be compared\n for (const dep of branchDeps) {\n normalizeDepNames(dep);\n }\n return getDepsSignature(baseDeps!) === getDepsSignature(branchDeps);\n } catch /* istanbul ignore next */ {\n logger.info(\n { manager, packageFile },\n 'Failed to parse branchContent - rebasing',\n );\n return false;\n }\n}\n\nasync function checkExistingBranch(\n upgrade: BranchUpgradeConfig,\n existingContent: string,\n): Promise<string | null> {\n const { packageFile, depName } = upgrade;\n if (!(await checkBranchDepsMatchBaseDeps(upgrade, existingContent))) {\n logger.debug(\n { packageFile, depName },\n 'Rebasing branch after deps list has changed',\n );\n return null;\n }\n if (!(await confirmIfDepUpdated(upgrade, existingContent))) {\n logger.debug(\n { packageFile, depName },\n 'Rebasing after outdated branch dep found',\n );\n return null;\n }\n // TODO: fix types (#22198)\n logger.debug(`Branch dep ${depName!} in ${packageFile!} is already updated`);\n return existingContent;\n}\n\nexport async function doAutoReplace(\n upgrade: BranchUpgradeConfig,\n existingContent: string,\n reuseExistingBranch: boolean,\n firstUpdate = true,\n): Promise<string | null> {\n const {\n packageFile,\n depName,\n depNameTemplate,\n newName,\n currentValue,\n currentValueTemplate,\n newValue,\n currentDigest,\n currentDigestShort,\n newDigest,\n autoReplaceGlobalMatch,\n autoReplaceStringTemplate,\n } = upgrade;\n /*\n If replacement support for more managers is added,\n please also update the list in docs/usage/configuration-options.md\n at replacementName and replacementVersion\n */\n if (reuseExistingBranch) {\n return await checkExistingBranch(upgrade, existingContent);\n }\n const valueChanging =\n isString(currentValue) && isString(newValue) && currentValue !== newValue;\n const digestChanging =\n isString(currentDigest) &&\n isString(newDigest) &&\n currentDigest !== newDigest;\n let replaceWithoutReplaceString =\n isString(newName) &&\n newName !== depName &&\n (isUndefined(upgrade.replaceString) ||\n !upgrade.replaceString?.includes(depName!));\n // fallback must contain the field being updated, else the replacement is\n // a no-op for managers where value and digest live in separate tokens\n let replaceString = upgrade.replaceString;\n if (isUndefined(replaceString)) {\n if (valueChanging && digestChanging) {\n // no single fallback covers both — use the per-field path\n replaceWithoutReplaceString = true;\n replaceString = currentValue;\n } else if (digestChanging) {\n replaceString = currentDigest;\n } else {\n replaceString = currentValue ?? currentDigest;\n }\n }\n logger.trace({ depName, replaceString }, 'autoReplace replaceString');\n let searchIndex: number;\n if (replaceWithoutReplaceString) {\n searchIndex = firstIndexOf(existingContent, depName!, currentValue!);\n } else {\n searchIndex = existingContent.indexOf(replaceString!);\n }\n if (searchIndex === -1) {\n logger.info(\n { packageFile, depName, existingContent, replaceString },\n 'Cannot find replaceString in current file content. Was it already updated?',\n );\n return existingContent;\n }\n try {\n let newString: string;\n if (autoReplaceStringTemplate && !newName) {\n newString = compile(autoReplaceStringTemplate, upgrade, false);\n } else {\n newString = replaceString!;\n\n const autoReplaceRegExpFlag = autoReplaceGlobalMatch ? 'g' : '';\n if (currentValue && newValue && currentValue !== newValue) {\n if (!newString.includes(currentValue)) {\n logger.debug(\n { stringToReplace: newString, currentValue, currentValueTemplate },\n 'currentValue not found in string to replace',\n );\n }\n newString = newString.replace(\n regEx(RegExp.escape(currentValue), autoReplaceRegExpFlag),\n newValue,\n );\n }\n if (depName && newName && depName !== newName) {\n if (!newString.includes(depName)) {\n logger.debug(\n { stringToReplace: newString, depName, depNameTemplate },\n 'depName not found in string to replace',\n );\n }\n newString = newString.replace(\n regEx(RegExp.escape(depName), autoReplaceRegExpFlag),\n newName,\n );\n }\n if (currentDigest && newDigest && currentDigest !== newDigest) {\n if (!newString.includes(currentDigest)) {\n logger.debug(\n { stringToReplace: newString, currentDigest },\n 'currentDigest not found in string to replace',\n );\n }\n newString = newString.replace(\n regEx(RegExp.escape(currentDigest), autoReplaceRegExpFlag),\n newDigest,\n );\n } else if (\n currentDigestShort &&\n newDigest &&\n currentDigestShort !== newDigest &&\n // Only use short digest replacement when there's no full currentDigest\n // that already matches newDigest (otherwise we'd incorrectly replace\n // part of an already-correct digest)\n !(currentDigest && currentDigest === newDigest)\n ) {\n if (!newString.includes(currentDigestShort)) {\n logger.debug(\n { stringToReplace: newString, currentDigestShort },\n 'currentDigestShort not found in string to replace',\n );\n }\n newString = newString.replace(\n regEx(RegExp.escape(currentDigestShort), autoReplaceRegExpFlag),\n newDigest,\n );\n }\n }\n if (!firstUpdate && (await confirmIfDepUpdated(upgrade, existingContent))) {\n logger.debug(\n { packageFile, depName },\n 'Package file is already updated - no work to do',\n );\n return existingContent;\n }\n logger.debug(\n { packageFile, depName },\n `Starting search at index ${searchIndex}`,\n );\n let newContent = existingContent;\n let nameReplaced = !newName;\n let valueReplaced = !newValue;\n let digestReplaced = !newDigest;\n let startIndex = searchIndex;\n // Iterate through the rest of the file\n for (; searchIndex < newContent.length; searchIndex += 1) {\n // First check if we have a hit for the old version\n if (replaceWithoutReplaceString) {\n // look for depName and currentValue\n if (newName && matchAt(newContent, searchIndex, depName!)) {\n logger.debug(\n { packageFile, depName },\n `Found depName at index ${searchIndex}`,\n );\n if (nameReplaced) {\n startIndex = firstIndexOf(\n existingContent,\n depName!,\n currentValue!,\n startIndex + 1,\n );\n searchIndex = startIndex - 1;\n await writeLocalFile(upgrade.packageFile!, existingContent);\n newContent = existingContent;\n nameReplaced = !newName;\n valueReplaced = !newValue;\n digestReplaced = !newDigest;\n continue;\n }\n // replace with newName\n newContent = replaceAt(newContent, searchIndex, depName!, newName);\n await writeLocalFile(upgrade.packageFile!, newContent);\n nameReplaced = true;\n searchIndex += newName.length - 1;\n } else if (\n newValue &&\n matchAt(newContent, searchIndex, currentValue!)\n ) {\n logger.debug(\n { packageFile, currentValue },\n `Found currentValue at index ${searchIndex}`,\n );\n if (valueReplaced) {\n startIndex = firstIndexOf(\n existingContent,\n depName!,\n currentValue!,\n startIndex + 1,\n );\n searchIndex = startIndex - 1;\n await writeLocalFile(upgrade.packageFile!, existingContent);\n newContent = existingContent;\n nameReplaced = !newName;\n valueReplaced = !newValue;\n digestReplaced = !newDigest;\n continue;\n }\n // Now test if the result matches\n newContent = replaceAt(\n newContent,\n searchIndex,\n currentValue!,\n newValue,\n );\n await writeLocalFile(upgrade.packageFile!, newContent);\n valueReplaced = true;\n searchIndex += newValue.length - 1;\n } else if (\n newDigest &&\n matchAt(newContent, searchIndex, currentDigest!)\n ) {\n logger.debug(\n { packageFile, currentDigest },\n `Found currentDigest at index ${searchIndex}`,\n );\n if (digestReplaced) {\n startIndex = firstIndexOf(\n existingContent,\n depName!,\n currentValue!,\n startIndex + 1,\n );\n searchIndex = startIndex - 1;\n await writeLocalFile(upgrade.packageFile!, existingContent);\n newContent = existingContent;\n nameReplaced = !newName;\n valueReplaced = !newValue;\n digestReplaced = !newDigest;\n continue;\n }\n // Now test if the result matches\n newContent = replaceAt(\n newContent,\n searchIndex,\n currentDigest!,\n newDigest,\n );\n await writeLocalFile(upgrade.packageFile!, newContent);\n digestReplaced = true;\n searchIndex += newDigest.length - 1;\n }\n if (nameReplaced && valueReplaced && digestReplaced) {\n if (await confirmIfDepUpdated(upgrade, newContent)) {\n return newContent;\n }\n startIndex = firstIndexOf(\n existingContent,\n depName!,\n currentValue!,\n startIndex + 1,\n );\n searchIndex = startIndex - 1;\n await writeLocalFile(upgrade.packageFile!, existingContent);\n newContent = existingContent;\n nameReplaced = !newName;\n valueReplaced = !newValue;\n digestReplaced = !newDigest;\n }\n } else if (matchAt(newContent, searchIndex, replaceString!)) {\n logger.debug(\n { packageFile, depName },\n `Found match at index ${searchIndex}`,\n );\n // Now test if the result matches\n newContent = replaceAt(\n newContent,\n searchIndex,\n replaceString!,\n newString,\n );\n await writeLocalFile(upgrade.packageFile!, newContent);\n if (await confirmIfDepUpdated(upgrade, newContent)) {\n return newContent;\n }\n await writeLocalFile(upgrade.packageFile!, existingContent);\n newContent = existingContent;\n }\n }\n } catch (err) {\n /* istanbul ignore next */\n logger.debug({ packageFile, depName, err }, 'doAutoReplace error');\n }\n // istanbul ignore next\n throw new Error(WORKER_FILE_UPDATE_FAILED);\n}\n"],"mappings":";;;;;;;;;;AAaA,eAAsB,oBACpB,SACA,YACkB;CAClB,MAAM,EAAE,SAAS,aAAa,aAAa;CAC3C,IAAI;CACJ,IAAI;EACF,MAAM,aAAa,MAAM,mBACvB,SACA,YACA,aACA,OACF;;EAEA,IAAI,CAAC,YAAY;GAEf,OAAO,MACL,qBAAqB,YAAa,YAAY,QAAQ,oEACxD;GACA,OAAO,MACL;IAAE;IAAa,SAAS;GAAW,GACnC,uCACF;GACA,OAAO;EACT;;EAEA,IAAI,CAAC,WAAW,MAAM,QAAQ;GAC5B,OAAO,MACL,aAAa,YAAa,qFAC5B;GACA,OAAO;EACT;;EAEA,IAAI,SAAS,QAAQ,KAAK,YAAY,WAAW,KAAK,QAAQ;GAC5D,OAAO,MACL,aAAa,YAAa,iDAC5B;GACA,OAAO;EACT;EACA,aAAa,WAAW,KAAK;CAC/B,SAAS,KAAK;;EAEZ,O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O,MAAM;GAAE;GAAa;GAAS;EAAI,GAAG,qBAAqB;CACnE;;CAEA,MAAM,IAAI,MAAM,yBAAyB;AAC3C"}
|
|
1
|
+
{"version":3,"file":"auto-replace.js","names":[],"sources":["../../../../../lib/workers/repository/update/branch/auto-replace.ts"],"sourcesContent":["// TODO #22198\nimport { isNumber, isString, isUndefined } from '@sindresorhus/is';\nimport { WORKER_FILE_UPDATE_FAILED } from '../../../../constants/error-messages.ts';\nimport { logger } from '../../../../logger/index.ts';\nimport { extractPackageFile } from '../../../../modules/manager/index.ts';\nimport type { PackageDependency } from '../../../../modules/manager/types.ts';\nimport { writeLocalFile } from '../../../../util/fs/index.ts';\nimport { regEx } from '../../../../util/regex.ts';\nimport { matchAt, replaceAt } from '../../../../util/string.ts';\nimport { compile } from '../../../../util/template/index.ts';\nimport type { BranchUpgradeConfig } from '../../../types.ts';\nimport { normalizeDepNames } from '../../extract/manager-files.ts';\n\nexport async function confirmIfDepUpdated(\n upgrade: BranchUpgradeConfig,\n newContent: string,\n): Promise<boolean> {\n const { manager, packageFile, depIndex } = upgrade;\n let newUpgrade: PackageDependency;\n try {\n const newExtract = await extractPackageFile(\n manager,\n newContent,\n packageFile!,\n upgrade,\n );\n // istanbul ignore if\n if (!newExtract) {\n // TODO: fix types (#22198)\n logger.debug(\n `Could not extract ${packageFile!} (manager=${manager}) after autoreplace. Did the autoreplace make the file unparseable?`,\n );\n logger.trace(\n { packageFile, content: newContent },\n 'packageFile content after autoreplace',\n );\n return false;\n }\n // istanbul ignore if\n if (!newExtract.deps?.length) {\n logger.debug(\n `Extracted ${packageFile!} after autoreplace has no deps array. Did the autoreplace make the file unparseable?`,\n );\n return false;\n }\n // istanbul ignore if\n if (isNumber(depIndex) && depIndex >= newExtract.deps.length) {\n logger.debug(\n `Extracted ${packageFile!} after autoreplace has fewer deps than expected.`,\n );\n return false;\n }\n newUpgrade = newExtract.deps[depIndex!];\n } catch (err) {\n /* istanbul ignore next */\n logger.debug({ manager, packageFile, err }, 'Failed to parse newContent');\n }\n\n if (!newUpgrade!) {\n logger.debug(`No newUpgrade in ${packageFile!}`);\n return false;\n }\n\n if (\n upgrade.depName !== newUpgrade.depName &&\n upgrade.newName !== newUpgrade.depName\n ) {\n logger.debug(\n {\n manager,\n packageFile,\n currentDepName: upgrade.depName,\n newDepName: newUpgrade.depName,\n },\n 'depName mismatch',\n );\n return false;\n }\n\n if (upgrade.newName && upgrade.newName !== newUpgrade.depName) {\n logger.debug(\n {\n manager,\n packageFile,\n currentDepName: upgrade.depName,\n newDepName: newUpgrade.depName,\n },\n 'depName is not updated',\n );\n return false;\n }\n\n if (upgrade.newValue && upgrade.newValue !== newUpgrade.currentValue) {\n // accept reshaped values produced by autoReplaceStringTemplate\n let templateMatchesExtractedValue = false;\n if (upgrade.autoReplaceStringTemplate) {\n try {\n const compiledValue = compile(\n upgrade.autoReplaceStringTemplate,\n upgrade,\n false,\n );\n templateMatchesExtractedValue =\n compiledValue === newUpgrade.currentValue;\n } catch (err) {\n logger.debug(\n { err, manager, packageFile },\n 'Failed to compile autoReplaceStringTemplate in confirmIfDepUpdated',\n );\n }\n }\n if (!templateMatchesExtractedValue) {\n logger.debug(\n {\n depName: upgrade.depName,\n manager,\n packageFile,\n expectedValue: upgrade.newValue,\n foundValue: newUpgrade.currentValue,\n },\n 'Value is not updated',\n );\n return false;\n }\n }\n\n const isPinOrDigestUpdate =\n upgrade.isPinDigest === true || upgrade.currentDigest;\n if (\n upgrade.newDigest &&\n isPinOrDigestUpdate &&\n upgrade.newDigest !== newUpgrade.currentDigest\n ) {\n logger.debug(\n {\n depName: upgrade.depName,\n manager,\n packageFile,\n expectedValue: upgrade.newDigest,\n foundValue: newUpgrade.currentDigest,\n },\n 'Digest is not updated',\n );\n return false;\n }\n\n return true;\n}\n\nfunction getDepsSignature(deps: PackageDependency[]): string {\n // TODO: types (#22198)\n return deps.map((dep) => `${dep.depName!}${dep.packageName!}`).join(',');\n}\n\nfunction firstIndexOf(\n existingContent: string,\n depName: string,\n currentValue: string,\n position = 0,\n): number {\n const depIndex = existingContent.indexOf(depName, position);\n const valIndex = existingContent.indexOf(currentValue, position);\n const index = depIndex < valIndex ? depIndex : valIndex;\n if (index < 0) {\n return position === 0 ? -1 : existingContent.length;\n }\n return index;\n}\n\nexport async function checkBranchDepsMatchBaseDeps(\n upgrade: BranchUpgradeConfig,\n branchContent: string,\n): Promise<boolean> {\n const { baseDeps, manager, packageFile } = upgrade;\n try {\n const res = await extractPackageFile(\n manager,\n branchContent,\n packageFile!,\n upgrade,\n )!;\n const branchDeps = res!.deps;\n // `baseDeps` were normalized during extraction, so the freshly extracted `branchDeps` need the same treatment before their signatures can be compared\n for (const dep of branchDeps) {\n normalizeDepNames(dep);\n }\n return getDepsSignature(baseDeps!) === getDepsSignature(branchDeps);\n } catch /* istanbul ignore next */ {\n logger.info(\n { manager, packageFile },\n 'Failed to parse branchContent - rebasing',\n );\n return false;\n }\n}\n\nasync function checkExistingBranch(\n upgrade: BranchUpgradeConfig,\n existingContent: string,\n): Promise<string | null> {\n const { packageFile, depName } = upgrade;\n if (!(await checkBranchDepsMatchBaseDeps(upgrade, existingContent))) {\n logger.debug(\n { packageFile, depName },\n 'Rebasing branch after deps list has changed',\n );\n return null;\n }\n if (!(await confirmIfDepUpdated(upgrade, existingContent))) {\n logger.debug(\n { packageFile, depName },\n 'Rebasing after outdated branch dep found',\n );\n return null;\n }\n // TODO: fix types (#22198)\n logger.debug(`Branch dep ${depName!} in ${packageFile!} is already updated`);\n return existingContent;\n}\n\nfunction isMissingDepName(\n replaceString: string | undefined,\n depName: string | undefined,\n): boolean {\n return isUndefined(replaceString) || !replaceString.includes(depName!);\n}\n\nexport async function doAutoReplace(\n upgrade: BranchUpgradeConfig,\n existingContent: string,\n reuseExistingBranch: boolean,\n firstUpdate = true,\n): Promise<string | null> {\n const {\n packageFile,\n depName,\n depNameTemplate,\n newName,\n currentValue,\n currentValueTemplate,\n newValue,\n currentDigest,\n currentDigestShort,\n newDigest,\n autoReplaceGlobalMatch,\n autoReplaceStringTemplate,\n } = upgrade;\n /*\n If replacement support for more managers is added,\n please also update the list in docs/usage/configuration-options.md\n at replacementName and replacementVersion\n */\n if (reuseExistingBranch) {\n return await checkExistingBranch(upgrade, existingContent);\n }\n const valueChanging =\n isString(currentValue) && isString(newValue) && currentValue !== newValue;\n const digestChanging =\n isString(currentDigest) &&\n isString(newDigest) &&\n currentDigest !== newDigest;\n let replaceWithoutReplaceString =\n isString(newName) &&\n newName !== depName &&\n isMissingDepName(upgrade.replaceString, depName);\n // fallback must contain the field being updated, else the replacement is\n // a no-op for managers where value and digest live in separate tokens\n let replaceString = upgrade.replaceString;\n if (isUndefined(replaceString)) {\n if (valueChanging && digestChanging) {\n // no single fallback covers both — use the per-field path\n replaceWithoutReplaceString = true;\n replaceString = currentValue;\n } else if (digestChanging) {\n replaceString = currentDigest;\n } else {\n replaceString = currentValue ?? currentDigest;\n }\n }\n logger.trace({ depName, replaceString }, 'autoReplace replaceString');\n let searchIndex: number;\n if (replaceWithoutReplaceString) {\n searchIndex = firstIndexOf(existingContent, depName!, currentValue!);\n } else {\n searchIndex = existingContent.indexOf(replaceString!);\n }\n if (searchIndex === -1) {\n logger.info(\n { packageFile, depName, existingContent, replaceString },\n 'Cannot find replaceString in current file content. Was it already updated?',\n );\n return existingContent;\n }\n try {\n let newString: string;\n if (autoReplaceStringTemplate && !newName) {\n newString = compile(autoReplaceStringTemplate, upgrade, false);\n } else {\n newString = replaceString!;\n\n const autoReplaceRegExpFlag = autoReplaceGlobalMatch ? 'g' : '';\n if (currentValue && newValue && currentValue !== newValue) {\n if (!newString.includes(currentValue)) {\n logger.debug(\n { stringToReplace: newString, currentValue, currentValueTemplate },\n 'currentValue not found in string to replace',\n );\n }\n newString = newString.replace(\n regEx(RegExp.escape(currentValue), autoReplaceRegExpFlag),\n newValue,\n );\n }\n if (depName && newName && depName !== newName) {\n if (!newString.includes(depName)) {\n logger.debug(\n { stringToReplace: newString, depName, depNameTemplate },\n 'depName not found in string to replace',\n );\n }\n newString = newString.replace(\n regEx(RegExp.escape(depName), autoReplaceRegExpFlag),\n newName,\n );\n }\n if (currentDigest && newDigest && currentDigest !== newDigest) {\n if (!newString.includes(currentDigest)) {\n logger.debug(\n { stringToReplace: newString, currentDigest },\n 'currentDigest not found in string to replace',\n );\n }\n newString = newString.replace(\n regEx(RegExp.escape(currentDigest), autoReplaceRegExpFlag),\n newDigest,\n );\n } else if (\n currentDigestShort &&\n newDigest &&\n currentDigestShort !== newDigest &&\n // Only use short digest replacement when there's no full currentDigest\n // that already matches newDigest (otherwise we'd incorrectly replace\n // part of an already-correct digest)\n !(currentDigest && currentDigest === newDigest)\n ) {\n if (!newString.includes(currentDigestShort)) {\n logger.debug(\n { stringToReplace: newString, currentDigestShort },\n 'currentDigestShort not found in string to replace',\n );\n }\n newString = newString.replace(\n regEx(RegExp.escape(currentDigestShort), autoReplaceRegExpFlag),\n newDigest,\n );\n }\n }\n if (!firstUpdate && (await confirmIfDepUpdated(upgrade, existingContent))) {\n logger.debug(\n { packageFile, depName },\n 'Package file is already updated - no work to do',\n );\n return existingContent;\n }\n logger.debug(\n { packageFile, depName },\n `Starting search at index ${searchIndex}`,\n );\n let newContent = existingContent;\n let nameReplaced = !newName;\n let valueReplaced = !newValue;\n let digestReplaced = !newDigest;\n let startIndex = searchIndex;\n // Iterate through the rest of the file\n for (; searchIndex < newContent.length; searchIndex += 1) {\n // First check if we have a hit for the old version\n if (replaceWithoutReplaceString) {\n // look for depName and currentValue\n if (newName && matchAt(newContent, searchIndex, depName!)) {\n logger.debug(\n { packageFile, depName },\n `Found depName at index ${searchIndex}`,\n );\n if (nameReplaced) {\n startIndex = firstIndexOf(\n existingContent,\n depName!,\n currentValue!,\n startIndex + 1,\n );\n searchIndex = startIndex - 1;\n await writeLocalFile(upgrade.packageFile!, existingContent);\n newContent = existingContent;\n nameReplaced = !newName;\n valueReplaced = !newValue;\n digestReplaced = !newDigest;\n continue;\n }\n // replace with newName\n newContent = replaceAt(newContent, searchIndex, depName!, newName);\n await writeLocalFile(upgrade.packageFile!, newContent);\n nameReplaced = true;\n searchIndex += newName.length - 1;\n } else if (\n newValue &&\n matchAt(newContent, searchIndex, currentValue!)\n ) {\n logger.debug(\n { packageFile, currentValue },\n `Found currentValue at index ${searchIndex}`,\n );\n if (valueReplaced) {\n startIndex = firstIndexOf(\n existingContent,\n depName!,\n currentValue!,\n startIndex + 1,\n );\n searchIndex = startIndex - 1;\n await writeLocalFile(upgrade.packageFile!, existingContent);\n newContent = existingContent;\n nameReplaced = !newName;\n valueReplaced = !newValue;\n digestReplaced = !newDigest;\n continue;\n }\n // Now test if the result matches\n newContent = replaceAt(\n newContent,\n searchIndex,\n currentValue!,\n newValue,\n );\n await writeLocalFile(upgrade.packageFile!, newContent);\n valueReplaced = true;\n searchIndex += newValue.length - 1;\n } else if (\n newDigest &&\n matchAt(newContent, searchIndex, currentDigest!)\n ) {\n logger.debug(\n { packageFile, currentDigest },\n `Found currentDigest at index ${searchIndex}`,\n );\n if (digestReplaced) {\n startIndex = firstIndexOf(\n existingContent,\n depName!,\n currentValue!,\n startIndex + 1,\n );\n searchIndex = startIndex - 1;\n await writeLocalFile(upgrade.packageFile!, existingContent);\n newContent = existingContent;\n nameReplaced = !newName;\n valueReplaced = !newValue;\n digestReplaced = !newDigest;\n continue;\n }\n // Now test if the result matches\n newContent = replaceAt(\n newContent,\n searchIndex,\n currentDigest!,\n newDigest,\n );\n await writeLocalFile(upgrade.packageFile!, newContent);\n digestReplaced = true;\n searchIndex += newDigest.length - 1;\n }\n if (nameReplaced && valueReplaced && digestReplaced) {\n if (await confirmIfDepUpdated(upgrade, newContent)) {\n return newContent;\n }\n startIndex = firstIndexOf(\n existingContent,\n depName!,\n currentValue!,\n startIndex + 1,\n );\n searchIndex = startIndex - 1;\n await writeLocalFile(upgrade.packageFile!, existingContent);\n newContent = existingContent;\n nameReplaced = !newName;\n valueReplaced = !newValue;\n digestReplaced = !newDigest;\n }\n } else if (matchAt(newContent, searchIndex, replaceString!)) {\n logger.debug(\n { packageFile, depName },\n `Found match at index ${searchIndex}`,\n );\n // Now test if the result matches\n newContent = replaceAt(\n newContent,\n searchIndex,\n replaceString!,\n newString,\n );\n await writeLocalFile(upgrade.packageFile!, newContent);\n if (await confirmIfDepUpdated(upgrade, newContent)) {\n return newContent;\n }\n await writeLocalFile(upgrade.packageFile!, existingContent);\n newContent = existingContent;\n }\n }\n } catch (err) {\n /* istanbul ignore next */\n logger.debug({ packageFile, depName, err }, 'doAutoReplace error');\n }\n // istanbul ignore next\n throw new Error(WORKER_FILE_UPDATE_FAILED);\n}\n"],"mappings":";;;;;;;;;;AAaA,eAAsB,oBACpB,SACA,YACkB;CAClB,MAAM,EAAE,SAAS,aAAa,aAAa;CAC3C,IAAI;CACJ,IAAI;EACF,MAAM,aAAa,MAAM,mBACvB,SACA,YACA,aACA,OACF;;EAEA,IAAI,CAAC,YAAY;GAEf,OAAO,MACL,qBAAqB,YAAa,YAAY,QAAQ,oEACxD;GACA,OAAO,MACL;IAAE;IAAa,SAAS;GAAW,GACnC,uCACF;GACA,OAAO;EACT;;EAEA,IAAI,CAAC,WAAW,MAAM,QAAQ;GAC5B,OAAO,MACL,aAAa,YAAa,qFAC5B;GACA,OAAO;EACT;;EAEA,IAAI,SAAS,QAAQ,KAAK,YAAY,WAAW,KAAK,QAAQ;GAC5D,OAAO,MACL,aAAa,YAAa,iDAC5B;GACA,OAAO;EACT;EACA,aAAa,WAAW,KAAK;CAC/B,SAAS,KAAK;;EAEZ,OAAO,MAAM;GAAE;GAAS;GAAa;EAAI,GAAG,4BAA4B;CAC1E;CAEA,IAAI,CAAC,YAAa;EAChB,OAAO,MAAM,oBAAoB,aAAc;EAC/C,OAAO;CACT;CAEA,IACE,QAAQ,YAAY,WAAW,WAC/B,QAAQ,YAAY,WAAW,SAC/B;EACA,OAAO,MACL;GACE;GACA;GACA,gBAAgB,QAAQ;GACxB,YAAY,WAAW;EACzB,GACA,kBACF;EACA,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ED, SYSTEM_INSUFFICIENT_DISK_SPACE } from "../../../../constants/error-messages.js";
|
|
2
2
|
import { logger } from "../../../../logger/index.js";
|
|
3
|
+
import { isNotFound } from "../../../../util/http/status.js";
|
|
3
4
|
import { ExternalHostError } from "../../../../types/errors/external-host-error.js";
|
|
4
5
|
// lib/workers/repository/update/branch/errors.ts
|
|
5
6
|
/**
|
|
@@ -8,7 +9,7 @@ import { ExternalHostError } from "../../../../types/errors/external-host-error.
|
|
|
8
9
|
* so that the remaining branches can still be processed.
|
|
9
10
|
*/
|
|
10
11
|
function handleBranchError(err, { branchExists, prNo, commitSha, updatesVerified }) {
|
|
11
|
-
if (err
|
|
12
|
+
if (isNotFound(err)) {
|
|
12
13
|
logger.debug({ err }, "Received a 404 error - aborting run");
|
|
13
14
|
throw new Error(REPOSITORY_CHANGED);
|
|
14
15
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"errors.js","names":[],"sources":["../../../../../lib/workers/repository/update/branch/errors.ts"],"sourcesContent":["import {\n CONFIG_VALIDATION,\n MANAGER_LOCKFILE_ERROR,\n PLATFORM_AUTHENTICATION_ERROR,\n PLATFORM_BAD_CREDENTIALS,\n PLATFORM_INTEGRATION_UNAUTHORIZED,\n PLATFORM_RATE_LIMIT_EXCEEDED,\n PR_ALREADY_IN_MERGE_QUEUE,\n REPOSITORY_CHANGED,\n SYSTEM_INSUFFICIENT_DISK_SPACE,\n TEMPORARY_ERROR,\n WORKER_FILE_UPDATE_FAILED,\n} from '../../../../constants/error-messages.ts';\nimport { logger } from '../../../../logger/index.ts';\nimport { ExternalHostError } from '../../../../types/errors/external-host-error.ts';\nimport type { ProcessBranchResult } from './types.ts';\n\nexport interface BranchErrorContext {\n branchExists: boolean;\n prNo?: number;\n commitSha: string | null;\n updatesVerified: boolean;\n}\n\n/**\n * Decides how an error thrown while updating a branch is handled: errors which\n * must abort the run are (re)thrown, all others are mapped to a branch result\n * so that the remaining branches can still be processed.\n */\nexport function handleBranchError(\n err: any,\n { branchExists, prNo, commitSha, updatesVerified }: BranchErrorContext,\n): ProcessBranchResult {\n if (err
|
|
1
|
+
{"version":3,"file":"errors.js","names":[],"sources":["../../../../../lib/workers/repository/update/branch/errors.ts"],"sourcesContent":["import {\n CONFIG_VALIDATION,\n MANAGER_LOCKFILE_ERROR,\n PLATFORM_AUTHENTICATION_ERROR,\n PLATFORM_BAD_CREDENTIALS,\n PLATFORM_INTEGRATION_UNAUTHORIZED,\n PLATFORM_RATE_LIMIT_EXCEEDED,\n PR_ALREADY_IN_MERGE_QUEUE,\n REPOSITORY_CHANGED,\n SYSTEM_INSUFFICIENT_DISK_SPACE,\n TEMPORARY_ERROR,\n WORKER_FILE_UPDATE_FAILED,\n} from '../../../../constants/error-messages.ts';\nimport { logger } from '../../../../logger/index.ts';\nimport { ExternalHostError } from '../../../../types/errors/external-host-error.ts';\nimport { isNotFound } from '../../../../util/http/status.ts';\nimport type { ProcessBranchResult } from './types.ts';\n\nexport interface BranchErrorContext {\n branchExists: boolean;\n prNo?: number;\n commitSha: string | null;\n updatesVerified: boolean;\n}\n\n/**\n * Decides how an error thrown while updating a branch is handled: errors which\n * must abort the run are (re)thrown, all others are mapped to a branch result\n * so that the remaining branches can still be processed.\n */\nexport function handleBranchError(\n err: any,\n { branchExists, prNo, commitSha, updatesVerified }: BranchErrorContext,\n): ProcessBranchResult {\n if (isNotFound(err)) {\n logger.debug({ err }, 'Received a 404 error - aborting run');\n throw new Error(REPOSITORY_CHANGED);\n }\n if (err.message === PLATFORM_RATE_LIMIT_EXCEEDED) {\n logger.debug('Passing rate-limit-exceeded error up');\n throw err;\n }\n if (err.message === REPOSITORY_CHANGED) {\n logger.debug('Passing repository-changed error up');\n throw err;\n }\n if (err.message?.startsWith('remote: Invalid username or password')) {\n logger.debug('Throwing bad credentials');\n throw new Error(PLATFORM_BAD_CREDENTIALS);\n }\n if (\n err.message?.startsWith(\n 'ssh_exchange_identification: Connection closed by remote host',\n )\n ) {\n logger.debug('Throwing bad credentials');\n throw new Error(PLATFORM_BAD_CREDENTIALS);\n }\n if (err.message === PLATFORM_BAD_CREDENTIALS) {\n logger.debug('Passing bad-credentials error up');\n throw err;\n }\n if (err.message === PLATFORM_INTEGRATION_UNAUTHORIZED) {\n logger.debug('Passing integration-unauthorized error up');\n throw err;\n }\n if (err.message === MANAGER_LOCKFILE_ERROR) {\n logger.debug('Passing lockfile-error up');\n throw err;\n }\n if (err.message === PR_ALREADY_IN_MERGE_QUEUE) {\n logger.debug('Branch PR is in the merge queue - skipping branch update');\n return {\n branchExists,\n prNo,\n result: 'done',\n commitSha,\n };\n }\n if (err.message?.includes('space left on device')) {\n throw new Error(SYSTEM_INSUFFICIENT_DISK_SPACE);\n }\n if (err.message === SYSTEM_INSUFFICIENT_DISK_SPACE) {\n logger.debug('Passing disk-space error up');\n throw err;\n }\n if (err.message.startsWith('Resource not accessible by integration')) {\n logger.debug('Passing 403 error up');\n throw err;\n }\n if (err.message === WORKER_FILE_UPDATE_FAILED) {\n logger.warn('Error updating branch: update failure');\n } else if (err.message.startsWith('bundler-')) {\n // we have already warned inside the bundler artifacts error handling, so just return\n return {\n branchExists: true,\n updatesVerified,\n prNo,\n result: 'error',\n commitSha,\n };\n } else if (err.message?.includes('fatal: Authentication failed')) {\n throw new Error(PLATFORM_AUTHENTICATION_ERROR);\n } else if (err.message?.includes('fatal: bad revision')) {\n logger.debug({ err }, 'Aborting job due to bad revision error');\n throw new Error(REPOSITORY_CHANGED);\n } else if (err.message === CONFIG_VALIDATION) {\n logger.debug('Passing config validation error up');\n throw err;\n } else if (err.message === TEMPORARY_ERROR) {\n logger.debug('Passing TEMPORARY_ERROR error up');\n throw err;\n } else if (!(err instanceof ExternalHostError)) {\n logger.warn({ err }, `Error updating branch`);\n }\n // Don't throw here - we don't want to stop the other renovations\n return {\n branchExists,\n prNo,\n result: 'error',\n commitSha,\n };\n}\n"],"mappings":";;;;;;;;;;AA8BA,SAAgB,kBACd,KACA,EAAE,cAAc,MAAM,W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AA8B,GAC7D,MAAM,IAAI,MAAM,6BAA6B;MACxC,IAAI,IAAI,SAAS,SAAS,qBAAqB,GAAG;EACvD,OAAO,MAAM,EAAE,IAAI,GAAG,wCAAwC;EAC9D,MAAM,IAAI,MAAM,kBAAkB;CACpC,OAAO,IAAI,IAAI,YAAA,qBAA+B;EAC5C,OAAO,MAAM,oCAAoC;EACjD,MAAM;CACR,OAAO,IAAI,IAAI,YAAA,mBAA6B;EAC1C,OAAO,MAAM,kCAAkC;EAC/C,MAAM;CACR,OAAO,IAAI,EAAE,eAAe,oBAC1B,OAAO,KAAK,EAAE,IAAI,GAAG,uBAAuB;CAG9C,OAAO;EACL;EACA;EACA,QAAQ;EACR;CACF;AACF"}
|
|
@@ -11,7 +11,7 @@ import { ensureLocalDir, localPathIsFile, outputCacheFile, privateCacheDir, read
|
|
|
11
11
|
import { getRepoStatus, isFileModeEnabled } from "../../../../util/git/index.js";
|
|
12
12
|
import { withGitEnvironment } from "../../../../util/git/exec.js";
|
|
13
13
|
import "../../../../config/index.js";
|
|
14
|
-
import {
|
|
14
|
+
import { isNonEmptyArray, isString } from "@sindresorhus/is";
|
|
15
15
|
import crypto from "node:crypto";
|
|
16
16
|
import upath from "upath";
|
|
17
17
|
// lib/workers/repository/update/branch/execute-post-upgrade-commands.ts
|
|
@@ -209,7 +209,7 @@ async function postUpgradeCommandsExecutor(filteredUpgradeCommands, config) {
|
|
|
209
209
|
};
|
|
210
210
|
}
|
|
211
211
|
async function executePostUpgradeCommands(config) {
|
|
212
|
-
if (!(
|
|
212
|
+
if (!(isNonEmptyArray(config.updatedPackageFiles) || isNonEmptyArray(config.updatedArtifacts))) {
|
|
213
213
|
logger.debug("No changes to package files, skipping post-upgrade tasks");
|
|
214
214
|
return null;
|
|
215
215
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"execute-post-upgrade-commands.js","names":[],"sources":["../../../../../lib/workers/repository/update/branch/execute-post-upgrade-commands.ts"],"sourcesContent":["// TODO #22198\n\nimport crypto from 'node:crypto';\nimport { isArray, isNonEmptyArray, isString } from '@sindresorhus/is';\nimport upath from 'upath';\nimport { GlobalConfig } from '../../../../config/global.ts';\nimport { mergeChildConfig } from '../../../../config/index.ts';\nimport { addMeta, logger } from '../../../../logger/index.ts';\nimport type { ArtifactError } from '../../../../modules/manager/types.ts';\nimport { coerceArray } from '../../../../util/array.ts';\nimport {\n type ExecOptions,\n isConstraintName,\n isToolName,\n} from '../../../../util/exec/types.ts';\nimport {\n ensureLocalDir,\n localPathIsFile,\n outputCacheFile,\n privateCacheDir,\n readLocalFile,\n statLocalFile,\n writeLocalFile,\n} from '../../../../util/fs/index.ts';\nimport { withGitEnvironment } from '../../../../util/git/exec.ts';\nimport {\n getRepoStatus,\n isFileModeEnabled,\n} from '../../../../util/git/index.ts';\nimport type { FileChange } from '../../../../util/git/types.ts';\nimport { minimatch } from '../../../../util/minimatch.ts';\nimport { regEx } from '../../../../util/regex.ts';\nimport { sanitize } from '../../../../util/sanitize.ts';\nimport { compile } from '../../../../util/template/index.ts';\nimport type { BranchConfig, BranchUpgradeConfig } from '../../../types.ts';\n\nexport interface PostUpgradeCommandsExecutionResult {\n updatedArtifacts: FileChange[];\n artifactErrors: ArtifactError[];\n}\n\nconst ownerExecutePermission = 0o100;\nconst gitExec = withGitEnvironment();\n\nasync function detectExecutable(\n relativePath: string,\n canReadFileMode: boolean,\n): Promise<true | undefined> {\n if (!canReadFileMode) {\n return undefined;\n }\n\n const fileStats = await statLocalFile(relativePath);\n if (!fileStats?.isFile()) {\n return undefined;\n }\n\n if ((fileStats.mode & ownerExecutePermission) === 0) {\n return undefined;\n }\n\n // Git derives its executable flag from the owner's execute permission.\n return true;\n}\n\nexport async function postUpgradeCommandsExecutor(\n filteredUpgradeCommands: BranchUpgradeConfig[],\n config: BranchConfig,\n): Promise<PostUpgradeCommandsExecutionResult> {\n let updatedArtifacts = [...coerceArray(config.updatedArtifacts)];\n const artifactErrors = [...coerceArray(config.artifactErrors)];\n const allowedCommands = GlobalConfig.get('allowedCommands');\n\n for (const upgrade of filteredUpgradeCommands) {\n addMeta({ dep: upgrade.depName });\n logger.trace(\n {\n tasks: upgrade.postUpgradeTasks,\n allowedCommands,\n },\n `Checking for post-upgrade tasks`,\n );\n const commands = upgrade.postUpgradeTasks?.commands;\n const dataFileTemplate = upgrade.postUpgradeTasks?.dataFileTemplate;\n const fileFilters = upgrade.postUpgradeTasks?.fileFilters ?? ['**/*'];\n if (isNonEmptyArray(commands)) {\n // Persist updated files in file system so any executed commands can see them\n const previouslyModifiedFiles =\n config.updatedPackageFiles!.concat(updatedArtifacts);\n for (const file of previouslyModifiedFiles) {\n const canWriteFile = await localPathIsFile(file.path);\n if (file.type === 'addition' && !file.isSymlink && canWriteFile) {\n let contents: Buffer | null;\n if (isString(file.contents)) {\n contents = Buffer.from(file.contents);\n } else {\n contents = file.contents;\n }\n // TODO #22198\n await writeLocalFile(file.path, contents!);\n }\n }\n\n let dataFilePath: string | null = null;\n if (dataFileTemplate) {\n const dataFileContent = sanitize(\n compile(dataFileTemplate, mergeChildConfig(config, upgrade)),\n );\n logger.debug(\n { dataFileTemplate },\n 'Processed post-upgrade commands data file template.',\n );\n\n const dataFileName = `post-upgrade-data-file-${crypto.randomBytes(8).toString('hex')}.tmp`;\n dataFilePath = upath.join(privateCacheDir(), dataFileName);\n\n try {\n await outputCacheFile(dataFilePath, dataFileContent);\n\n logger.debug(\n { dataFilePath, dataFileContent },\n 'Created post-upgrade commands data file.',\n );\n } catch (error) {\n artifactErrors.push({\n stderr: sanitize(\n `Failed to create post-upgrade commands data file at ${dataFilePath}, reason: ${error.message}`,\n ),\n });\n\n dataFilePath = null;\n }\n }\n\n const workingDirTemplate = upgrade.postUpgradeTasks?.workingDirTemplate;\n let workingDir = GlobalConfig.get('localDir');\n\n if (workingDirTemplate) {\n workingDir = sanitize(\n compile(workingDirTemplate, mergeChildConfig(config, upgrade)),\n );\n workingDir = await ensureLocalDir(workingDir);\n logger.trace(\n { workingDirTemplate },\n 'Processed post-upgrade commands working directory template.',\n );\n }\n\n for (const cmd of commands) {\n const compiledCmd = compile(cmd, mergeChildConfig(config, upgrade));\n if (compiledCmd !== cmd) {\n logger.debug(\n { rawCmd: cmd, compiledCmd },\n 'Post-upgrade command has been compiled',\n );\n }\n if (compiledCmd === '') {\n logger.trace({ rawCmd: cmd }, 'Skipping empty post-upgrade task');\n continue;\n }\n if (\n allowedCommands.some((pattern) => regEx(pattern).test(compiledCmd))\n ) {\n try {\n logger.trace({ cmd: compiledCmd }, 'Executing post-upgrade task');\n\n const execOpts: ExecOptions = {\n // oxlint-disable-next-line renovate/no-exec-shell-option -- some self-hosted adminstrators allow their users to use shell features (pipes, globbing, sub-shells), so this is allowed for that purpose when it's opted in via allowShellExecutorForPostUpgradeCommands\n shell: GlobalConfig.get(\n 'allowShellExecutorForPostUpgradeCommands',\n ),\n\n cwd: workingDir,\n };\n if (dataFilePath) {\n execOpts.env = {\n RENOVATE_POST_UPGRADE_COMMAND_DATA_FILE: dataFilePath,\n };\n }\n if (upgrade.postUpgradeTasks?.installTools) {\n execOpts.toolConstraints ??= [];\n\n for (const [tool] of Object.entries(\n upgrade.postUpgradeTasks?.installTools,\n )) {\n const validTool = isToolName(tool);\n const validConstraint = isConstraintName(tool);\n if (!validTool) {\n logger.warn(\n {\n tool,\n validTool,\n validConstraint,\n },\n 'Skipping constraint that is not a tool that Containerbase knows',\n );\n continue;\n }\n\n execOpts.toolConstraints.push({\n toolName: tool,\n constraint: upgrade.constraints?.[tool],\n });\n }\n }\n const execResult = await gitExec(compiledCmd, execOpts);\n\n logger.debug(\n { cmd: compiledCmd, ...execResult },\n 'Executed post-upgrade task',\n );\n } catch (error) {\n artifactErrors.push({\n fileName: upgrade.packageFile,\n stderr: sanitize(error.message),\n });\n }\n } else {\n logger.warn(\n {\n cmd: compiledCmd,\n allowedCommands,\n },\n 'Post-upgrade task did not match any on allowedCommands list',\n );\n artifactErrors.push({\n fileName: upgrade.packageFile,\n stderr: sanitize(\n `Post-upgrade command '${compiledCmd}' has not been added to the allowed list in allowedCommands`,\n ),\n });\n }\n }\n\n const status = await getRepoStatus();\n\n logger.trace({ status }, 'git status after post-upgrade tasks');\n\n logger.debug(\n {\n addedCount: status.not_added?.length,\n modifiedCount: status.modified?.length,\n deletedCount: status.deleted?.length,\n renamedCount: status.renamed?.length,\n },\n 'git status counts after post-upgrade tasks',\n );\n\n const addedOrModifiedFiles = [\n ...coerceArray(status.not_added),\n ...coerceArray(status.modified),\n ...coerceArray(status.renamed?.map((x) => x.to)),\n ];\n const changedFiles = [\n ...addedOrModifiedFiles,\n ...coerceArray(status.deleted),\n ...coerceArray(status.renamed?.map((x) => x.from)),\n ];\n\n // Check for files which were previously deleted but have been re-added without modification\n const previouslyDeletedFiles = updatedArtifacts.filter(\n (ua) => ua.type === 'deletion',\n );\n for (const previouslyDeletedFile of previouslyDeletedFiles) {\n /* v8 ignore if -- TODO: needs test */\n if (!changedFiles.includes(previouslyDeletedFile.path)) {\n logger.debug(\n { file: previouslyDeletedFile.path },\n 'Previously deleted file has been restored without modification',\n );\n updatedArtifacts = updatedArtifacts.filter(\n (ua) =>\n !(\n ua.type === 'deletion' && ua.path === previouslyDeletedFile.path\n ),\n );\n }\n }\n\n logger.trace({ addedOrModifiedFiles }, 'Added or modified files');\n logger.debug(\n `Checking ${addedOrModifiedFiles.length} added or modified files for post-upgrade changes`,\n );\n\n const fileExcludes: string[] = [];\n if (config.npmrc) {\n fileExcludes.push('.npmrc');\n }\n const canReadFileMode = await isFileModeEnabled();\n\n for (const relativePath of addedOrModifiedFiles) {\n if (\n fileExcludes.some((pattern) =>\n minimatch(pattern, { dot: true }).match(relativePath),\n )\n ) {\n continue;\n }\n\n let fileMatched = false;\n for (const pattern of fileFilters) {\n if (minimatch(pattern, { dot: true }).match(relativePath)) {\n fileMatched = true;\n logger.debug(\n { file: relativePath, pattern },\n 'Post-upgrade file saved',\n );\n const existingContent = await readLocalFile(relativePath);\n const isExecutable = await detectExecutable(\n relativePath,\n canReadFileMode,\n );\n const existingUpdatedArtifacts = updatedArtifacts.find(\n (ua) => ua.path === relativePath,\n );\n if (existingUpdatedArtifacts?.type === 'addition') {\n existingUpdatedArtifacts.contents = existingContent;\n if (isExecutable !== undefined) {\n existingUpdatedArtifacts.isExecutable = isExecutable;\n }\n } else {\n const updatedArtifact: FileChange = {\n type: 'addition',\n path: relativePath,\n contents: existingContent,\n };\n if (isExecutable !== undefined) {\n updatedArtifact.isExecutable = isExecutable;\n }\n updatedArtifacts.push(updatedArtifact);\n }\n // If the file is deleted by a previous post-update command, remove the deletion from updatedArtifacts\n updatedArtifacts = updatedArtifacts.filter(\n (ua) => !(ua.type === 'deletion' && ua.path === relativePath),\n );\n }\n }\n if (!fileMatched) {\n logger.debug(\n { file: relativePath },\n 'Post-upgrade file did not match any file filters',\n );\n }\n }\n\n for (const relativePath of coerceArray(status.deleted)) {\n for (const pattern of fileFilters) {\n if (minimatch(pattern, { dot: true }).match(relativePath)) {\n if (\n !updatedArtifacts.some(\n (ua) => ua.path === relativePath && ua.type === 'deletion',\n )\n ) {\n logger.debug(\n { file: relativePath, pattern },\n 'Post-upgrade file removed',\n );\n updatedArtifacts.push({\n type: 'deletion',\n path: relativePath,\n });\n }\n // If the file is created or modified by a previous post-update command, remove the modification from updatedArtifacts\n updatedArtifacts = updatedArtifacts.filter(\n (ua) => !(ua.type === 'addition' && ua.path === relativePath),\n );\n }\n }\n }\n }\n }\n return { updatedArtifacts, artifactErrors };\n}\n\nexport default async function executePostUpgradeCommands(\n config: BranchConfig,\n): Promise<PostUpgradeCommandsExecutionResult | null> {\n const hasChangedFiles =\n (isArray(config.updatedPackageFiles) &&\n config.updatedPackageFiles.length > 0) ||\n (isArray(config.updatedArtifacts) && config.updatedArtifacts.length > 0);\n\n if (!hasChangedFiles) {\n /* Only run post-upgrade tasks if there are changes to package files... */\n logger.debug('No changes to package files, skipping post-upgrade tasks');\n return null;\n }\n\n const branchUpgradeCommands: BranchUpgradeConfig[] = [\n {\n manager: config.manager,\n depName: config.upgrades.map(({ depName }) => depName).join(' '),\n branchName: config.branchName,\n constraints: config.constraints,\n postUpgradeTasks:\n config.postUpgradeTasks!.executionMode === 'branch'\n ? config.postUpgradeTasks\n : undefined,\n },\n ];\n\n const updateUpgradeCommands: BranchUpgradeConfig[] = config.upgrades.filter(\n ({ postUpgradeTasks }) =>\n !postUpgradeTasks?.executionMode ||\n postUpgradeTasks.executionMode === 'update',\n );\n\n const { updatedArtifacts, artifactErrors } =\n await postUpgradeCommandsExecutor(updateUpgradeCommands, config);\n return postUpgradeCommandsExecutor(branchUpgradeCommands, {\n ...config,\n updatedArtifacts,\n artifactErrors,\n });\n}\n"],"mappings":";;;;;;;;;;;;;;;;;AAyCA,MAAM,yBAAyB;AAC/B,MAAM,UAAU,mBAAmB;AAEnC,eAAe,iBACb,cACA,iBAC2B;CAC3B,IAAI,CAAC,iBACH;CAGF,MAAM,YAAY,MAAM,cAAc,YAAY;CAClD,IAAI,CAAC,WAAW,OAAO,GACrB;CAGF,KAAK,UAAU,OAAO,4BAA4B,GAChD;CAIF,OAAO;AACT;AAEA,eAAsB,4BACpB,yBACA,QAC6C;CAC7C,IAAI,mBAAmB,CAAC,GAAG,YAAY,OAAO,gBAAgB,CAAC;CAC/D,MAAM,iBAAiB,CAAC,GAAG,YAAY,OAAO,cAAc,CAAC;CAC7D,MAAM,kBAAkB,aAAa,IAAI,iBAAiB;CAE1D,KAAK,MAAM,WAAW,yBAAyB;EAC7C,QAAQ,EAAE,KAAK,QAAQ,QAAQ,CAAC;EAChC,OAAO,MACL;GACE,OAAO,QAAQ;GACf;EACF,GACA,iCACF;EACA,MAAM,WAAW,QAAQ,kBAAkB;EAC3C,MAAM,mBAAmB,QAAQ,kBAAkB;EACnD,MAAM,cAAc,QAAQ,kBAAkB,eAAe,CAAC,MAAM;EACpE,IAAI,gBAAgB,QAAQ,GAAG;GAE7B,MAAM,0BACJ,OAAO,oBAAqB,OAAO,gBAAgB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mBACP,KAAA;CACR,CACF;CAQA,MAAM,EAAE,kBAAkB,mBACxB,MAAM,4BAP6C,OAAO,SAAS,QAClE,EAAE,uBACD,CAAC,kBAAkB,iBACnB,iBAAiB,kBAAkB,QAIiB,GAAG,MAAM;CACjE,OAAO,4BAA4B,uBAAuB;EACxD,GAAG;EACH;EACA;CACF,CAAC;AACH"}
|
|
1
|
+
{"version":3,"file":"execute-post-upgrade-commands.js","names":[],"sources":["../../../../../lib/workers/repository/update/branch/execute-post-upgrade-commands.ts"],"sourcesContent":["// TODO #22198\n\nimport crypto from 'node:crypto';\nimport { isNonEmptyArray, isString } from '@sindresorhus/is';\nimport upath from 'upath';\nimport { GlobalConfig } from '../../../../config/global.ts';\nimport { mergeChildConfig } from '../../../../config/index.ts';\nimport { addMeta, logger } from '../../../../logger/index.ts';\nimport type { ArtifactError } from '../../../../modules/manager/types.ts';\nimport { coerceArray } from '../../../../util/array.ts';\nimport {\n type ExecOptions,\n isConstraintName,\n isToolName,\n} from '../../../../util/exec/types.ts';\nimport {\n ensureLocalDir,\n localPathIsFile,\n outputCacheFile,\n privateCacheDir,\n readLocalFile,\n statLocalFile,\n writeLocalFile,\n} from '../../../../util/fs/index.ts';\nimport { withGitEnvironment } from '../../../../util/git/exec.ts';\nimport {\n getRepoStatus,\n isFileModeEnabled,\n} from '../../../../util/git/index.ts';\nimport type { FileChange } from '../../../../util/git/types.ts';\nimport { minimatch } from '../../../../util/minimatch.ts';\nimport { regEx } from '../../../../util/regex.ts';\nimport { sanitize } from '../../../../util/sanitize.ts';\nimport { compile } from '../../../../util/template/index.ts';\nimport type { BranchConfig, BranchUpgradeConfig } from '../../../types.ts';\n\nexport interface PostUpgradeCommandsExecutionResult {\n updatedArtifacts: FileChange[];\n artifactErrors: ArtifactError[];\n}\n\nconst ownerExecutePermission = 0o100;\nconst gitExec = withGitEnvironment();\n\nasync function detectExecutable(\n relativePath: string,\n canReadFileMode: boolean,\n): Promise<true | undefined> {\n if (!canReadFileMode) {\n return undefined;\n }\n\n const fileStats = await statLocalFile(relativePath);\n if (!fileStats?.isFile()) {\n return undefined;\n }\n\n if ((fileStats.mode & ownerExecutePermission) === 0) {\n return undefined;\n }\n\n // Git derives its executable flag from the owner's execute permission.\n return true;\n}\n\nexport async function postUpgradeCommandsExecutor(\n filteredUpgradeCommands: BranchUpgradeConfig[],\n config: BranchConfig,\n): Promise<PostUpgradeCommandsExecutionResult> {\n let updatedArtifacts = [...coerceArray(config.updatedArtifacts)];\n const artifactErrors = [...coerceArray(config.artifactErrors)];\n const allowedCommands = GlobalConfig.get('allowedCommands');\n\n for (const upgrade of filteredUpgradeCommands) {\n addMeta({ dep: upgrade.depName });\n logger.trace(\n {\n tasks: upgrade.postUpgradeTasks,\n allowedCommands,\n },\n `Checking for post-upgrade tasks`,\n );\n const commands = upgrade.postUpgradeTasks?.commands;\n const dataFileTemplate = upgrade.postUpgradeTasks?.dataFileTemplate;\n const fileFilters = upgrade.postUpgradeTasks?.fileFilters ?? ['**/*'];\n if (isNonEmptyArray(commands)) {\n // Persist updated files in file system so any executed commands can see them\n const previouslyModifiedFiles =\n config.updatedPackageFiles!.concat(updatedArtifacts);\n for (const file of previouslyModifiedFiles) {\n const canWriteFile = await localPathIsFile(file.path);\n if (file.type === 'addition' && !file.isSymlink && canWriteFile) {\n let contents: Buffer | null;\n if (isString(file.contents)) {\n contents = Buffer.from(file.contents);\n } else {\n contents = file.contents;\n }\n // TODO #22198\n await writeLocalFile(file.path, contents!);\n }\n }\n\n let dataFilePath: string | null = null;\n if (dataFileTemplate) {\n const dataFileContent = sanitize(\n compile(dataFileTemplate, mergeChildConfig(config, upgrade)),\n );\n logger.debug(\n { dataFileTemplate },\n 'Processed post-upgrade commands data file template.',\n );\n\n const dataFileName = `post-upgrade-data-file-${crypto.randomBytes(8).toString('hex')}.tmp`;\n dataFilePath = upath.join(privateCacheDir(), dataFileName);\n\n try {\n await outputCacheFile(dataFilePath, dataFileContent);\n\n logger.debug(\n { dataFilePath, dataFileContent },\n 'Created post-upgrade commands data file.',\n );\n } catch (error) {\n artifactErrors.push({\n stderr: sanitize(\n `Failed to create post-upgrade commands data file at ${dataFilePath}, reason: ${error.message}`,\n ),\n });\n\n dataFilePath = null;\n }\n }\n\n const workingDirTemplate = upgrade.postUpgradeTasks?.workingDirTemplate;\n let workingDir = GlobalConfig.get('localDir');\n\n if (workingDirTemplate) {\n workingDir = sanitize(\n compile(workingDirTemplate, mergeChildConfig(config, upgrade)),\n );\n workingDir = await ensureLocalDir(workingDir);\n logger.trace(\n { workingDirTemplate },\n 'Processed post-upgrade commands working directory template.',\n );\n }\n\n for (const cmd of commands) {\n const compiledCmd = compile(cmd, mergeChildConfig(config, upgrade));\n if (compiledCmd !== cmd) {\n logger.debug(\n { rawCmd: cmd, compiledCmd },\n 'Post-upgrade command has been compiled',\n );\n }\n if (compiledCmd === '') {\n logger.trace({ rawCmd: cmd }, 'Skipping empty post-upgrade task');\n continue;\n }\n if (\n allowedCommands.some((pattern) => regEx(pattern).test(compiledCmd))\n ) {\n try {\n logger.trace({ cmd: compiledCmd }, 'Executing post-upgrade task');\n\n const execOpts: ExecOptions = {\n // oxlint-disable-next-line renovate/no-exec-shell-option -- some self-hosted adminstrators allow their users to use shell features (pipes, globbing, sub-shells), so this is allowed for that purpose when it's opted in via allowShellExecutorForPostUpgradeCommands\n shell: GlobalConfig.get(\n 'allowShellExecutorForPostUpgradeCommands',\n ),\n\n cwd: workingDir,\n };\n if (dataFilePath) {\n execOpts.env = {\n RENOVATE_POST_UPGRADE_COMMAND_DATA_FILE: dataFilePath,\n };\n }\n if (upgrade.postUpgradeTasks?.installTools) {\n execOpts.toolConstraints ??= [];\n\n for (const [tool] of Object.entries(\n upgrade.postUpgradeTasks?.installTools,\n )) {\n const validTool = isToolName(tool);\n const validConstraint = isConstraintName(tool);\n if (!validTool) {\n logger.warn(\n {\n tool,\n validTool,\n validConstraint,\n },\n 'Skipping constraint that is not a tool that Containerbase knows',\n );\n continue;\n }\n\n execOpts.toolConstraints.push({\n toolName: tool,\n constraint: upgrade.constraints?.[tool],\n });\n }\n }\n const execResult = await gitExec(compiledCmd, execOpts);\n\n logger.debug(\n { cmd: compiledCmd, ...execResult },\n 'Executed post-upgrade task',\n );\n } catch (error) {\n artifactErrors.push({\n fileName: upgrade.packageFile,\n stderr: sanitize(error.message),\n });\n }\n } else {\n logger.warn(\n {\n cmd: compiledCmd,\n allowedCommands,\n },\n 'Post-upgrade task did not match any on allowedCommands list',\n );\n artifactErrors.push({\n fileName: upgrade.packageFile,\n stderr: sanitize(\n `Post-upgrade command '${compiledCmd}' has not been added to the allowed list in allowedCommands`,\n ),\n });\n }\n }\n\n const status = await getRepoStatus();\n\n logger.trace({ status }, 'git status after post-upgrade tasks');\n\n logger.debug(\n {\n addedCount: status.not_added?.length,\n modifiedCount: status.modified?.length,\n deletedCount: status.deleted?.length,\n renamedCount: status.renamed?.length,\n },\n 'git status counts after post-upgrade tasks',\n );\n\n const addedOrModifiedFiles = [\n ...coerceArray(status.not_added),\n ...coerceArray(status.modified),\n ...coerceArray(status.renamed?.map((x) => x.to)),\n ];\n const changedFiles = [\n ...addedOrModifiedFiles,\n ...coerceArray(status.deleted),\n ...coerceArray(status.renamed?.map((x) => x.from)),\n ];\n\n // Check for files which were previously deleted but have been re-added without modification\n const previouslyDeletedFiles = updatedArtifacts.filter(\n (ua) => ua.type === 'deletion',\n );\n for (const previouslyDeletedFile of previouslyDeletedFiles) {\n /* v8 ignore if -- TODO: needs test */\n if (!changedFiles.includes(previouslyDeletedFile.path)) {\n logger.debug(\n { file: previouslyDeletedFile.path },\n 'Previously deleted file has been restored without modification',\n );\n updatedArtifacts = updatedArtifacts.filter(\n (ua) =>\n !(\n ua.type === 'deletion' && ua.path === previouslyDeletedFile.path\n ),\n );\n }\n }\n\n logger.trace({ addedOrModifiedFiles }, 'Added or modified files');\n logger.debug(\n `Checking ${addedOrModifiedFiles.length} added or modified files for post-upgrade changes`,\n );\n\n const fileExcludes: string[] = [];\n if (config.npmrc) {\n fileExcludes.push('.npmrc');\n }\n const canReadFileMode = await isFileModeEnabled();\n\n for (const relativePath of addedOrModifiedFiles) {\n if (\n fileExcludes.some((pattern) =>\n minimatch(pattern, { dot: true }).match(relativePath),\n )\n ) {\n continue;\n }\n\n let fileMatched = false;\n for (const pattern of fileFilters) {\n if (minimatch(pattern, { dot: true }).match(relativePath)) {\n fileMatched = true;\n logger.debug(\n { file: relativePath, pattern },\n 'Post-upgrade file saved',\n );\n const existingContent = await readLocalFile(relativePath);\n const isExecutable = await detectExecutable(\n relativePath,\n canReadFileMode,\n );\n const existingUpdatedArtifacts = updatedArtifacts.find(\n (ua) => ua.path === relativePath,\n );\n if (existingUpdatedArtifacts?.type === 'addition') {\n existingUpdatedArtifacts.contents = existingContent;\n if (isExecutable !== undefined) {\n existingUpdatedArtifacts.isExecutable = isExecutable;\n }\n } else {\n const updatedArtifact: FileChange = {\n type: 'addition',\n path: relativePath,\n contents: existingContent,\n };\n if (isExecutable !== undefined) {\n updatedArtifact.isExecutable = isExecutable;\n }\n updatedArtifacts.push(updatedArtifact);\n }\n // If the file is deleted by a previous post-update command, remove the deletion from updatedArtifacts\n updatedArtifacts = updatedArtifacts.filter(\n (ua) => !(ua.type === 'deletion' && ua.path === relativePath),\n );\n }\n }\n if (!fileMatched) {\n logger.debug(\n { file: relativePath },\n 'Post-upgrade file did not match any file filters',\n );\n }\n }\n\n for (const relativePath of coerceArray(status.deleted)) {\n for (const pattern of fileFilters) {\n if (minimatch(pattern, { dot: true }).match(relativePath)) {\n if (\n !updatedArtifacts.some(\n (ua) => ua.path === relativePath && ua.type === 'deletion',\n )\n ) {\n logger.debug(\n { file: relativePath, pattern },\n 'Post-upgrade file removed',\n );\n updatedArtifacts.push({\n type: 'deletion',\n path: relativePath,\n });\n }\n // If the file is created or modified by a previous post-update command, remove the modification from updatedArtifacts\n updatedArtifacts = updatedArtifacts.filter(\n (ua) => !(ua.type === 'addition' && ua.path === relativePath),\n );\n }\n }\n }\n }\n }\n return { updatedArtifacts, artifactErrors };\n}\n\nexport default async function executePostUpgradeCommands(\n config: BranchConfig,\n): Promise<PostUpgradeCommandsExecutionResult | null> {\n const hasChangedFiles =\n isNonEmptyArray(config.updatedPackageFiles) ||\n isNonEmptyArray(config.updatedArtifacts);\n\n if (!hasChangedFiles) {\n /* Only run post-upgrade tasks if there are changes to package files... */\n logger.debug('No changes to package files, skipping post-upgrade tasks');\n return null;\n }\n\n const branchUpgradeCommands: BranchUpgradeConfig[] = [\n {\n manager: config.manager,\n depName: config.upgrades.map(({ depName }) => depName).join(' '),\n branchName: config.branchName,\n constraints: config.constraints,\n postUpgradeTasks:\n config.postUpgradeTasks!.executionMode === 'branch'\n ? config.postUpgradeTasks\n : undefined,\n },\n ];\n\n const updateUpgradeCommands: BranchUpgradeConfig[] = config.upgrades.filter(\n ({ postUpgradeTasks }) =>\n !postUpgradeTasks?.executionMode ||\n postUpgradeTasks.executionMode === 'update',\n );\n\n const { updatedArtifacts, artifactErrors } =\n await postUpgradeCommandsExecutor(updateUpgradeCommands, config);\n return postUpgradeCommandsExecutor(branchUpgradeCommands, {\n ...config,\n updatedArtifacts,\n artifactErrors,\n });\n}\n"],"mappings":";;;;;;;;;;;;;;;;;AAyCA,MAAM,yBAAyB;AAC/B,MAAM,UAAU,mBAAmB;AAEnC,eAAe,iBACb,cACA,iBAC2B;CAC3B,IAAI,CAAC,iBACH;CAGF,MAAM,YAAY,MAAM,cAAc,YAAY;CAClD,IAAI,CAAC,WAAW,OAAO,GACrB;CAGF,KAAK,UAAU,OAAO,4BAA4B,GAChD;CAIF,OAAO;AACT;AAEA,eAAsB,4BACpB,yBACA,QAC6C;CAC7C,IAAI,mBAAmB,CAAC,GAAG,YAAY,OAAO,gBAAgB,CAAC;CAC/D,MAAM,iBAAiB,CAAC,GAAG,YAAY,OAAO,cAAc,CAAC;CAC7D,MAAM,kBAAkB,aAAa,IAAI,iBAAiB;CAE1D,KAAK,MAAM,WAAW,yBAAyB;EAC7C,Q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EnB;EAEpB,OAAO,MAAM,0DAA0D;EACvE,OAAO;CACT;CAEA,MAAM,wBAA+C,CACnD;EACE,SAAS,OAAO;EAChB,SAAS,OAAO,SAAS,KAAK,EAAE,cAAc,OAAO,CAAC,CAAC,KAAK,GAAG;EAC/D,YAAY,OAAO;EACnB,aAAa,OAAO;EACpB,kBACE,OAAO,iBAAkB,kBAAkB,WACvC,OAAO,mBACP,KAAA;CACR,CACF;CAQA,MAAM,EAAE,kBAAkB,mBACxB,MAAM,4BAP6C,OAAO,SAAS,QAClE,EAAE,uBACD,CAAC,kBAAkB,iBACnB,iBAAiB,kBAAkB,QAIiB,GAAG,MAAM;CACjE,OAAO,4BAA4B,uBAAuB;EACxD,GAAG;EACH;EACA;CACF,CAAC;AACH"}
|
|
@@ -91,8 +91,7 @@ async function getUpdatedPackageFiles(config) {
|
|
|
91
91
|
let lockFileContent = null;
|
|
92
92
|
const lockFile = upgrade.lockFile ?? upgrade.lockFiles?.[0] ?? "";
|
|
93
93
|
if (lockFile) lockFileContent = await getFileContent(updatedFileContents, lockFile, config);
|
|
94
|
-
|
|
95
|
-
if (reuseExistingBranch && (!packageFileContent || lockFile && !lockFileContent)) {
|
|
94
|
+
if (reuseExistingBranch && (!packageFileContent || !!lockFile && !lockFileContent)) {
|
|
96
95
|
logger.debug({
|
|
97
96
|
packageFile,
|
|
98
97
|
depName
|