Skip to content

Commit e5bf35e

Browse files
alan-agius4dgp1130
authored andcommitted
feat(@angular/cli): add ng cache command
With this change we create a new command `ng cache` that can be used control and check the disk cache settings. This command has 4 subcommands - `ng cache enable` which can be used to enable the cache. - `ng cache disable` which can be used to disable the cache. - `ng cache clean` which can be used to delete the cache from disk. - `ng cache info` which will print statistics and information about the cache.
1 parent eef17b3 commit e5bf35e

10 files changed

Lines changed: 448 additions & 0 deletions

File tree

‎packages/angular/cli/src/command-builder/command-runner.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@ import { Parser } from 'yargs/helpers';
1212
import { AddCommandModule } from '../commands/add/cli';
1313
import { AnalyticsCommandModule } from '../commands/analytics/cli';
1414
import { BuildCommandModule } from '../commands/build/cli';
15+
import { CacheCommandModule } from '../commands/cache/cli';
1516
import { ConfigCommandModule } from '../commands/config/cli';
1617
import { DeployCommandModule } from '../commands/deploy/cli';
1718
import { DocCommandModule } from '../commands/doc/cli';
@@ -51,6 +52,7 @@ const COMMANDS = [
5152
NewCommandModule,
5253
UpdateCommandModule,
5354
RunCommandModule,
55+
CacheCommandModule,
5456
].sort(); // Will be sorted by class name.
5557

