Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Edit a Feature pinned version via upgrade cmd #684

Merged
merged 5 commits into from
Nov 21, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions src/spec-configuration/containerFeaturesConfiguration.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ import { request } from '../spec-utils/httpRequest';
import { fetchOCIFeature, tryGetOCIFeatureSet, fetchOCIFeatureManifestIfExistsFromUserIdentifier } from './containerFeaturesOCI';
import { uriToFsPath } from './configurationCommonUtils';
import { CommonParams, ManifestContainer, OCIManifest, OCIRef, getRef, getVersionsStrictSorted } from './containerCollectionsOCI';
import { Lockfile, readLockfile, writeLockfile } from './lockfile';
import { Lockfile, generateLockfile, readLockfile, writeLockfile } from './lockfile';
import { computeDependsOnInstallationOrder } from './containerFeaturesOrder';
import { logFeatureAdvisories } from './featureAdvisories';
import { getEntPasswdShellCommand } from '../spec-common/commonUtils';
Expand Down Expand Up @@ -570,7 +570,7 @@ export async function generateFeaturesConfig(params: ContainerFeatureInternalPar
await fetchFeatures(params, featuresConfig, locallyCachedFeatureSet, dstFolder, localFeaturesFolder, ociCacheDir, lockfile);

await logFeatureAdvisories(params, featuresConfig);
await writeLockfile(params, config, featuresConfig, initLockfile);
await writeLockfile(params, config, await generateLockfile(featuresConfig), initLockfile);
return featuresConfig;
}

Expand Down
33 changes: 15 additions & 18 deletions src/spec-configuration/lockfile.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,20 +13,8 @@ export interface Lockfile {
features: Record<string, { version: string; resolved: string; integrity: string }>;
}

