Skip to content
Open
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
147 changes: 147 additions & 0 deletions packages/angular/cli/src/package-managers/min-release-age.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,147 @@
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/

/**
* @fileoverview This file contains the logic for reading the user-configured
* "minimum release age" (a.k.a. install cooldown) from the active package
* manager. When configured, the CLI must respect the same gate during
* automatic version selection (e.g. `ng update`, `ng add`); otherwise it can
* pick a version that the package manager itself will refuse to install.
*
* Coverage notes:
* - **npm** reads `min-release-age` from `.npmrc` (value in days).
* See https://docs.npmjs.com/cli/v11/using-npm/config#min-release-age.
* - **pnpm 10.x** reads `minimum-release-age` from `.npmrc` (value in minutes).
* pnpm 11+ migrated the canonical setting to `minimumReleaseAge` in
* `pnpm-workspace.yaml`, which is not currently parsed by this utility.
* - **yarn-classic** has no native cooldown, but mirrors npm's `.npmrc`
* parsing, so we honor `min-release-age` when present.
* - **yarn (berry)** uses `npmMinimalAgeGate` in `.yarnrc.yml`, which is not
* currently parsed by this utility.
* - **bun** uses `install.minimumReleaseAge` in `bunfig.toml`, which is not
* currently parsed by this utility.
*/

import * as ini from 'ini';
import { dirname, join } from 'node:path';
import { Host } from './host';
import { Logger } from './logger';
import { PackageManagerDescriptor } from './package-manager-descriptor';

const MS_PER_MINUTE = 60_000;
const MS_PER_DAY = 86_400_000;

/**
* Converts a value in `unit` to milliseconds.
*/
function toMs(value: number, unit: 'days' | 'minutes'): number {
return unit === 'days' ? value * MS_PER_DAY : value * MS_PER_MINUTE;
}

/**
* Reads and merges `.npmrc` files starting at `startDir` and walking up the
* directory tree until either a git repository root or the filesystem root is
* reached.
*
* Values defined in directories closer to `startDir` take precedence over
* those defined in ancestor directories. This mirrors how `npm` itself
* resolves project-level configuration.
*
* @returns The merged options as a plain object. Returns an empty object when
* no `.npmrc` files are found.
*/
async function readNpmrcChain(
host: Host,
startDir: string,
logger?: Logger,
): Promise<Record<string, unknown>> {
const directoriesToVisit: string[] = [];

let currentDir = startDir;
while (true) {
directoriesToVisit.push(currentDir);

// Stop walking when we reach a git repository root, mirroring `discovery.ts`.
// `.git` may be a directory (regular repo), a file (submodules and
// worktrees use a `gitdir:` pointer file), or absent. We just need to
// know whether it exists; `host.stat` rejects when it doesn't.
try {
await host.stat(join(currentDir, '.git'));
break;
} catch {
// No `.git` here; continue searching upwards.
}
Comment thread
crimsondhaks marked this conversation as resolved.

const parentDir = dirname(currentDir);
if (parentDir === currentDir) {
// Reached the filesystem root.
break;
}
currentDir = parentDir;
}

// Apply ancestor configs first so that closer-to-cwd values override them.
const merged: Record<string, unknown> = {};
for (let i = directoriesToVisit.length - 1; i >= 0; i--) {
const npmrcPath = join(directoriesToVisit[i], '.npmrc');
let contents: string;
try {
contents = await host.readFile(npmrcPath);
} catch {
// File not present or unreadable.
continue;
}

try {
const parsed = ini.parse(contents) as Record<string, unknown>;
Object.assign(merged, parsed);
logger?.debug(`Loaded options from '${npmrcPath}'.`);
} catch (e) {
logger?.debug(`Failed to parse '${npmrcPath}': ${e}.`);
}
}

return merged;
}

