forked from angular/angular-cli
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhost.ts
More file actions
167 lines (149 loc) · 5.35 KB
/
host.ts
File metadata and controls
167 lines (149 loc) · 5.35 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
/**
* @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 defines an abstraction layer for side-effectful operations, such as
* file system access and command execution. This allows for easier testing by
* enabling the injection of mock or test-specific implementations.
*/
import { type SpawnOptions, spawn } from 'node:child_process';
import { Stats } from 'node:fs';
import { copyFile, mkdir, mkdtemp, readFile, readdir, rm, stat, writeFile } from 'node:fs/promises';
import { platform } from 'node:os';
import { join } from 'node:path';
import { PackageManagerError } from './error';
/**
* An abstraction layer for side-effectful operations.
*/
export interface Host {
/**
* Gets the stats of a file or directory.
* @param path The path to the file or directory.
* @returns A promise that resolves to the stats.
*/
stat(path: string): Promise<Stats>;
/**
* Reads the contents of a directory.
* @param path The path to the directory.
* @returns A promise that resolves to an array of file and directory names.
*/
readdir(path: string): Promise<string[]>;
/**
* Reads the content of a file.
* @param path The path to the file.
* @returns A promise that resolves to the file content as a string.
*/
readFile(path: string): Promise<string>;
/**
* Creates a new, unique temporary directory.
* @returns A promise that resolves to the absolute path of the created directory.
*/
createTempDirectory(): Promise<string>;
/**
* Deletes a directory recursively.
* @param path The path to the directory to delete.
* @returns A promise that resolves when the deletion is complete.
*/
deleteDirectory(path: string): Promise<void>;
/**
* Writes content to a file.
* @param path The path to the file.
* @param content The content to write.
* @returns A promise that resolves when the write is complete.
*/
writeFile(path: string, content: string): Promise<void>;
/**
* Spawns a child process and returns a promise that resolves with the process's
* output or rejects with a structured error.
* @param command The command to run.
* @param args The arguments to pass to the command.
* @param options Options for the child process.
* @returns A promise that resolves with the standard output and standard error of the command.
*/
runCommand(
command: string,
args: readonly string[],
options?: {
timeout?: number;
stdio?: 'pipe' | 'ignore';
cwd?: string;
env?: Record<string, string>;
},
): Promise<{ stdout: string; stderr: string }>;
}
/**
* A concrete implementation of the `Host` interface that uses the Node.js APIs.
* @param root The root directory of the project.
* @param cacheDirectory The directory to use for caching.
* @returns A host that uses the Node.js APIs.
*/
export function createNodeJsHost(root: string, cacheDirectory: string): Host {
return {
stat,
readdir,
readFile: (path: string) => readFile(path, { encoding: 'utf8' }),
writeFile,
createTempDirectory: async () => {
await mkdir(cacheDirectory, { recursive: true });
const tmpDir = await mkdtemp(join(cacheDirectory, 'package-manager-temp-'));
// Copy the .npmrc file to the temp directory if it exists.
await copyFile(`${root}/.npmrc`, `${tmpDir}/.npmrc`).catch(() => {});
return tmpDir;
},
deleteDirectory: (path: string) => rm(path, { recursive: true, force: true }),
runCommand: async (
command: string,
args: readonly string[],
options: {
timeout?: number;
stdio?: 'pipe' | 'ignore';
cwd?: string;
env?: Record<string, string>;
} = {},
): Promise<{ stdout: string; stderr: string }> => {
const signal = options.timeout ? AbortSignal.timeout(options.timeout) : undefined;
const isWin32 = platform() === 'win32';
return new Promise((resolve, reject) => {
const spawnOptions = {
shell: isWin32,
stdio: options.stdio ?? 'pipe',
signal,
cwd: options.cwd,
env: {
...process.env,
...options.env,
},
} satisfies SpawnOptions;
const childProcess = isWin32
? spawn(`${command} ${args.join(' ')}`, spawnOptions)
: spawn(command, args, spawnOptions);
let stdout = '';
childProcess.stdout?.on('data', (data) => (stdout += data.toString()));
let stderr = '';
childProcess.stderr?.on('data', (data) => (stderr += data.toString()));
childProcess.on('close', (code) => {
if (code === 0) {
resolve({ stdout, stderr });
} else {
const message = `Process exited with code ${code}.`;
reject(new PackageManagerError(message, stdout, stderr, code));
}
});
childProcess.on('error', (err) => {
if (err.name === 'AbortError') {
const message = `Process timed out.`;
reject(new PackageManagerError(message, stdout, stderr, null));
return;
}
const message = `Process failed with error: ${err.message}`;
reject(new PackageManagerError(message, stdout, stderr, null));
});
});
},
};
}