export async function writeLockfile(params: ContainerFeatureInternalParams, config: DevContainerConfig, featuresConfig: FeaturesConfig, forceInitLockfile?: boolean, dryRun?: boolean): Promise<string | undefined> {
joshspicer marked this conversation as resolved.
Show resolved Hide resolved
const lockfilePath = getLockfilePath(config);
const oldLockfileContent = await readLocalFile(lockfilePath)
.catch(err => {
if (err?.code !== 'ENOENT') {
throw err;
}
});

if (!forceInitLockfile && !oldLockfileContent && !params.experimentalLockfile && !params.experimentalFrozenLockfile) {
return;
}

const lockfile: Lockfile = featuresConfig.featureSets
export async function generateLockfile(featuresConfig: FeaturesConfig): Promise<Lockfile> {
return featuresConfig.featureSets
.map(f => [f, f.sourceInformation] as const)
.filter((tup): tup is [FeatureSet, OCISourceInformation | DirectTarballSourceInformation] => ['oci', 'direct-tarball'].indexOf(tup[1].type) !== -1)
.map(([set, source]) => {
Expand All @@ -50,13 +38,22 @@ export async function writeLockfile(params: ContainerFeatureInternalParams, conf
}, {
features: {} as Record<string, { version: string; resolved: string; integrity: string }>,
});
}

const newLockfileContentString = JSON.stringify(lockfile, null, 2);
export async function writeLockfile(params: ContainerFeatureInternalParams, config: DevContainerConfig, lockfile: Lockfile, forceInitLockfile?: boolean): Promise<string | undefined> {
const lockfilePath = getLockfilePath(config);
const oldLockfileContent = await readLocalFile(lockfilePath)
.catch(err => {
if (err?.code !== 'ENOENT') {
throw err;
}
});

if (dryRun) {
return newLockfileContentString;
if (!forceInitLockfile && !oldLockfileContent && !params.experimentalLockfile && !params.experimentalFrozenLockfile) {
return;
}

const newLockfileContentString = JSON.stringify(lockfile, null, 2);
const newLockfileContent = Buffer.from(newLockfileContentString);
if (params.experimentalFrozenLockfile && !oldLockfileContent) {
throw new Error('Lockfile does not exist.');
Expand All @@ -73,7 +70,7 @@ export async function writeLockfile(params: ContainerFeatureInternalParams, conf
export async function readLockfile(config: DevContainerConfig): Promise<{ lockfile?: Lockfile; initLockfile?: boolean }> {
try {
const content = await readLocalFile(getLockfilePath(config));
// If empty file, use as maker to initialize lockfile when build completes.
// If empty file, use as marker to initialize lockfile when build completes.
if (content.toString().trim() === '') {
return { initLockfile: true };
}
Expand Down
118 changes: 97 additions & 21 deletions src/spec-node/upgradeCommand.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,17 +6,18 @@ import { createLog } from './devContainers';
import { getPackageConfig } from '../spec-utils/product';
import { DockerCLIParameters } from '../spec-shutdown/dockerUtils';
import path from 'path';
import { getCLIHost } from '../spec-common/cliHost';
import { CLIHost, getCLIHost } from '../spec-common/cliHost';
import { loadNativeModule } from '../spec-common/commonUtils';
import { URI } from 'vscode-uri';
import { workspaceFromPath } from '../spec-utils/workspaces';
import { Workspace, workspaceFromPath } from '../spec-utils/workspaces';
import { getDefaultDevContainerConfigPath, getDevContainerConfigPathIn, uriToFsPath } from '../spec-configuration/configurationCommonUtils';
import { readDevContainerConfigFile } from './configContainer';
import { ContainerError } from '../spec-common/errors';
import { getCacheFolder } from './utils';
import { getLockfilePath, writeLockfile } from '../spec-configuration/lockfile';
import { writeLocalFile } from '../spec-utils/pfs';
import { Lockfile, generateLockfile, getLockfilePath, writeLockfile } from '../spec-configuration/lockfile';
import { isLocalFile, readLocalFile, writeLocalFile } from '../spec-utils/pfs';
import { readFeaturesConfig } from './featureUtils';
import { DevContainerConfig } from '../spec-configuration/configuration';

export function featuresUpgradeOptions(y: Argv) {
return y
Expand All @@ -27,6 +28,22 @@ export function featuresUpgradeOptions(y: Argv) {
'config': { type: 'string', description: 'devcontainer.json path. The default is to use .devcontainer/devcontainer.json or, if that does not exist, .devcontainer.json in the workspace folder.' },
'log-level': { choices: ['error' as 'error', 'info' as 'info', 'debug' as 'debug', 'trace' as 'trace'], default: 'info' as 'info', description: 'Log level.' },
'dry-run': { type: 'boolean', description: 'Write generated lockfile to standard out instead of to disk.' },
// Added for dependabot
'feature': { hidden: true, type: 'string', alias: 'f', description: 'Upgrade the version requirements of a given Feature (and its dependencies). Then, upgrade the lockfile. Must supply \'--target-version\'.' },
'target-version': { hidden: true, type: 'string', alias: 'v', description: 'The major (x), minor (x.y), or patch version (x.y.z) of the Feature to pin in devcontainer.json. Must supply a \'--feature\'.' },
})
.check(argv => {
if (argv.feature && !argv['target-version'] || !argv.feature && argv['target-version']) {
throw new Error('The \'--target-version\' and \'--feature\' flag must be used together.');
}

if (argv['target-version']) {
const targetVersion = argv['target-version'];
if (!targetVersion.match(/^\d+(\.\d+(\.\d+)?)?$/)) {
throw new Error(`Invalid version '${targetVersion}'. Must be in the form of 'x', 'x.y', or 'x.y.z'`);
}
}
return true;
});
}

Expand All @@ -43,6 +60,8 @@ async function featuresUpgrade({
'docker-compose-path': dockerComposePath,
'log-level': inputLogLevel,
'dry-run': dryRun,
feature: feature,
'target-version': targetVersion,
}: FeaturesUpgradeArgs) {
const disposables: (() => Promise<unknown> | undefined)[] = [];
const dispose = async () => {
Expand Down Expand Up @@ -77,11 +96,7 @@ async function featuresUpgrade({

const workspace = workspaceFromPath(cliHost.path, workspaceFolder);
const configPath = configFile ? configFile : await getDevContainerConfigPathIn(cliHost, workspace.configFolderPath);
const configs = configPath && await readDevContainerConfigFile(cliHost, workspace, configPath, true, output) || undefined;
if (!configs) {
throw new ContainerError({ description: `Dev container config (${uriToFsPath(configFile || getDefaultDevContainerConfigPath(cliHost, workspace!.configFolderPath), cliHost.platform)}) not found.` });
}
const config = configs.config.config;
let config = await getConfig(configPath, cliHost, workspace, output, configFile);
const cacheFolder = await getCacheFolder(cliHost);
const params = {
extensionPath,
Expand All @@ -93,25 +108,31 @@ async function featuresUpgrade({
platform: cliHost.platform,
};

const bold = process.stdout.isTTY ? '\x1b[1m' : '';
const clear = process.stdout.isTTY ? '\x1b[0m' : '';
output.raw(`${bold}Upgrading lockfile...\n${clear}\n`, LogLevel.Info);
if (feature && targetVersion) {
output.write(`Updating '${feature}' to '${targetVersion}' in devcontainer.json`, LogLevel.Info);
// Update Feature version tag in devcontainer.json
await updateFeatureVersionInConfig(params, config, config.configFilePath!.fsPath, feature, targetVersion);
// Re-read config for subsequent lockfile generation
config = await getConfig(configPath, cliHost, workspace, output, configFile);
}

// Truncate existing lockfile
const lockfilePath = getLockfilePath(config);
await writeLocalFile(lockfilePath, '');
// Update lockfile
const featuresConfig = await readFeaturesConfig(dockerParams, pkg, config, extensionPath, false, {});
if (!featuresConfig) {
throw new ContainerError({ description: `Failed to update lockfile` });
}
const lockFile = await writeLockfile(params, config, featuresConfig, true, dryRun);

const lockfile: Lockfile = await generateLockfile(featuresConfig);

if (dryRun) {
if (!lockFile) {
throw new ContainerError({ description: `Failed to generate lockfile.` });
}
console.log(lockFile);
console.log(JSON.stringify(lockfile, null, 2));
return;
}

// Truncate any existing lockfile
const lockfilePath = getLockfilePath(config);
await writeLocalFile(lockfilePath, '');
// Update lockfile
await writeLockfile(params, config, lockfile, true);
} catch (err) {
if (output) {
output.write(err && (err.stack || err.message) || String(err));
Expand All @@ -123,4 +144,59 @@ async function featuresUpgrade({
}
await dispose();
process.exit(0);
}

async function updateFeatureVersionInConfig(params: { output: Log }, config: DevContainerConfig, configPath: string, targetFeature: string, targetVersion: string) {
const { output } = params;

if (!config.features) {
// No Features in config to upgrade
output.write(`No Features found in '${configPath}'.`);
return;
}

if (!configPath || !(await isLocalFile(configPath))) {
throw new ContainerError({ description: `Error running upgrade command. Config path '${configPath}' does not exist.` });
}

const configText = await readLocalFile(configPath);
const previousConfigText: string = configText.toString();
let updatedText: string = configText.toString();

const targetFeatureNoVersion = getFeatureIdWithoutVersion(targetFeature);
for (const [userFeatureId, _] of Object.entries(config.features)) {
if (targetFeatureNoVersion !== getFeatureIdWithoutVersion(userFeatureId)) {
continue;
}
updatedText = upgradeFeatureKeyInConfig(updatedText, userFeatureId, `${targetFeatureNoVersion}:${targetVersion}`);
break;
}

output.write(updatedText, LogLevel.Trace);
if (updatedText === previousConfigText) {
output.write(`No changes to config file: ${configPath}\n`, LogLevel.Trace);
return;
}

output.write(`Updating config file: '${configPath}'`, LogLevel.Info);
await writeLocalFile(configPath, updatedText);
}

function upgradeFeatureKeyInConfig(configText: string, current: string, updated: string) {
const featureIdRegex = new RegExp(current, 'g');
return configText.replace(featureIdRegex, updated);
}

async function getConfig(configPath: URI | undefined, cliHost: CLIHost, workspace: Workspace, output: Log, configFile: URI | undefined): Promise<DevContainerConfig> {
const configs = configPath && await readDevContainerConfigFile(cliHost, workspace, configPath, true, output) || undefined;
if (!configs) {
throw new ContainerError({ description: `Dev container config (${uriToFsPath(configFile || getDefaultDevContainerConfigPath(cliHost, workspace!.configFolderPath), cliHost.platform)}) not found.` });
}
return configs.config.config;
}

const lastDelimiter = /[:@][^/]*$/;
function getFeatureIdWithoutVersion(featureId: string) {
const m = lastDelimiter.exec(featureId);
return m ? featureId.substring(0, m.index) : featureId;
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
.devcontainer-lock.json
.devcontainer.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
{
"image": "mcr.microsoft.com/devcontainers/base",
// Comment
"features": {
"ghcr.io/codspace/versioning/bar:1.0.0": {},
// Comment
"ghcr.io/codspace/versioning/foo:2": { // Comment
"hello": "world" // Comment
}
// Comment
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
{
"image": "mcr.microsoft.com/devcontainers/base",
// Comment
"features": {
"ghcr.io/codspace/versioning/bar:1.0.0": {},
// Comment
"ghcr.io/codspace/versioning/foo:1": { // Comment
"hello": "world" // Comment
}
// Comment
}
}
18 changes: 18 additions & 0 deletions src/test/container-features/lockfile.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -146,6 +146,24 @@ describe('Lockfile', function () {
assert.ok(lockfile.features['ghcr.io/codspace/dependson/A:2']);
});

it('upgrade command with --feature', async () => {
const workspaceFolder = path.join(__dirname, 'configs/lockfile-upgrade-feature');
await cpLocal(path.join(workspaceFolder, 'input.devcontainer.json'), path.join(workspaceFolder, '.devcontainer.json'));

const res = await shellExec(`${cli} upgrade --dry-run --workspace-folder ${workspaceFolder} --feature ghcr.io/codspace/versioning/foo --target-version 2`);

// Check devcontainer.json was updated
const actual = await readLocalFile(path.join(workspaceFolder, '.devcontainer.json'));
const expected = await readLocalFile(path.join(workspaceFolder, 'expected.devcontainer.json'));
assert.equal(actual.toString(), expected.toString());

// Check lockfile was updated
const lockfile = JSON.parse(res.stdout);
assert.ok(lockfile);
assert.ok(lockfile.features);
assert.ok(lockfile.features['ghcr.io/codspace/versioning/foo:2'].version === '2.11.1');
});

it('OCI feature integrity', async () => {
const workspaceFolder = path.join(__dirname, 'configs/lockfile-oci-integrity');

Expand Down
Loading