UNPKG

16.8 kBJavaScriptView Raw
1"use strict";
2/**
3 * @license
4 * Copyright Google LLC All Rights Reserved.
5 *
6 * Use of this source code is governed by an MIT-style license that can be
7 * found in the LICENSE file at https://angular.io/license
8 */
9var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
10 if (k2 === undefined) k2 = k;
11 Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
12}) : (function(o, m, k, k2) {
13 if (k2 === undefined) k2 = k;
14 o[k2] = m[k];
15}));
16var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
17 Object.defineProperty(o, "default", { enumerable: true, value: v });
18}) : function(o, v) {
19 o["default"] = v;
20});
21var __importStar = (this && this.__importStar) || function (mod) {
22 if (mod && mod.__esModule) return mod;
23 var result = {};
24 if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
25 __setModuleDefault(result, mod);
26 return result;
27};
28Object.defineProperty(exports, "__esModule", { value: true });
29exports.isWarningEnabled = exports.getSchematicDefaults = exports.migrateLegacyGlobalConfig = exports.getConfiguredPackageManager = exports.getProjectByCwd = exports.validateWorkspace = exports.getWorkspaceRaw = exports.createGlobalSettings = exports.getWorkspace = exports.AngularWorkspace = exports.workspaceSchemaPath = void 0;
30const core_1 = require("@angular-devkit/core");
31const fs_1 = require("fs");
32const os = __importStar(require("os"));
33const path = __importStar(require("path"));
34const find_up_1 = require("./find-up");
35const json_file_1 = require("./json-file");
36function isJsonObject(value) {
37 return value !== undefined && core_1.json.isJsonObject(value);
38}
39function createWorkspaceHost() {
40 return {
41 async readFile(path) {
42 return fs_1.readFileSync(path, 'utf-8');
43 },
44 async writeFile(path, data) {
45 fs_1.writeFileSync(path, data);
46 },
47 async isDirectory(path) {
48 try {
49 return fs_1.statSync(path).isDirectory();
50 }
51 catch {
52 return false;
53 }
54 },
55 async isFile(path) {
56 try {
57 return fs_1.statSync(path).isFile();
58 }
59 catch {
60 return false;
61 }
62 },
63 };
64}
65function getSchemaLocation() {
66 return path.join(__dirname, '../lib/config/schema.json');
67}
68exports.workspaceSchemaPath = getSchemaLocation();
69const configNames = ['angular.json', '.angular.json'];
70const globalFileName = '.angular-config.json';
71function xdgConfigHome(home, configFile) {
72 // https://specifications.freedesktop.org/basedir-spec/basedir-spec-latest.html
73 const xdgConfigHome = process.env['XDG_CONFIG_HOME'] || path.join(home, '.config');
74 const xdgAngularHome = path.join(xdgConfigHome, 'angular');
75 return configFile ? path.join(xdgAngularHome, configFile) : xdgAngularHome;
76}
77function xdgConfigHomeOld(home) {
78 // Check the configuration files in the old location that should be:
79 // - $XDG_CONFIG_HOME/.angular-config.json (if XDG_CONFIG_HOME is set)
80 // - $HOME/.config/angular/.angular-config.json (otherwise)
81 const p = process.env['XDG_CONFIG_HOME'] || path.join(home, '.config', 'angular');
82 return path.join(p, '.angular-config.json');
83}
84function projectFilePath(projectPath) {
85 // Find the configuration, either where specified, in the Angular CLI project
86 // (if it's in node_modules) or from the current process.
87 return ((projectPath && find_up_1.findUp(configNames, projectPath)) ||
88 find_up_1.findUp(configNames, process.cwd()) ||
89 find_up_1.findUp(configNames, __dirname));
90}
91function globalFilePath() {
92 const home = os.homedir();
93 if (!home) {
94 return null;
95 }
96 // follow XDG Base Directory spec
97 // note that createGlobalSettings() will continue creating
98 // global file in home directory, with this user will have
99 // choice to move change its location to meet XDG convention
100 const xdgConfig = xdgConfigHome(home, 'config.json');
101 if (fs_1.existsSync(xdgConfig)) {
102 return xdgConfig;
103 }
104 // NOTE: This check is for the old configuration location, for more
105 // information see https://github.com/angular/angular-cli/pull/20556
106 const xdgConfigOld = xdgConfigHomeOld(home);
107 if (fs_1.existsSync(xdgConfigOld)) {
108 /* eslint-disable no-console */
109 console.warn(`Old configuration location detected: ${xdgConfigOld}\n` +
110 `Please move the file to the new location ~/.config/angular/config.json`);
111 return xdgConfigOld;
112 }
113 const p = path.join(home, globalFileName);
114 if (fs_1.existsSync(p)) {
115 return p;
116 }
117 return null;
118}
119class AngularWorkspace {
120 constructor(workspace, filePath) {
121 this.workspace = workspace;
122 this.filePath = filePath;
123 this.basePath = path.dirname(filePath);
124 }
125 get extensions() {
126 return this.workspace.extensions;
127 }
128 get projects() {
129 return this.workspace.projects;
130 }
131 // Temporary helper functions to support refactoring
132 // eslint-disable-next-line @typescript-eslint/no-explicit-any
133 getCli() {
134 return this.workspace.extensions['cli'] || {};
135 }
136 // eslint-disable-next-line @typescript-eslint/no-explicit-any
137 getProjectCli(projectName) {
138 const project = this.workspace.projects.get(projectName);
139 return (project === null || project === void 0 ? void 0 : project.extensions['cli']) || {};
140 }
141 static async load(workspaceFilePath) {
142 const oldConfigFileNames = ['.angular-cli.json', 'angular-cli.json'];
143 if (oldConfigFileNames.includes(path.basename(workspaceFilePath))) {
144 // 1.x file format
145 // Create an empty workspace to allow update to be used
146 return new AngularWorkspace({ extensions: {}, projects: new core_1.workspaces.ProjectDefinitionCollection() }, workspaceFilePath);
147 }
148 const result = await core_1.workspaces.readWorkspace(workspaceFilePath, createWorkspaceHost(), core_1.workspaces.WorkspaceFormat.JSON);
149 return new AngularWorkspace(result.workspace, workspaceFilePath);
150 }
151}
152exports.AngularWorkspace = AngularWorkspace;
153const cachedWorkspaces = new Map();
154async function getWorkspace(level = 'local') {
155 const cached = cachedWorkspaces.get(level);
156 if (cached !== undefined) {
157 return cached;
158 }
159 const configPath = level === 'local' ? projectFilePath() : globalFilePath();
160 if (!configPath) {
161 cachedWorkspaces.set(level, null);
162 return null;
163 }
164 try {
165 const workspace = await AngularWorkspace.load(configPath);
166 cachedWorkspaces.set(level, workspace);
167 return workspace;
168 }
169 catch (error) {
170 throw new Error(`Workspace config file cannot be loaded: ${configPath}` +
171 `\n${error instanceof Error ? error.message : error}`);
172 }
173}
174exports.getWorkspace = getWorkspace;
175function createGlobalSettings() {
176 const home = os.homedir();
177 if (!home) {
178 throw new Error('No home directory found.');
179 }
180 const globalPath = path.join(home, globalFileName);
181 fs_1.writeFileSync(globalPath, JSON.stringify({ version: 1 }));
182 return globalPath;
183}
184exports.createGlobalSettings = createGlobalSettings;
185function getWorkspaceRaw(level = 'local') {
186 let configPath = level === 'local' ? projectFilePath() : globalFilePath();
187 if (!configPath) {
188 if (level === 'global') {
189 configPath = createGlobalSettings();
190 }
191 else {
192 return [null, null];
193 }
194 }
195 return [new json_file_1.JSONFile(configPath), configPath];
196}
197exports.getWorkspaceRaw = getWorkspaceRaw;
198async function validateWorkspace(data) {
199 const schema = json_file_1.readAndParseJson(path.join(__dirname, '../lib/config/schema.json'));
200 const { formats } = await Promise.resolve().then(() => __importStar(require('@angular-devkit/schematics')));
201 const registry = new core_1.json.schema.CoreSchemaRegistry(formats.standardFormats);
202 const validator = await registry.compile(schema).toPromise();
203 const { success, errors } = await validator(data).toPromise();
204 if (!success) {
205 throw new core_1.json.schema.SchemaValidationException(errors);
206 }
207}
208exports.validateWorkspace = validateWorkspace;
209function findProjectByPath(workspace, location) {
210 const isInside = (base, potential) => {
211 const absoluteBase = path.resolve(workspace.basePath, base);
212 const absolutePotential = path.resolve(workspace.basePath, potential);
213 const relativePotential = path.relative(absoluteBase, absolutePotential);
214 if (!relativePotential.startsWith('..') && !path.isAbsolute(relativePotential)) {
215 return true;
216 }
217 return false;
218 };
219 const projects = Array.from(workspace.projects)
220 .map(([name, project]) => [project.root, name])
221 .filter((tuple) => isInside(tuple[0], location))
222 // Sort tuples by depth, with the deeper ones first. Since the first member is a path and
223 // we filtered all invalid paths, the longest will be the deepest (and in case of equality
224 // the sort is stable and the first declared project will win).
225 .sort((a, b) => b[0].length - a[0].length);
226 if (projects.length === 0) {
227 return null;
228 }
229 else if (projects.length > 1) {
230 const found = new Set();
231 const sameRoots = projects.filter((v) => {
232 if (!found.has(v[0])) {
233 found.add(v[0]);
234 return false;
235 }
236 return true;
237 });
238 if (sameRoots.length > 0) {
239 // Ambiguous location - cannot determine a project
240 return null;
241 }
242 }
243 return projects[0][1];
244}
245function getProjectByCwd(workspace) {
246 if (workspace.projects.size === 1) {
247 // If there is only one project, return that one.
248 return Array.from(workspace.projects.keys())[0];
249 }
250 const project = findProjectByPath(workspace, process.cwd());
251 if (project) {
252 return project;
253 }
254 const defaultProject = workspace.extensions['defaultProject'];
255 if (defaultProject && typeof defaultProject === 'string') {
256 // If there is a default project name, return it.
257 return defaultProject;
258 }
259 return null;
260}
261exports.getProjectByCwd = getProjectByCwd;
262async function getConfiguredPackageManager() {
263 var _a;
264 const getPackageManager = (source) => {
265 if (isJsonObject(source)) {
266 const value = source['packageManager'];
267 if (value && typeof value === 'string') {
268 return value;
269 }
270 }
271 };
272 let result;
273 const workspace = await getWorkspace('local');
274 if (workspace) {
275 const project = getProjectByCwd(workspace);
276 if (project) {
277 result = getPackageManager((_a = workspace.projects.get(project)) === null || _a === void 0 ? void 0 : _a.extensions['cli']);
278 }
279 result = result !== null && result !== void 0 ? result : getPackageManager(workspace.extensions['cli']);
280 }
281 if (result === undefined) {
282 const globalOptions = await getWorkspace('global');
283 result = getPackageManager(globalOptions === null || globalOptions === void 0 ? void 0 : globalOptions.extensions['cli']);
284 if (!workspace && !globalOptions) {
285 // Only check legacy if updated workspace is not found
286 result = getLegacyPackageManager();
287 }
288 }
289 // Default to null
290 return result !== null && result !== void 0 ? result : null;
291}
292exports.getConfiguredPackageManager = getConfiguredPackageManager;
293function migrateLegacyGlobalConfig() {
294 const homeDir = os.homedir();
295 if (homeDir) {
296 const legacyGlobalConfigPath = path.join(homeDir, '.angular-cli.json');
297 if (fs_1.existsSync(legacyGlobalConfigPath)) {
298 const legacy = json_file_1.readAndParseJson(legacyGlobalConfigPath);
299 if (!isJsonObject(legacy)) {
300 return false;
301 }
302 const cli = {};
303 if (legacy.packageManager &&
304 typeof legacy.packageManager == 'string' &&
305 legacy.packageManager !== 'default') {
306 cli['packageManager'] = legacy.packageManager;
307 }
308 if (isJsonObject(legacy.defaults) &&
309 isJsonObject(legacy.defaults.schematics) &&
310 typeof legacy.defaults.schematics.collection == 'string') {
311 cli['defaultCollection'] = legacy.defaults.schematics.collection;
312 }
313 if (isJsonObject(legacy.warnings)) {
314 const warnings = {};
315 if (typeof legacy.warnings.versionMismatch == 'boolean') {
316 warnings['versionMismatch'] = legacy.warnings.versionMismatch;
317 }
318 if (Object.getOwnPropertyNames(warnings).length > 0) {
319 cli['warnings'] = warnings;
320 }
321 }
322 if (Object.getOwnPropertyNames(cli).length > 0) {
323 const globalPath = path.join(homeDir, globalFileName);
324 fs_1.writeFileSync(globalPath, JSON.stringify({ version: 1, cli }, null, 2));
325 return true;
326 }
327 }
328 }
329 return false;
330}
331exports.migrateLegacyGlobalConfig = migrateLegacyGlobalConfig;
332// Fallback, check for packageManager in config file in v1.* global config.
333function getLegacyPackageManager() {
334 const homeDir = os.homedir();
335 if (homeDir) {
336 const legacyGlobalConfigPath = path.join(homeDir, '.angular-cli.json');
337 if (fs_1.existsSync(legacyGlobalConfigPath)) {
338 const legacy = json_file_1.readAndParseJson(legacyGlobalConfigPath);
339 if (!isJsonObject(legacy)) {
340 return null;
341 }
342 if (legacy.packageManager &&
343 typeof legacy.packageManager === 'string' &&
344 legacy.packageManager !== 'default') {
345 return legacy.packageManager;
346 }
347 }
348 }
349 return null;
350}
351async function getSchematicDefaults(collection, schematic, project) {
352 var _a;
353 const result = {};
354 const mergeOptions = (source) => {
355 if (isJsonObject(source)) {
356 // Merge options from the qualified name
357 Object.assign(result, source[`${collection}:${schematic}`]);
358 // Merge options from nested collection schematics
359 const collectionOptions = source[collection];
360 if (isJsonObject(collectionOptions)) {
361 Object.assign(result, collectionOptions[schematic]);
362 }
363 }
364 };
365 // Global level schematic options
366 const globalOptions = await getWorkspace('global');
367 mergeOptions(globalOptions === null || globalOptions === void 0 ? void 0 : globalOptions.extensions['schematics']);
368 const workspace = await getWorkspace('local');
369 if (workspace) {
370 // Workspace level schematic options
371 mergeOptions(workspace.extensions['schematics']);
372 project = project || getProjectByCwd(workspace);
373 if (project) {
374 // Project level schematic options
375 mergeOptions((_a = workspace.projects.get(project)) === null || _a === void 0 ? void 0 : _a.extensions['schematics']);
376 }
377 }
378 return result;
379}
380exports.getSchematicDefaults = getSchematicDefaults;
381async function isWarningEnabled(warning) {
382 var _a;
383 const getWarning = (source) => {
384 if (isJsonObject(source)) {
385 const warnings = source['warnings'];
386 if (isJsonObject(warnings)) {
387 const value = warnings[warning];
388 if (typeof value == 'boolean') {
389 return value;
390 }
391 }
392 }
393 };
394 let result;
395 const workspace = await getWorkspace('local');
396 if (workspace) {
397 const project = getProjectByCwd(workspace);
398 if (project) {
399 result = getWarning((_a = workspace.projects.get(project)) === null || _a === void 0 ? void 0 : _a.extensions['cli']);
400 }
401 result = result !== null && result !== void 0 ? result : getWarning(workspace.extensions['cli']);
402 }
403 if (result === undefined) {
404 const globalOptions = await getWorkspace('global');
405 result = getWarning(globalOptions === null || globalOptions === void 0 ? void 0 : globalOptions.extensions['cli']);
406 }
407 // All warnings are enabled by default
408 return result !== null && result !== void 0 ? result : true;
409}
410exports.isWarningEnabled = isWarningEnabled;