/**
* Determines the minimum release age (in milliseconds) configured for the
* given package manager.
*
* @param host A `Host` instance for reading configuration files.
* @param cwd The directory from which to start the configuration search.
* @param descriptor The active package manager's descriptor.
* @param logger An optional logger instance.
* @returns A non-negative number of milliseconds. Returns `0` when the active
* package manager has no minimum release age configured (or when this
* utility does not yet support reading the relevant configuration source).
*/
export async function getMinReleaseAgeMs(
host: Host,
cwd: string,
descriptor: PackageManagerDescriptor,
logger?: Logger,
): Promise<number> {
const config = descriptor.minReleaseAge;
if (!config) {
return 0;
}

const npmrc = await readNpmrcChain(host, cwd, logger);
const rawValue = npmrc[config.key];
if (rawValue === undefined || rawValue === null || rawValue === '') {
return 0;
}

const parsed = Number(rawValue);
if (!Number.isFinite(parsed) || parsed <= 0) {
return 0;
}

return toMs(parsed, config.unit);
}
105 changes: 105 additions & 0 deletions packages/angular/cli/src/package-managers/min-release-age_spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,105 @@
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/

import { getMinReleaseAgeMs } from './min-release-age';
import { SUPPORTED_PACKAGE_MANAGERS } from './package-manager-descriptor';
import { MockHost } from './testing/mock-host';

const MS_PER_MINUTE = 60_000;
const MS_PER_DAY = 86_400_000;

describe('getMinReleaseAgeMs', () => {
it('returns 0 when the descriptor has no minReleaseAge configuration', async () => {
const host = new MockHost();

expect(await getMinReleaseAgeMs(host, '/project', SUPPORTED_PACKAGE_MANAGERS.bun)).toBe(0);
});

it('returns 0 when no .npmrc file is present', async () => {
const host = new MockHost();
host.setDirectory('/project/.git');

expect(await getMinReleaseAgeMs(host, '/project', SUPPORTED_PACKAGE_MANAGERS.npm)).toBe(0);
});

it('reads npm `min-release-age` (in days) from project .npmrc', async () => {
const host = new MockHost();
host.setDirectory('/project/.git');
host.setFile('/project/.npmrc', 'min-release-age=7\n');

expect(await getMinReleaseAgeMs(host, '/project', SUPPORTED_PACKAGE_MANAGERS.npm)).toBe(
7 * MS_PER_DAY,
);
});

it('reads pnpm `minimum-release-age` (in minutes) from project .npmrc', async () => {
const host = new MockHost();
host.setDirectory('/project/.git');
host.setFile('/project/.npmrc', 'minimum-release-age=1440\n');

expect(await getMinReleaseAgeMs(host, '/project', SUPPORTED_PACKAGE_MANAGERS.pnpm)).toBe(
1440 * MS_PER_MINUTE,
);
});

it('does not pick up an unrelated key', async () => {
const host = new MockHost();
host.setDirectory('/project/.git');
host.setFile('/project/.npmrc', 'min-release-age=7\n');

// pnpm uses `minimum-release-age`, not `min-release-age`.
expect(await getMinReleaseAgeMs(host, '/project', SUPPORTED_PACKAGE_MANAGERS.pnpm)).toBe(0);
});

it('walks up the directory tree until reaching the .git root', async () => {
const host = new MockHost();
host.setDirectory('/repo/.git');
host.setFile('/repo/.npmrc', 'min-release-age=3\n');

expect(
await getMinReleaseAgeMs(host, '/repo/packages/app', SUPPORTED_PACKAGE_MANAGERS.npm),
).toBe(3 * MS_PER_DAY);
});

it('lets values closer to the project override ancestor values', async () => {
const host = new MockHost();
host.setDirectory('/repo/.git');
host.setFile('/repo/.npmrc', 'min-release-age=10\n');
host.setFile('/repo/packages/app/.npmrc', 'min-release-age=2\n');

expect(
await getMinReleaseAgeMs(host, '/repo/packages/app', SUPPORTED_PACKAGE_MANAGERS.npm),
).toBe(2 * MS_PER_DAY);
});

it('treats a `.git` file as a repo root (git submodules and worktrees)', async () => {
const host = new MockHost();
// In a submodule or worktree `.git` is a regular file containing a
// `gitdir:` pointer, not a directory. The walk must still stop here.
host.setFile('/repo/.git', 'gitdir: /elsewhere/.git/modules/repo\n');
host.setFile('/repo/.npmrc', 'min-release-age=4\n');

expect(await getMinReleaseAgeMs(host, '/repo', SUPPORTED_PACKAGE_MANAGERS.npm)).toBe(
4 * MS_PER_DAY,
);
});

it('returns 0 for non-positive or non-numeric values', async () => {
const host = new MockHost();
host.setDirectory('/project/.git');
host.setFile('/project/.npmrc', 'min-release-age=not-a-number\n');

expect(await getMinReleaseAgeMs(host, '/project', SUPPORTED_PACKAGE_MANAGERS.npm)).toBe(0);

host.setFile('/project/.npmrc', 'min-release-age=0\n');
expect(await getMinReleaseAgeMs(host, '/project', SUPPORTED_PACKAGE_MANAGERS.npm)).toBe(0);

host.setFile('/project/.npmrc', 'min-release-age=-5\n');
expect(await getMinReleaseAgeMs(host, '/project', SUPPORTED_PACKAGE_MANAGERS.npm)).toBe(0);
});
});
Original file line number Diff line number Diff line change
Expand Up @@ -120,6 +120,27 @@ export interface PackageManagerDescriptor {

/** A function that checks if a structured error represents a "package not found" error. */
readonly isNotFound: (error: ErrorInfo) => boolean;

/**
* Describes how to read the user-configured "minimum release age" (also
* known as the install cooldown) for this package manager.
*
* When set, the CLI uses this configuration to filter out versions that
* are too new during automatic version selection (e.g. `ng update`,
* `ng add`). This prevents the CLI from picking a version that the
* underlying package manager would subsequently refuse to install.
*
* Set to `undefined` for package managers whose configuration is not yet
* supported here. The cooldown filter then becomes a no-op for those
* package managers, which preserves the existing behavior.
*/
readonly minReleaseAge?: {
/** The setting name to read from `.npmrc`. */
readonly key: string;

/** The unit the setting value is expressed in. */
readonly unit: 'days' | 'minutes';
};
}

