Files
renovate/lib/modules/manager/cargo/artifacts.ts
Michael Kriese 55a7341be2 test(manager): close long-tail branch coverage gaps (#45954)
* test(manager): close azure-pipelines, bundler and cocoapods gaps

Adds a pipeline whose step task is not versioned, so nothing is
extracted, and a gem lock line carrying no version, which is skipped.

Marks four guards that cannot be false: `extractContainer()` always
returns a dep, `getLockFilePath()` always returns a path, and the
cocoapods dep name, spec name and git account all derive from values
their enclosing check already proved present.

Co-Authored-By: Claude Opus 5 <michael.kriese+claude-code@mend.io>

* test(manager): close cargo, composer and cpanfile gaps

Adds a composer repository map that disables something other than
packagist, which is dropped rather than recorded.

Marks five guards: the cargo warning only fires for a crate dep and its
retry only runs when a dep was already current, a gitlab rule without a
token never passes the auth check, and both cpanfile handlers run only
once their match produced a value.

Two implicit elses stay counted, in the cargo version resolver and the
composer repository mapper, since a coverage-ignore hint does not attach
to an `else if`.

Co-Authored-By: Claude Opus 5 <michael.kriese+claude-code@mend.io>

* test(manager): close deps-edn, docker-compose and dockerfile gaps

Adds three extractions: a deps.edn alias whose value is not a map, a
compose extension carrying no image, and a dockerfile escape directive
naming a character other than a backtick, which leaves the default in
place.

Marks the deps-edn repository name check, since object keys are always
strings, and notes the repository spec chain, where a coverage-ignore
hint does not attach to an `else if`.

Co-Authored-By: Claude Opus 5 <michael.kriese+claude-code@mend.io>

* test(manager/flux): close the flux coverage gaps

Adds two GitRepository resources whose url is ssh rather than http, one
pinned to a tag and one to a commit. Neither yields a source url, since
only http urls can be turned into one.

Marks the Kustomization image guard: the schema rejects an image without
a name, so `extractImage()` cannot return null there.

Co-Authored-By: Claude Opus 5 <michael.kriese+claude-code@mend.io>

* test(manager): mark github-actions, gitlabci and glasskube guards

None of these six needs a test. A parsed action ref is either a docker
or a repository ref, `getDep()` always returns a dep for a job container
and a service, and the remaining three need a listed file that cannot be
read, a listed file that yields no deps, or a manifest whose
repositories match no name.

The glasskube resource kind chain stays counted, since a coverage-ignore
hint does not attach to an `else if`.

Co-Authored-By: Claude Opus 5 <michael.kriese+claude-code@mend.io>

* test(manager): mark gomod and gradle-wrapper guards

Four guards that need setups no test provides: a removed dep that is not
added back, a go.mod the replace massaging leaves unchanged, and a
daemon-jvm file carrying no toolchain version. A parsed go directive
always yields a version.

The additional-dependency count chain stays counted, since a
coverage-ignore hint does not attach to an `else if`.

Co-Authored-By: Claude Opus 5 <michael.kriese+claude-code@mend.io>

---------

Co-authored-by: Claude Opus 5 <michael.kriese+claude-code@mend.io>
2026-09-15 07:10:10 +00:00

231 lines
7.2 KiB
TypeScript

import { quote } from 'shlex';
import { TEMPORARY_ERROR } from '../../../constants/error-messages.ts';
import { logger } from '../../../logger/index.ts';
import { coerceArray } from '../../../util/array.ts';
import type { ExecOptions } from '../../../util/exec/types.ts';
import {
findLocalSiblingOrParent,
readLocalFile,
writeLocalFile,
} from '../../../util/fs/index.ts';
import { withGitEnvironment } from '../../../util/git/exec.ts';
import { regEx } from '../../../util/regex.ts';
import { CrateDatasource } from '../../datasource/crate/index.ts';
import type {
UpdateArtifact,
UpdateArtifactsResult,
Upgrade,
} from '../types.ts';
import { resolveToolConstraint } from '../util.ts';
import { extractLockFileContentVersions } from './locked-version.ts';
const gitExec = withGitEnvironment(['cargo']);
async function cargoUpdate(
manifestPath: string,
isLockFileMaintenance: boolean,
constraint: string | undefined,
): Promise<void> {
let cmd = `cargo update --config net.git-fetch-with-cli=true --manifest-path ${quote(
manifestPath,
)}`;
// If we're updating a specific crate, `cargo-update` requires `--workspace`
// for more information, see: https://github.com/renovatebot/renovate/issues/12332
if (!isLockFileMaintenance) {
cmd += ` --workspace`;
}
const execOptions: ExecOptions = {
docker: {},
toolConstraints: [{ toolName: 'rust', constraint }],
};
await gitExec(cmd, execOptions);
}
async function cargoUpdatePrecise(
manifestPath: string,
updatedDeps: Upgrade[],
constraint: string | undefined,
): Promise<void> {
const cmds = [];
// First update individual dependencies to their `newVersion`. Necessary when
// using the `update-lockfile` rangeStrategy which doesn't touch Cargo.toml.
for (const dep of updatedDeps) {
// If the range is bumped in Cargo.toml, the old lockedVersion may no longer
// exist in Cargo's dependency graph, so let the --workspace update at the
// end re-resolve it instead.
if (dep.currentValue && dep.newValue && dep.currentValue !== dep.newValue) {
continue;
}
cmds.push(
`cargo update --config net.git-fetch-with-cli=true` +
` --manifest-path ${quote(manifestPath)}` +
` --package ${quote(`${dep.packageName}@${dep.lockedVersion}`)}` +
` --precise ${quote(dep.newVersion!)}`,
);
}
// Then update all dependencies that have been bumped in `Cargo.toml`.
cmds.push(
`cargo update --config net.git-fetch-with-cli=true --manifest-path ${quote(manifestPath)} --workspace`,
);
const execOptions: ExecOptions = {
docker: {},
toolConstraints: [{ toolName: 'rust', constraint }],
};
await gitExec(cmds, execOptions);
}
export async function updateArtifacts(
updateArtifact: UpdateArtifact,
): Promise<UpdateArtifactsResult[] | null> {
return await updateArtifactsImpl(updateArtifact);
}
async function updateArtifactsImpl(
{
packageFileName,
updatedDeps,
newPackageFileContent,
config,
}: UpdateArtifact,
recursionLimit = 10,
): Promise<UpdateArtifactsResult[] | null> {
logger.debug(`cargo.updateArtifacts(${packageFileName})`);
// For standalone package crates, the `Cargo.lock` will be in the same
// directory as `Cargo.toml` (ie. a sibling). For cargo workspaces, it
// will be further up.
const lockFileName = await findLocalSiblingOrParent(
packageFileName,
'Cargo.lock',
);
const existingLockFileContent = lockFileName
? await readLocalFile(lockFileName)
: null;
if (!existingLockFileContent || !lockFileName) {
logger.debug('No Cargo.lock found');
return null;
}
const { isLockFileMaintenance } = config;
if (!isLockFileMaintenance && !updatedDeps?.length) {
logger.debug('No more dependencies to update');
return [
{
file: {
type: 'addition',
path: lockFileName,
contents: existingLockFileContent,
},
},
];
}
const rustConstraint = await resolveToolConstraint(config, 'rust');
try {
await writeLocalFile(packageFileName, newPackageFileContent);
logger.debug(`Updating ${lockFileName}`);
if (isLockFileMaintenance) {
await cargoUpdate(packageFileName, true, rustConstraint);
} else {
const hasNonCrateDep = updatedDeps.some(
(dep) => dep.datasource !== CrateDatasource.id,
);
const crateDepWithoutLockedVersion = updatedDeps.find(
(dep) => !dep.lockedVersion && dep.datasource === CrateDatasource.id,
);
// Non-crate dependencies (like git ones) do not have locked versions.
// For crate dependencies, a locked version is expected.
// In both situations, perform a regular workspace lockfile update.
if (hasNonCrateDep || crateDepWithoutLockedVersion) {
// v8 ignore else -- needs a workspace update driven only by a non-crate dep
if (crateDepWithoutLockedVersion) {
// Only warn when a crate dependency has no locked version
logger.warn(
{ dependency: crateDepWithoutLockedVersion.depName },
'Missing locked version for dependency',
);
}
await cargoUpdate(packageFileName, false, rustConstraint);
} else {
// If all dependencies have locked versions then update them precisely.
await cargoUpdatePrecise(packageFileName, updatedDeps, rustConstraint);
}
}
logger.debug('Returning updated Cargo.lock');
const newCargoLockContent = await readLocalFile(lockFileName);
if (existingLockFileContent === newCargoLockContent) {
logger.debug('Cargo.lock is unchanged');
return null;
}
return [
{
file: {
type: 'addition',
path: lockFileName,
contents: newCargoLockContent,
},
},
];
} catch (err) {
// istanbul ignore if
if (err.message === TEMPORARY_ERROR) {
throw err;
}
// Sometimes `cargo update` will fail when a preceding dependency update
// causes another dependency to update. In this case we can no longer
// reference the dependency by its old version, so we filter it out
// and retry recursively.
const newCargoLockContent = await readLocalFile(lockFileName, 'utf8');
if (
recursionLimit > 0 &&
newCargoLockContent &&
regEx(/error: package ID specification/).test(err.stderr)
) {
const versions = extractLockFileContentVersions(newCargoLockContent);
const newUpdatedDeps = updatedDeps.filter(
(dep) =>
!coerceArray(versions?.get(dep.packageName!)).includes(
dep.newVersion!,
),
);
// v8 ignore else -- this retry only runs when a dep was already current
if (newUpdatedDeps.length < updatedDeps.length) {
logger.debug(
'Dependency already up to date - reattempting recursively',
);
return updateArtifactsImpl(
{
packageFileName,
updatedDeps: newUpdatedDeps,
newPackageFileContent,
config,
},
recursionLimit - 1,
);
}
}
logger.debug({ err }, 'Failed to update Cargo lock file');
return [
{
artifactError: {
fileName: lockFileName,
stderr: err.message,
},
},
];
}
}