5658
const yargsParser = Parser as unknown as typeof Parser.default;
Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
/**
2+
* @license
3+
* Copyright Google LLC All Rights Reserved.
4+
*
5+
* Use of this source code is governed by an MIT-style license that can be
6+
* found in the LICENSE file at https://angular.io/license
7+
*/
8+
9+
import { promises as fs } from 'fs';
10+
import { Argv } from 'yargs';
11+
import {
12+
CommandModule,
13+
CommandModuleImplementation,
14+
CommandScope,
15+
} from '../../../command-builder/command-module';
16+
import { getCacheConfig } from '../utilities';
17+
18+
export class CacheCleanModule extends CommandModule implements CommandModuleImplementation {
19+
command = 'clean';
20+
describe = 'Deletes persistent disk cache from disk.';
21+
longDescriptionPath: string | undefined;
22+
static override scope: CommandScope.In;
23+
24+
builder(localYargs: Argv): Argv {
25+
return localYargs.strict();
26+
}
27+
28+
run(): Promise<void> {
29+
const { path } = getCacheConfig(this.context.workspace);
30+
31+
return fs.rm(path, {
32+
force: true,
33+
recursive: true,
34+
maxRetries: 3,
35+
});
36+
}
37+
}
Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
/**
2+
* @license
3+
* Copyright Google LLC All Rights Reserved.
4+
*
5+
* Use of this source code is governed by an MIT-style license that can be
6+
* found in the LICENSE file at https://angular.io/license
7+
*/
8+
9+
import { join } from 'path';
10+
import { Argv } from 'yargs';
11+
import {
12+
CommandModule,
13+
CommandModuleImplementation,
14+
CommandScope,
15+
Options,
16+
} from '../../command-builder/command-module';
17+
import {
18+
addCommandModuleToYargs,
19+
demandCommandFailureMessage,
20+
} from '../../command-builder/utilities/command';
21+
import { CacheCleanModule } from './clean/cli';
22+
import { CacheInfoCommandModule } from './info/cli';
23+
import { CacheDisableModule, CacheEnableModule } from './settings/cli';
24+
25+
export class CacheCommandModule extends CommandModule implements CommandModuleImplementation {
26+
command = 'cache';
27+
describe = 'Configure persistent disk cache and retrieve cache statistics.';
28+
longDescriptionPath = join(__dirname, 'long-description.md');
29+
static override scope: CommandScope.In;
30+
31+
builder(localYargs: Argv): Argv {
32+
const subcommands = [
33+
CacheEnableModule,
34+
CacheDisableModule,
35+
CacheCleanModule,
36+
CacheInfoCommandModule,
37+
].sort();
38+
39+
for (const module of subcommands) {
40+
localYargs = addCommandModuleToYargs(localYargs, module, this.context);
41+
}
42+
43+
return localYargs.demandCommand(1, demandCommandFailureMessage).strict();
44+
}
45+
46+
run(_options: Options<{}>): void {}
47+
}
Lines changed: 99 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,99 @@
1+
/**
2+
* @license
3+
* Copyright Google LLC All Rights Reserved.
4+
*
5+
* Use of this source code is governed by an MIT-style license that can be
6+
* found in the LICENSE file at https://angular.io/license
7+
*/
8+
9+
import { tags } from '@angular-devkit/core';
10+
import { promises as fs } from 'fs';
11+
import { join } from 'path';
12+
import { Argv } from 'yargs';
13+
import {
14+
CommandModule,
15+
CommandModuleImplementation,
16+
CommandScope,
17+
} from '../../../command-builder/command-module';
18+
import { isCI } from '../../../utilities/environment-options';
19+
import { getCacheConfig } from '../utilities';
20+
21+
export class CacheInfoCommandModule extends CommandModule implements CommandModuleImplementation {
22+
command = 'info';
23+
describe = 'Prints persistent disk cache configuration and statistics in the console.';
24+
longDescriptionPath?: string | undefined;
25+
static override scope: CommandScope.In;
26+
27+
builder(localYargs: Argv): Argv {
28+
return localYargs.strict();
29+
}
30+
31+
async run(): Promise<void> {
32+
const { path, environment, enabled } = getCacheConfig(this.context.workspace);
33+
34+
this.context.logger.info(tags.stripIndents`
35+
Enabled: ${enabled ? 'yes' : 'no'}
36+
Environment: ${environment}
37+
Path: ${path}
38+
Size on disk: ${await this.getSizeOfDirectory(path)}
39+
Effective status on current machine: ${this.effectiveEnabledStatus() ? 'enabled' : 'disabled'}
40+
`);
41+
}
42+
43+
private async getSizeOfDirectory(path: string): Promise<string> {
44+
const directoriesStack = [path];
45+
let size = 0;
46+
47+
while (directoriesStack.length) {
48+
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
49+
const dirPath = directoriesStack.pop()!;
50+
let entries: string[] = [];
51+
52+
try {
53+
entries = await fs.readdir(dirPath);
54+
} catch {}
55+
56+
for (const entry of entries) {
57+
const entryPath = join(dirPath, entry);
58+
const stats = await fs.stat(entryPath);
59+
60+
if (stats.isDirectory()) {
61+
directoriesStack.push(entryPath);
62+
}
63+
64+
size += stats.size;
65+
}
66+
}
67+
68+
return this.formatSize(size);
69+
}
70+
71+
private formatSize(size: number): string {
72+
if (size <= 0) {
73+
return '0 bytes';
74+
}
75+
76+
const abbreviations = ['bytes', 'kB', 'MB', 'GB'];
77+
const index = Math.floor(Math.log(size) / Math.log(1024));
78+
const roundedSize = size / Math.pow(1024, index);
79+
// bytes don't have a fraction
80+
const fractionDigits = index === 0 ? 0 : 2;
81+
82+
return `${roundedSize.toFixed(fractionDigits)} ${abbreviations[index]}`;
83+
}
84+
85+
private effectiveEnabledStatus(): boolean {
86+
const { enabled, environment } = getCacheConfig(this.context.workspace);
87+
88+
if (enabled) {
89+
switch (environment) {
90+
case 'ci':
91+
return isCI;
92+
case 'local':
93+
return !isCI;
94+
}
95+
}
96+
97+
return enabled;
98+
}
99+
}
Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
Angular CLI saves a number of cachable operations on disk by default.
2+
3+
When you re-run the same build, the build system restores the state of the previous build and re-uses previously performed operations, which decreases the time taken to build and test your applications and libraries.
4+
5+
To amend the default cache settings, add the `cli.cache` object to your [Workspace Configuration](guide/workspace-config).
6+
The object goes under `cli.cache` at the top level of the file, outside the `projects` sections.
7+
8+
```jsonc
9+
{
10+
"$schema": "./node_modules/@angular/cli/lib/config/schema.json",
11+
"version": 1,
12+
"cli": {
13+
"cache": {
14+
// ...
15+
}
16+
},
17+
"projects": {}
18+
}
19+
```
20+
21+
For more information, see [cache options](guide/workspace-config#cache-options).
22+
23+
### Cache environments
24+
25+
By default, disk cache is only enabled for local environments. The value of environment can be one of the following:
26+
27+
- `all` - allows disk cache on all machines.
28+
- `local` - allows disk cache only on development machines.
29+
- `ci` - allows disk cache only on continuous integration (Ci) systems.
30+
31+
To change the environment setting to `all`, run the following command:
32+
33+
```bash
34+
ng config cli.cache.environment all
35+
```
36+
37+
For more information, see `environment` in [cache options](guide/workspace-config#cache-options).
38+
39+
<div class="alert is-helpful">
40+
41+
The Angular CLI checks for the presence and value of the `CI` environment variable to determine in which environment it is running.
42+
43+
</div>
44+
45+
### Cache path
46+
47+
By default, `.angular/cache` is used as a base directory to store cache results.
48+
49+
To change this path to `.cache/ng`, run the following command:
50+
51+
```bash
52+
ng config cli.cache.path ".cache/ng"
53+
```
Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
/**
2+
* @license
3+
* Copyright Google LLC All Rights Reserved.
4+
*
5+
* Use of this source code is governed by an MIT-style license that can be
6+
* found in the LICENSE file at https://angular.io/license
7+
*/
8+
9+
import { Argv } from 'yargs';
10+
import {
11+
CommandModule,
12+
CommandModuleImplementation,
13+
CommandScope,
14+
} from '../../../command-builder/command-module';
15+
import { updateCacheConfig } from '../utilities';
16+
17+
export class CacheDisableModule extends CommandModule implements CommandModuleImplementation {
18+
command = 'disable';
19+
aliases = 'off';
20+
describe = 'Disables persistent disk cache for all projects in the workspace.';
21+
longDescriptionPath: string | undefined;
22+
static override scope: CommandScope.In;
23+
24+
builder(localYargs: Argv): Argv {
25+
return localYargs;
26+
}
27+
28+
run(): void {
29+
updateCacheConfig('enabled', false);
30+
}
31+
}
32+
33+
export class CacheEnableModule extends CommandModule implements CommandModuleImplementation {
34+
command = 'enable';
35+
aliases = 'on';
36+
describe = 'Enables disk cache for all projects in the workspace.';
37+
longDescriptionPath: string | undefined;
38+
static override scope: CommandScope.In;
39+
40+
builder(localYargs: Argv): Argv {
41+
return localYargs;
42+
}
43+
44+
run(): void {
45+
updateCacheConfig('enabled', true);
46+
}
47+
}
Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
/**
2+
* @license
3+
* Copyright Google LLC All Rights Reserved.
4+
*
5+
* Use of this source code is governed by an MIT-style license that can be
6+
* found in the LICENSE file at https://angular.io/license
7+
*/
8+
9+
import { isJsonObject } from '@angular-devkit/core';
10+
import { resolve } from 'path';
11+
import { Cache, Environment } from '../../../lib/config/workspace-schema';
12+
import { AngularWorkspace, getWorkspaceRaw } from '../../utilities/config';
13+
14+
export function updateCacheConfig<K extends keyof Cache>(key: K, value: Cache[K]): void {
15+
const [localWorkspace] = getWorkspaceRaw('local');
16+
if (!localWorkspace) {
17+
throw new Error('Cannot find workspace configuration file.');
18+
}
19+
20+
localWorkspace.modify(['cli', 'cache', key], value);
21+
localWorkspace.save();
22+
}
23+
24+
export function getCacheConfig(workspace: AngularWorkspace | undefined): Required<Cache> {
25+
if (!workspace) {
26+
throw new Error(`Cannot retrieve cache configuration as workspace is not defined.`);
27+
}
28+
29+
const defaultSettings: Required<Cache> = {
30+
path: resolve(workspace.basePath, '.angular/cache'),
31+
environment: Environment.Local,
32+
enabled: true,
33+
};
34+
35+
const cliSetting = workspace.extensions['cli'];
36+
if (!cliSetting || !isJsonObject(cliSetting)) {
37+
return defaultSettings;
38+
}
39+
40+
const cacheSettings = cliSetting['cache'];
41+
if (!isJsonObject(cacheSettings)) {
42+
return defaultSettings;
43+
}
44+
45+
const {
46+
path = defaultSettings.path,
47+
environment = defaultSettings.environment,
48+
enabled = defaultSettings.enabled,
49+
// eslint-disable-next-line @typescript-eslint/no-explicit-any
50+
} = cacheSettings as Record<string, any>;
51+
52+
return {
53+
path: resolve(workspace.basePath, path),
54+
environment,
55+
enabled,
56+
};
57+
}
Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
import { createDir, expectFileNotToExist, expectFileToExist } from '../../../utils/fs';
2+
import { ng } from '../../../utils/process';
3+
4+
export default async function () {
5+
const cachePath = '.angular/cache';
6+
await createDir(cachePath);
7+
await expectFileToExist(cachePath);
8+
9+
await ng('cache', 'clean');
10+
await expectFileNotToExist(cachePath);
11+
}
Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
import { readFile } from '../../../utils/fs';
2+
import { ng } from '../../../utils/process';
3+
4+
export default async function () {
5+
await ng('cache', 'enable');
6+
if (JSON.parse(await readFile('angular.json')).cli.cache.enabled !== true) {
7+
throw new Error(`Expected 'cli.cache.enable' to be true.`);
8+
}
9+
10+
await ng('cache', 'disable');
11+
if (JSON.parse(await readFile('angular.json')).cli.cache.enabled !== false) {
12+
throw new Error(`Expected 'cli.cache.enable' to be false.`);
13+
}
14+
}

0 commit comments

Comments
 (0)