/** A type that represents the name of a supported package manager. */
Expand Down Expand Up @@ -175,6 +196,8 @@ export const SUPPORTED_PACKAGE_MANAGERS = {
getError: parseNpmLikeError,
},
isNotFound: isKnownNotFound,
// npm 11.10+ honors `min-release-age` (in days) from `.npmrc`.
minReleaseAge: { key: 'min-release-age', unit: 'days' },
},
yarn: {
binary: 'yarn',
Expand Down Expand Up @@ -228,6 +251,8 @@ export const SUPPORTED_PACKAGE_MANAGERS = {
getError: parseYarnClassicError,
},
isNotFound: isKnownNotFound,
// Yarn classic has no native cooldown but reads `.npmrc`, so honor `min-release-age`.
minReleaseAge: { key: 'min-release-age', unit: 'days' },
},
pnpm: {
binary: 'pnpm',
Expand Down Expand Up @@ -255,6 +280,9 @@ export const SUPPORTED_PACKAGE_MANAGERS = {
getError: parseNpmLikeError,
},
isNotFound: isKnownNotFound,
// pnpm 10.x reads `minimum-release-age` from `.npmrc` (in minutes).
// pnpm 11+ uses `minimumReleaseAge` in `pnpm-workspace.yaml`, which is not handled here.
minReleaseAge: { key: 'minimum-release-age', unit: 'minutes' },
},
bun: {
binary: 'bun',
Expand Down
Loading
Loading