Files
renovate/lib/modules/manager/bundler/artifacts.ts
Sebastian Poxhofer 4b4d14ec00 feat(manager): pass extracted constraints to updateArtifacts (#45826)
* feat(manager): pass extracted constraints to updateArtifacts

`extractedConstraints` were collected during extraction but only ever read
by `fetch.ts` for the lookup. At artifact time every manager had to derive
the same tool constraints a second time, and when the updated package file
no longer carried the constraint there was nothing to fall back to.

`generateBranchConfig()` now merges the `extractedConstraints` of all
upgrades of a branch onto the branch config, which reaches `updateArtifacts()`
through `patchConfigForArtifactsUpdate()`. `UpdateArtifactsConfig` declares
the field and documents what it contains.

The new `resolveToolConstraint()` helper implements the ladder once:
user `constraints` > an optional artifact-time derivation > the extracted
value. The derivation is ranked above the extracted value on purpose: it
reads the package files as the branch changed them, so poetry (python is an
updatable dependency there), composer, pipenv (`pipenv` can be a dev
package) and pep621 (`requires-python` is an updatable dependency) would
otherwise regress to a stale constraint. pipenv, pep621 uv/pdm, poetry and
composer are migrated to the helper and keep their derivation.

Behaviour change: these managers now use the extract-time constraint as a
last resort instead of running unconstrained, for example on lock file
maintenance where pipenv deletes `Pipfile.lock` before deriving.

`execute-post-upgrade-commands.ts` is unaffected: it reads
`upgrade.constraints` per upgrade, and the extracted values are kept in a
separate field rather than folded into `constraints`, so post-upgrade task
tool constraints still come from user config only.

Not migrated, because their constraints are never extracted, so the
fallback would be dead code: bundler (`ruby`/`bundler`), pixi (`pixi`),
pep621 uv (`required-version`) and npm's node ladder, whose last step
already reads `package.json` engines.

* refactor(manager): resolve tool constraints through resolveToolConstraint()

Every manager now obtains the constraint of a tool it runs through
`resolveToolConstraint()` instead of reading `config.constraints` itself, so
the precedence "user config, then a value derived from the updated files, then
the constraints collected during extraction" applies everywhere. The helper
treats an empty string as not set at every step and accepts the
`PostUpdateConfig` shape, whose `constraints` may be `null`.

Behaviour changes that go beyond the new fallback to extracted constraints:

- `mix` applies its hardcoded erlang default only after the extracted
  constraint, so an erlang version collected at extraction can win over it.
- `kustomize` decides `HELM_EXPERIMENTAL_OCI` from the fully resolved helm
  constraint; `generateHelmEnvs()` takes that value instead of the config.
- `npm` (yarn): an upgrade of yarn without a new value now consults the user
  constraint before deriving one from package.json or the lock file.
- The "Using <tool> constraint from config" debug lines in bundler, composer,
  copier and pip-compile are gone, as the helper is the only reader of the
  config now.

Helpers that read the config synchronously became async: bundler
`getBundlerConstraint()`, copier `getPythonVersionConstraint()` and
`getCopierVersionConstraint()`, pip-compile `get*VersionConstraint()` and
`getToolVersionConstraint()`, gomod `deriveGoToolchainConstraints()` and
`getUpdateImportPathCmds()`, mise `getMiseLockToolConstraints()`. composer
`getPhpConstraint()` is removed.

Each converted manager has a test showing the extracted constraint reaching
the executed tool, and, where a derive callback exists, that the derived value
still wins over it.

* refactor(linters): add prefer-resolve-tool-constraint rule

Reports member reads and destructuring of `constraints` and
`extractedConstraints` from a manager config in `lib/modules/manager/**`, so
that tool constraints are resolved through `resolveToolConstraint()` in
`lib/modules/manager/util.ts` only. Writes and the same properties on package
files, which extraction has to populate, are not reported. The helper itself
and spec files are exempt in `.oxlintrc.json`.

* refactor(manager): inline thin resolveToolConstraint wrappers

Drop copier/utils.ts and the pip-compile getPipToolsVersionConstraint /
getUvVersionConstraint helpers, which only forwarded to
resolveToolConstraint(). Callers now call it directly.

* docs(development): note lock file maintenance in tool constraints section

* refactor(manager): address review on tool constraint resolution

composer only runs extractConstraints() when a user constraint is missing,
via Lazy. UpdateArtifactsConfig no longer re-declares constraints and
extractedConstraints, which ToolConstraintsConfig already provides.
2026-09-14 11:09:07 +00:00

265 lines
7.5 KiB
TypeScript

import { isNonEmptyStringAndNotWhitespace, isString } from '@sindresorhus/is';
import { quote } from 'shlex';
import {
BUNDLER_INVALID_CREDENTIALS,
TEMPORARY_ERROR,
} from '../../../constants/error-messages.ts';
import { logger } from '../../../logger/index.ts';
import type { HostRule } from '../../../types/index.ts';
import * as memCache from '../../../util/cache/memory/index.ts';
import { exec } from '../../../util/exec/index.ts';
import type { ExecOptions } from '../../../util/exec/types.ts';
import {
ensureCacheDir,
readLocalFile,
writeLocalFile,
} from '../../../util/fs/index.ts';
import { getRepoStatus } from '../../../util/git/index.ts';
import { newlineRegex, regEx } from '../../../util/regex.ts';
import type { UpdateArtifact, UpdateArtifactsResult } from '../types.ts';
import {
getBundlerConstraint,
getLockFilePath,
getRubyConstraint,
} from './common.ts';
import {
findAllAuthenticatable,
getAuthenticationHeaderValue,
} from './host-rules.ts';
const hostConfigVariablePrefix = 'BUNDLE_';
function buildBundleHostVariable(hostRule: HostRule): Record<string, string> {
// istanbul ignore if: doesn't happen in practice
if (!hostRule.resolvedHost) {
return {};
}
const varName = hostConfigVariablePrefix.concat(
hostRule.resolvedHost
.toUpperCase()
.split('.')
.join('__')
.split('-')
.join('___'),
);
return {
[varName]: `${getAuthenticationHeaderValue(hostRule)}`,
};
}
const resolvedPkgRegex = regEx(
/(?<pkg>\S+)(?:\s*\([^)]+\)\s*)? was resolved to/,
);
function getResolvedPackages(input: string): string[] {
const lines = input.split(newlineRegex);
const result: string[] = [];
for (const line of lines) {
const resolveMatchGroups = line.match(resolvedPkgRegex)?.groups;
if (resolveMatchGroups) {
const { pkg } = resolveMatchGroups;
result.push(pkg);
}
}
return [...new Set(result)];
}
export async function updateArtifacts(
updateArtifact: UpdateArtifact,
recursionLimit = 10,
): Promise<UpdateArtifactsResult[] | null> {
const { packageFileName, updatedDeps, newPackageFileContent, config } =
updateArtifact;
logger.debug(`bundler.updateArtifacts(${packageFileName})`);
const existingError = memCache.get<string>('bundlerArtifactsError');
// istanbul ignore if
if (existingError) {
logger.debug('Aborting Bundler artifacts due to previous failed attempt');
throw new Error(existingError);
}
const lockFileName = await getLockFilePath(packageFileName);
const existingLockFileContent = await readLocalFile(lockFileName, 'utf8');
if (!existingLockFileContent) {
logger.debug('No Gemfile.lock found');
return null;
}
const updatedDepNames: string[] = updatedDeps
.map(({ depName }) => depName)
.filter(isNonEmptyStringAndNotWhitespace);
try {
await writeLocalFile(packageFileName, newPackageFileContent);
const commands: string[] = [];
if (config.isLockFileMaintenance) {
commands.push('bundler lock --update');
} else {
const bundlerUpgraded = updatedDeps
.map((dep) => dep.depName)
.includes('bundler');
if (bundlerUpgraded) {
commands.push('bundler lock --update --bundler');
}
const updateTypes = {
patch: '--patch ',
minor: '--minor ',
major: '',
};
for (const [updateType, updateArg] of Object.entries(updateTypes)) {
const deps = updatedDeps
.filter((dep) => (dep.updateType ?? 'major') === updateType)
.map((dep) => dep.depName)
.filter(isString)
.filter((dep) => dep !== 'ruby' && dep !== 'bundler');
let additionalArgs = '';
if (config.postUpdateOptions?.includes('bundlerConservative')) {
additionalArgs = '--conservative ';
}
if (deps.length) {
const cmd = `bundler lock ${updateArg}${additionalArgs}--update ${deps
.map(quote)
.join(' ')}`;
commands.push(cmd);
}
}
const rubyUpgraded = updatedDeps
.map((dep) => dep.depName)
.includes('ruby');
if (rubyUpgraded) {
commands.push('bundler lock');
}
}
const bundlerHostRules = findAllAuthenticatable({
hostType: 'rubygems',
});
const bundlerHostRulesVariables = bundlerHostRules.reduce(
(variables, hostRule) => ({
...variables,
...buildBundleHostVariable(hostRule),
}),
{} as Record<string, string>,
);
const bundler = await getBundlerConstraint(
updateArtifact,
existingLockFileContent,
);
const preCommands = ['ruby --version'];
const execOptions: ExecOptions = {
cwdFile: lockFileName,
extraEnv: {
...bundlerHostRulesVariables,
GEM_HOME: await ensureCacheDir('bundler'),
},
docker: {},
toolConstraints: [
{
toolName: 'ruby',
constraint: await getRubyConstraint(updateArtifact),
},
{
toolName: 'bundler',
constraint: bundler,
},
],
preCommands,
};
await exec(commands, execOptions);
const status = await getRepoStatus();
if (!status.modified.includes(lockFileName)) {
return null;
}
logger.debug('Returning updated Gemfile.lock');
const lockFileContent = await readLocalFile(lockFileName);
return [
{
file: {
type: 'addition',
path: lockFileName,
contents: lockFileContent,
},
},
];
} catch (err) {
if (err.message === TEMPORARY_ERROR) {
throw err;
}
const output = `${String(err.stdout)}\n${String(err.stderr)}`;
if (
err.message.includes('fatal: Could not parse object') ||
output.includes('but that version could not be found')
) {
return [
{
artifactError: {
fileName: lockFileName,
stderr: output,
},
},
];
}
if (
err.stdout?.includes('Please supply credentials for this source') ||
err.stderr?.includes('Authentication is required') ||
err.stderr?.includes(
'Please make sure you have the correct access rights',
)
) {
logger.debug(
{ err },
'Gemfile.lock update failed due to missing credentials - skipping branch',
);
// Do not generate these PRs because we don't yet support Bundler authentication
memCache.set('bundlerArtifactsError', BUNDLER_INVALID_CREDENTIALS);
throw new Error(BUNDLER_INVALID_CREDENTIALS);
}
const resolveMatches: string[] = getResolvedPackages(output).filter(
(depName) => !updatedDepNames.includes(depName),
);
if (
recursionLimit > 0 &&
resolveMatches.length &&
!config.isLockFileMaintenance
) {
logger.debug(
{ resolveMatches, updatedDeps },
'Found new resolve matches - reattempting recursively',
);
const newUpdatedDeps = [
...new Set([
...updatedDeps,
...resolveMatches.map((match) => ({ depName: match })),
]),
];
return updateArtifacts(
{
packageFileName,
updatedDeps: newUpdatedDeps,
newPackageFileContent,
config,
},
recursionLimit - 1,
);
}
logger.info({ err }, 'Gemfile.lock update failed due to an unknown reason');
return [
{
artifactError: {
fileName: lockFileName,
stderr: `${String(err.stdout)}\n${String(err.stderr)}`,
},
},
];
}
}