_id
stringlengths
21
254
text
stringlengths
1
93.7k
metadata
dict
angular-cli/scripts/templates/contributing.ejs_0_4255
# Contributing to Angular DevKit We would love for you to contribute to DevKit and help make it even better than it is today! As a contributor, here are the guidelines we would like you to follow: - [Code of Conduct](#coc) - [Question or Problem?](#question) - [Issues and Bugs](#issue) - [Feature Requests](#feature) - [Submission Guidelines](#submit) - [Coding Rules](#rules) - [Commit Message Guidelines](#commit) - [Signing the CLA](#cla) - [Updating the Public API](#public-api) ## <a name="coc"></a> Code of Conduct Help us keep Angular open and inclusive. Please read and follow our [Code of Conduct][coc]. ## <a name="question"></a> Got a Question or Problem? Please, do not open issues for the general support questions as we want to keep GitHub issues for bug reports and feature requests. You've got much better chances of getting your question answered on [StackOverflow](https://stackoverflow.com/questions/tagged/angular-devkit) where the questions should be tagged with tag `angular-cli` or `angular-devkit`. StackOverflow is a much better place to ask questions since: - There are thousands of people willing to help on StackOverflow. - Questions and answers stay available for public viewing so your question / answer might help someone else. - StackOverflow's voting system assures that the best answers are prominently visible. To save your and our time we will be systematically closing all the issues that are requests for general support and redirecting people to StackOverflow. If you would like to chat about the question in real-time, you can reach out via [our gitter channel][gitter]. ## <a name="issue"></a> Found an Issue? If you find a bug in the source code or a mistake in the documentation, you can help us by [submitting an issue](#submit-issue) to our [GitHub Repository][github]. Even better, you can [submit a Pull Request](#submit-pr) with a fix. ## <a name="feature"></a> Want a Feature? You can *request* a new feature by [submitting an issue](#submit-issue) to our [GitHub Repository][github]. If you would like to *implement* a new feature, please submit an issue with a proposal for your work first, to be sure that we can use it. Please consider what kind of change it is: * For a **Major Feature**, first open an issue and outline your proposal so that it can be discussed. This will also allow us to better coordinate our efforts, prevent duplication of work, and help you to craft the change so that it is successfully accepted into the project. * **Small Features** can be crafted and directly [submitted as a Pull Request](#submit-pr). ## <a name="submit"></a> Submission Guidelines ### <a name="submit-issue"></a> Submitting an Issue Before you submit an issue, please search the issue tracker, maybe an issue for your problem already exists and the discussion might inform you of workarounds readily available. We want to fix all the issues as soon as possible, but before fixing a bug we need to reproduce and confirm it. Having a reproducible scenario gives us wealth of important information without going back & forth to you with additional questions like: - version of Angular CLI used - `angular.json` configuration - version of Angular DevKit used - 3rd-party libraries and their versions - and most importantly - a use-case that fails A minimal reproduce scenario using allows us to quickly confirm a bug (or point out coding problem) as well as confirm that we are fixing the right problem. We will be insisting on a minimal reproduce scenario in order to save maintainers time and ultimately be able to fix more bugs. Interestingly, from our experience users often find coding problems themselves while preparing a minimal repository. We understand that sometimes it might be hard to extract essentials bits of code from a larger code-base but we really need to isolate the problem before we can fix it. Unfortunately we are not able to investigate / fix bugs without a minimal reproduction, so if we don't hear back from you we are going to close an issue that don't have enough info to be reproduced. You can file new issues by selecting from our [new issue templates](https://github.com/angular/angular-cli/issues/new/choose) and filling out the issue template.
{ "end_byte": 4255, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/scripts/templates/contributing.ejs" }
angular-cli/scripts/templates/contributing.ejs_4258_12446
### <a name="submit-pr"></a> Submitting a Pull Request (PR) Before you submit your Pull Request (PR) consider the following guidelines: * Search [GitHub](https://github.com/angular/angular-cli/pulls) for an open or closed PR that relates to your submission. You don't want to duplicate effort. * Please sign our [Contributor License Agreement (CLA)](#cla) before sending PRs. We cannot accept code without this. * Make your changes in a new git branch: ```shell git checkout -b my-fix-branch main ``` * Create your patch, **including appropriate test cases**. * Follow our [Coding Rules](#rules). * Run the full Angular CLI and DevKit test suite, as described in the [developer documentation][dev-doc], and ensure that all tests pass (coming soon). * Commit your changes using a descriptive commit message that follows our [commit message conventions](#commit). Adherence to these conventions is necessary because release notes are automatically generated from these messages. ```shell git commit -a ``` Note: the optional commit `-a` command line option will automatically "add" and "rm" edited files. * Push your branch to GitHub: ```shell git push origin my-fix-branch ``` * In GitHub, send a pull request to `angular/angular-cli:main`. * If we suggest changes then: * Make the required updates. * Re-run the Angular DevKit test suites to ensure tests are still passing. * Once your PR is approved and you are done with any follow up changes: * Rebase to the current main to pre-emptively address any merge conflicts. ```shell git rebase upstream/main -i git push -f ``` * Add the `action: merge` label and the correct [target label](https://github.com/angular/angular/blob/main/docs/TRIAGE_AND_LABELS.md#pr-target) (if PR author has the project collaborator status, or else the last reviewer should do this). * The current caretaker will merge the PR to the target branch(es) within 1-2 business days. That's it! 🎉 Thank you for your contribution! #### After your pull request is merged After your pull request is merged, you can safely delete your branch and pull the changes from the main (upstream) repository: * Delete the remote branch on GitHub either through the GitHub web UI or your local shell as follows: ```shell git push origin --delete my-fix-branch ``` * Check out the main branch: ```shell git checkout main -f ``` * Delete the local branch: ```shell git branch -D my-fix-branch ``` * Update your local `main` with the latest upstream version: ```shell git pull --ff upstream main ``` ## <a name="rules"></a> Coding Rules To ensure consistency throughout the source code, keep these rules in mind as you are working: * All features or bug fixes **must be tested** by one or more specs (unit-tests or e2e-tests). * All public API methods **must be documented**. (Details TBC). * We follow [Google's JavaScript Style Guide][js-style-guide], but wrap all code at **100 characters**. ## <a name="commit"></a> Commit Message Guidelines We have very precise rules over how our git commit messages can be formatted. This leads to **more readable messages** that are easy to follow when looking through the **project history**. But also, we use the git commit messages to **generate the Angular DevKit change log**. ### Commit Message Format Each commit message consists of a **header**, a **body** and a **footer**. The header has a special format that includes a **type**, a **scope** and a **subject**: ``` <type>(<scope>): <subject> <BLANK LINE> <body> <BLANK LINE> <footer> ``` The **header** is mandatory and the **scope** of the header is optional. Any line of the commit message cannot be longer 100 characters! This allows the message to be easier to read on GitHub as well as in various git tools. ### Revert If the commit reverts a previous commit, it should begin with `revert: `, followed by the header of the reverted commit. In the body it should say: `This reverts commit <hash>.`, where the hash is the SHA of the commit being reverted. ### Type Must be one of the following: <% for (const typeName of Object.keys(COMMIT_TYPES).sort()) { const type = COMMIT_TYPES[typeName]; %>* **<%= typeName %>**: <%= type.description %><% if (type.scope == ScopeRequirement.Required) { %> [1]<% } else if (type.scope == ScopeRequirement.Forbidden) { %> [2]<% } %> <% } %> <sup>[1] This type MUST have a scope. See the next section for more information.</sup><br/> <sup>[2] This type MUST NOT have a scope. It only applies to general scripts and tooling.</sup> ### Scope The scope should be the name of the npm package affected as perceived by the person reading changelog generated from the commit messages. The following is the list of supported scopes: <% for (const scope of packages) { %>* **<%= scope %>** <% } %> ### Subject The subject contains succinct description of the change: * use the imperative, present tense: "change" not "changed" nor "changes" * don't capitalize first letter * be concise and direct * no dot (.) at the end ### Examples Examples of valid commit messages: * `fix(@angular/cli): prevent the flubber from grassing` * `refactor(@schematics/angular): move all JSON classes together` Examples of invalid commit messages: * `fix(@angular/cli): add a new XYZ command` This is a feature, not a fix. * `ci(@angular/cli): fix publishing workflow` The `ci` type cannot have a scope. ### Body Just as in the **subject**, use the imperative, present tense: "change" not "changed" nor "changes". The body should include the motivation for the change and contrast this with previous behavior. ### Footer The footer can contain information about breaking changes and deprecations. It is also the place to reference GitHub issues, Jira tickets, and other PRs that are related to this commit or that this commit will close. For example: ``` BREAKING CHANGE: <breaking change summary> <BLANK LINE> <breaking change description + migration instructions> <BLANK LINE> <BLANK LINE> Fixes #<issue number> ``` or ``` DEPRECATED: <what is deprecated> <BLANK LINE> <deprecation description + recommended update path> <BLANK LINE> <BLANK LINE> Closes #<pr number> ``` Breaking Change section should start with the phrase "BREAKING CHANGE: " followed by a summary of the breaking change, a blank line, and a detailed description of the breaking change that also includes migration instructions. Similarly, a Deprecation section should start with "DEPRECATED: " followed by a short description of what is deprecated, a blank line, and a detailed description of the deprecation that also mentions the recommended update path. ## <a name="cla"></a> Signing the CLA Please sign our Contributor License Agreement (CLA) before sending pull requests. For any code changes to be accepted, the CLA must be signed. It's a quick process, we promise! * For individuals we have a [simple click-through form][individual-cla]. * For corporations we'll need you to [print, sign and one of scan+email, fax or mail the form][corporate-cla]. [coc]: https://github.com/angular/code-of-conduct/blob/main/CODE_OF_CONDUCT.md [commit-message-format]: https://docs.google.com/document/d/1QrDFcIiPjSLDn3EL15IJygNPiHORgU1_OOAqWjiDU5Y/edit# [corporate-cla]: https://code.google.com/legal/corporate-cla-v1.0.html [dev-doc]: https://github.com/angular/angular-cli/blob/main/packages/angular/cli/README.md#development-hints-for-working-on-angular-cli [GitHub]: https://github.com/angular/angular-cli [gitter]: https://gitter.im/angular/angular-cli [individual-cla]: https://code.google.com/legal/individual-cla-v1.0.html [js-style-guide]: https://google.github.io/styleguide/jsguide.html [stackoverflow]: https://stackoverflow.com/questions/tagged/angular-devkit ## <a name="public-api"></a> Updating the Public API Our Public API surface is tracked using golden files. You check all golden files by running: ```bash yarn public-api:check ``` If you modified the public API, the test will fail. To update the golden files you need to run: ```bash yarn public-api:update ```
{ "end_byte": 12446, "start_byte": 4258, "url": "https://github.com/angular/angular-cli/blob/main/scripts/templates/contributing.ejs" }
angular-cli/scripts/templates/user-analytics-table.ejs_0_162
<% %>| Name | Parameter | Type | |:---:|:---|:---| <% for (const { parameter, name, type } of data) {%>| <%= name %> | `<%= parameter %>` | `<%= type %>` | <%}%>
{ "end_byte": 162, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/scripts/templates/user-analytics-table.ejs" }
angular-cli/scripts/templates/readme.ejs_0_6744
<!-- BEFORE UPDATING THIS FILE, READ THIS. This file is automatically generated during release. It is important for you to not update README directly. - If you need to change the content, update `scripts/templates/readme.ejs` - If you need to add/remove a package or a link, update the .monorepo.json file instead. Any changes to README.md directly will result in a failure on CI. --> <h1 style="text-align: center">Angular CLI - The CLI tool for Angular.</h1> <p style="text-align: center"> <br> <img src="/docs/images/angular-cli-logo.png" alt="Angular CLI logo" width="100px" height="108px"/> <br><br> <em>The Angular CLI is a command-line interface tool that you use to initialize, develop, scaffold, <br>and maintain Angular applications directly from a command shell.</em> <br> </p> <p style="text-align: center"> <a href="https://angular.dev/tools/cli"><strong>angular.dev/tools/cli</strong></a> <br> </p> <p style="text-align: center"> <a href="CONTRIBUTING.md">Contributing Guidelines</a> · <a href="https://github.com/angular/angular-cli/issues">Submit an Issue</a> · <a href="https://blog.angular.dev">Blog</a> <br> <br> </p> <p style="text-align: center"> <a href="https://circleci.com/gh/angular/workflows/angular-cli/tree/main"> <img src="https://img.shields.io/circleci/build/github/angular/angular-cli/main.svg?logo=circleci&logoColor=fff&label=CircleCI" alt="CI status" /> </a>&nbsp; <a href="https://discord.gg/angular"> <img src="https://img.shields.io/discord/463752820026376202.svg?logo=discord&logoColor=fff&label=Discord&color=7389d8" alt="Discord conversation" /> </a> </p> <hr> ## Documentation Get started with Angular CLI, learn the fundamentals and explore advanced topics on our documentation website. - [Getting started][quickstart] - [CLI][cli] - [Workspace and project file structure][filestructure] - [Workspace configuration][workspaceconfig] - [Schematics][schematics] ## Development Setup ### Prerequisites - Install [Node.js] which includes [Node Package Manager][npm] ### Setting Up a Project Install the Angular CLI globally: ``` npm install -g @angular/cli ``` Create workspace: ``` ng new [PROJECT NAME] ``` Run the application: ``` cd [PROJECT NAME] ng serve ``` Angular is cross-platform, fast, scalable, has incredible tooling, and is loved by millions. ## Quickstart [Get started in 5 minutes][quickstart]. ## Ecosystem <p> <img src="/docs/images/angular-ecosystem-logos.png" alt="angular ecosystem logos" width="500px" height="auto"> </p> - [Angular Framework][adev] - [Angular Material][angularmaterial] ## Changelog [Learn about the latest improvements][changelog]. ## Upgrading Check out our [upgrade guide](https://update.angular.dev/) to find out the best way to upgrade your project. ## Contributing ### Contributing Guidelines Read through our [contributing guidelines][contributing] to learn about our submission process, coding rules and more. ### Want to Help? Want to report a bug, contribute some code, or improve documentation? Excellent! Read up on our guidelines for [contributing][contributing] and then check out one of our issues labeled as <kbd>[help wanted](https://github.com/angular/angular-cli/labels/help%20wanted)</kbd> or <kbd>[good first issue](https://github.com/angular/angular-cli/labels/good%20first%20issue)</kbd>. ### Code of Conduct Help us keep Angular open and inclusive. Please read and follow our [Code of Conduct][codeofconduct]. ### Developer Guide Read through our [developer guide][developer] to learn about how to build and test the Angular CLI locally. ## Community Join the conversation and help the community. - [Twitter][twitter] - [Discord][discord] - [Gitter][gitter] - [YouTube][youtube] - [StackOverflow][stackoverflow] - Find a Local [Meetup][meetup] ## Packages This is a monorepo which contains many tools and packages: <% const sections = [ ...new Set(packages.map(pkgName => monorepo.packages[pkgName].section )) ].filter(x => x && x != 'Tooling'); sections.unshift(undefined); %> ### Tools | Project | Package | Version | Links | |---|---|---|---| <% for (const pkgName of packages) { const mrPkg = monorepo.packages[pkgName]; if (mrPkg.section != 'Tooling') { continue; } %>**<%= mrPkg.name%>**<% %> | [`<%= pkgName %>`](https://npmjs.com/package/<%= pkgName %>)<% %> | [![latest](https://img.shields.io/npm/v/<%= encode(pkgName) %>/latest.svg)](https://npmjs.com/package/<%= pkgName %>)<% %> | <% for (const link of mrPkg.links || []) { %>[![<%= link.label %>](https://img.shields.io/badge/<%= link.label %>--<%= link.color || 'green' %>.svg)](<%= link.url %>)<% } if (mrPkg.snapshotRepo) { %> [![snapshot](https://img.shields.io/badge/snapshot--blue.svg)](https://github.com/<%= mrPkg.snapshotRepo %>)<% } %> <% } %> ### Packages <% for (const section of sections) { %><%= section ? '#### ' + section : '' %> | Project | Package | Version | Links | |---|---|---|---| <% for (const pkgName of packages) { const mrPkg = monorepo.packages[pkgName]; if (mrPkg.section != section) { continue; } %>**<%= mrPkg.name%>**<% %> | [`<%= pkgName %>`](https://npmjs.com/package/<%= pkgName %>)<% %> | [![latest](https://img.shields.io/npm/v/<%= encode(pkgName) %>/latest.svg)](https://npmjs.com/package/<%= pkgName %>)<% %> | <% for (const link of mrPkg.links || []) { %>[![<%= link.label %>](https://img.shields.io/badge/<%= link.label %>--<%= link.color || 'green' %>.svg)](<%= link.url %>)<% } if (mrPkg.snapshotRepo) { %> [![snapshot](https://img.shields.io/badge/snapshot--blue.svg)](https://github.com/<%= mrPkg.snapshotRepo %>)<% } %> <% } %> <% } %> **Love Angular CLI? Give our repo a star :star: :arrow_up:.** [contributing]: CONTRIBUTING.md [developer]: docs/DEVELOPER.md [quickstart]: https://angular.dev/tutorials/learn-angular [changelog]: CHANGELOG.md [documentation]: https://angular.dev/overview [angularmaterial]: https://material.angular.io/ [cli]: https://angular.dev/tools/cli [adev]: https://angular.dev/ [workspaceconfig]: https://angular.dev/reference/configs/workspace-config [schematics]: https://angular.dev/tools/cli/schematics [filestructure]: https://angular.dev/reference/configs/file-structure [node.js]: https://nodejs.org/ [npm]: https://www.npmjs.com/get-npm [codeofconduct]: https://github.com/angular/angular/blob/main/CODE_OF_CONDUCT.md [twitter]: https://www.twitter.com/angular [discord]: https://discord.gg/angular [gitter]: https://gitter.im/angular/angular-cli [stackoverflow]: https://stackoverflow.com/questions/tagged/angular-cli [youtube]: https://youtube.com/angular [meetup]: https://www.meetup.com/find/?keywords=angular
{ "end_byte": 6744, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/scripts/templates/readme.ejs" }
angular-cli/packages/README.md_0_309
# `/packages` Folder This folder is the root of all defined packages in this repository. Packages that are marked as `private: true` will not be published to NPM. This folder includes a directory for every scope in NPM, without the `@` sign. Then one folder per package, which contains the `package.json`.
{ "end_byte": 309, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/README.md" }
angular-cli/packages/angular/cli/README.md_0_314
# Angular CLI - The CLI tool for Angular. The sources for this package are in the [Angular CLI](https://github.com/angular/angular-cli) repository. Please file issues and pull requests against that repository. Usage information and reference details can be found in repository [README](../../../README.md) file.
{ "end_byte": 314, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular/cli/README.md" }
angular-cli/packages/angular/cli/BUILD.bazel_0_6468
# Copyright Google Inc. 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 load("@npm//@bazel/jasmine:index.bzl", "jasmine_node_test") load("//tools:defaults.bzl", "pkg_npm", "ts_library") load("//tools:ng_cli_schema_generator.bzl", "cli_json_schema") load("//tools:ts_json_schema.bzl", "ts_json_schema") licenses(["notice"]) package(default_visibility = ["//visibility:public"]) ts_library( name = "angular-cli", package_name = "@angular/cli", srcs = glob( include = [ "lib/**/*.ts", "src/**/*.ts", ], exclude = [ "**/*_spec.ts", ], ) + [ # @external_begin # These files are generated from the JSON schema "//packages/angular/cli:lib/config/workspace-schema.ts", "//packages/angular/cli:src/commands/update/schematic/schema.ts", # @external_end ], data = glob( include = [ "bin/**/*", "src/**/*.md", "src/**/*.json", ], exclude = [ "lib/config/workspace-schema.json", ], ) + [ # @external_begin "//packages/angular/cli:lib/config/schema.json", # @external_end ], module_name = "@angular/cli", deps = [ "//packages/angular_devkit/architect", "//packages/angular_devkit/architect/node", "//packages/angular_devkit/core", "//packages/angular_devkit/core/node", "//packages/angular_devkit/schematics", "//packages/angular_devkit/schematics/tasks", "//packages/angular_devkit/schematics/tools", "@npm//@angular/core", "@npm//@inquirer/prompts", "@npm//@listr2/prompt-adapter-inquirer", "@npm//@types/ini", "@npm//@types/node", "@npm//@types/npm-package-arg", "@npm//@types/pacote", "@npm//@types/resolve", "@npm//@types/semver", "@npm//@types/yargs", "@npm//@types/yarnpkg__lockfile", "@npm//@yarnpkg/lockfile", "@npm//ini", "@npm//jsonc-parser", "@npm//listr2", "@npm//npm-package-arg", "@npm//npm-pick-manifest", "@npm//pacote", "@npm//semver", "@npm//yargs", ], ) # @external_begin CLI_SCHEMA_DATA = [ "//packages/angular/build:src/builders/application/schema.json", "//packages/angular/build:src/builders/dev-server/schema.json", "//packages/angular/build:src/builders/extract-i18n/schema.json", "//packages/angular_devkit/build_angular:src/builders/app-shell/schema.json", "//packages/angular_devkit/build_angular:src/builders/browser/schema.json", "//packages/angular_devkit/build_angular:src/builders/browser-esbuild/schema.json", "//packages/angular_devkit/build_angular:src/builders/dev-server/schema.json", "//packages/angular_devkit/build_angular:src/builders/extract-i18n/schema.json", "//packages/angular_devkit/build_angular:src/builders/jest/schema.json", "//packages/angular_devkit/build_angular:src/builders/web-test-runner/schema.json", "//packages/angular_devkit/build_angular:src/builders/karma/schema.json", "//packages/angular_devkit/build_angular:src/builders/ng-packagr/schema.json", "//packages/angular_devkit/build_angular:src/builders/prerender/schema.json", "//packages/angular_devkit/build_angular:src/builders/ssr-dev-server/schema.json", "//packages/angular_devkit/build_angular:src/builders/protractor/schema.json", "//packages/angular_devkit/build_angular:src/builders/server/schema.json", "//packages/schematics/angular:app-shell/schema.json", "//packages/schematics/angular:application/schema.json", "//packages/schematics/angular:class/schema.json", "//packages/schematics/angular:component/schema.json", "//packages/schematics/angular:directive/schema.json", "//packages/schematics/angular:enum/schema.json", "//packages/schematics/angular:guard/schema.json", "//packages/schematics/angular:interceptor/schema.json", "//packages/schematics/angular:interface/schema.json", "//packages/schematics/angular:library/schema.json", "//packages/schematics/angular:module/schema.json", "//packages/schematics/angular:ng-new/schema.json", "//packages/schematics/angular:pipe/schema.json", "//packages/schematics/angular:resolver/schema.json", "//packages/schematics/angular:service/schema.json", "//packages/schematics/angular:service-worker/schema.json", "//packages/schematics/angular:web-worker/schema.json", ] cli_json_schema( name = "cli_config_schema", src = "lib/config/workspace-schema.json", out = "lib/config/schema.json", data = CLI_SCHEMA_DATA, ) ts_json_schema( name = "cli_schema", src = "lib/config/workspace-schema.json", data = CLI_SCHEMA_DATA, ) ts_json_schema( name = "update_schematic_schema", src = "src/commands/update/schematic/schema.json", ) ts_library( name = "angular-cli_test_lib", testonly = True, srcs = glob( include = ["**/*_spec.ts"], exclude = [ # NB: we need to exclude the nested node_modules that is laid out by yarn workspaces "node_modules/**", ], ), deps = [ ":angular-cli", "//packages/angular_devkit/core", "//packages/angular_devkit/schematics", "//packages/angular_devkit/schematics/testing", "@npm//@types/semver", "@npm//@types/yargs", ], ) jasmine_node_test( name = "angular-cli_test", srcs = [":angular-cli_test_lib"], ) genrule( name = "license", srcs = ["//:LICENSE"], outs = ["LICENSE"], cmd = "cp $(execpath //:LICENSE) $@", ) pkg_npm( name = "npm_package", pkg_deps = [ "//packages/angular_devkit/architect:package.json", "//packages/angular_devkit/build_angular:package.json", "//packages/angular_devkit/build_webpack:package.json", "//packages/angular_devkit/core:package.json", "//packages/angular_devkit/schematics:package.json", "//packages/schematics/angular:package.json", ], tags = ["release-package"], deps = [ ":README.md", ":angular-cli", ":license", ":src/commands/update/schematic/collection.json", ":src/commands/update/schematic/schema.json", ], ) # @external_end
{ "end_byte": 6468, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular/cli/BUILD.bazel" }
angular-cli/packages/angular/cli/bin/bootstrap.js_0_1280
/** * @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 is used to bootstrap the CLI process by dynamically importing the main initialization code. * This is done to allow the main bin file (`ng`) to remain CommonJS so that older versions of Node.js * can be checked and validated prior to the execution of the CLI. This separate bootstrap file is * needed to allow the use of a dynamic import expression without crashing older versions of Node.js that * do not support dynamic import expressions and would otherwise throw a syntax error. This bootstrap file * is required from the main bin file only after the Node.js version is determined to be in the supported * range. */ // Enable on-disk code caching if available (Node.js 22.8+) // Skip if running inside Bazel via a RUNFILES environment variable check. The cache does not work // well with Bazel's hermeticity requirements. if (!process.env['RUNFILES']) { try { const { enableCompileCache } = require('node:module'); enableCompileCache?.(); } catch {} } // Initialize the Angular CLI void import('../lib/init.js');
{ "end_byte": 1280, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular/cli/bin/bootstrap.js" }
angular-cli/packages/angular/cli/bin/ng.js_0_2527
#!/usr/bin/env node /** * @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 */ /* eslint-disable no-console */ /* eslint-disable import/no-unassigned-import */ 'use strict'; const path = require('path'); // Error if the external CLI appears to be used inside a google3 context. if (process.cwd().split(path.sep).includes('google3')) { console.error( 'This is the external Angular CLI, but you appear to be running in google3. There is a separate, internal version of the CLI which should be used instead. See http://go/angular/cli.', ); process.exit(); } // Provide a title to the process in `ps`. // Due to an obscure Mac bug, do not start this title with any symbol. try { process.title = 'ng ' + Array.from(process.argv).slice(2).join(' '); } catch (_) { // If an error happened above, use the most basic title. process.title = 'ng'; } const rawCommandName = process.argv[2]; if (rawCommandName === '--get-yargs-completions' || rawCommandName === 'completion') { // Skip Node.js supported checks when running ng completion. // A warning at this stage could cause a broken source action (`source <(ng completion script)`) when in the shell init script. require('./bootstrap'); return; } // This node version check ensures that extremely old versions of node are not used. // These may not support ES2015 features such as const/let/async/await/etc. // These would then crash with a hard to diagnose error message. var version = process.versions.node.split('.').map((part) => Number(part)); if (version[0] % 2 === 1) { // Allow new odd numbered releases with a warning (currently v17+) console.warn( 'Node.js version ' + process.version + ' detected.\n' + 'Odd numbered Node.js versions will not enter LTS status and should not be used for production.' + ' For more information, please see https://nodejs.org/en/about/previous-releases/.', ); require('./bootstrap'); } else if (version[0] < 18 || (version[0] === 18 && version[1] < 19)) { // Error and exit if less than 18.19 console.error( 'Node.js version ' + process.version + ' detected.\n' + 'The Angular CLI requires a minimum Node.js version of v18.19.\n\n' + 'Please update your Node.js version or visit https://nodejs.org/ for additional instructions.\n', ); process.exitCode = 3; } else { require('./bootstrap'); }
{ "end_byte": 2527, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular/cli/bin/ng.js" }
angular-cli/packages/angular/cli/lib/init.ts_0_5473
/** * @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 'symbol-observable'; // symbol polyfill must go first import { promises as fs } from 'fs'; import { createRequire } from 'module'; import * as path from 'path'; import { SemVer, major } from 'semver'; import { colors } from '../src/utilities/color'; import { isWarningEnabled } from '../src/utilities/config'; import { disableVersionCheck } from '../src/utilities/environment-options'; import { VERSION } from '../src/utilities/version'; /** * Angular CLI versions prior to v14 may not exit correctly if not forcibly exited * via `process.exit()`. When bootstrapping, `forceExit` will be set to `true` * if the local CLI version is less than v14 to prevent the CLI from hanging on * exit in those cases. */ let forceExit = false; (async (): Promise<typeof import('./cli').default | null> => { /** * Disable Browserslist old data warning as otherwise with every release we'd need to update this dependency * which is cumbersome considering we pin versions and the warning is not user actionable. * `Browserslist: caniuse-lite is outdated. Please run next command `npm update` * See: https://github.com/browserslist/browserslist/blob/819c4337456996d19db6ba953014579329e9c6e1/node.js#L324 */ process.env.BROWSERSLIST_IGNORE_OLD_DATA = '1'; const rawCommandName = process.argv[2]; /** * Disable CLI version mismatch checks and forces usage of the invoked CLI * instead of invoking the local installed version. * * When running `ng new` always favor the global version. As in some * cases orphan `node_modules` would cause the non global CLI to be used. * @see: https://github.com/angular/angular-cli/issues/14603 */ if (disableVersionCheck || rawCommandName === 'new') { return (await import('./cli')).default; } let cli; try { // No error implies a projectLocalCli, which will load whatever // version of ng-cli you have installed in a local package.json const cwdRequire = createRequire(process.cwd() + '/'); const projectLocalCli = cwdRequire.resolve('@angular/cli'); cli = await import(projectLocalCli); const globalVersion = new SemVer(VERSION.full); // Older versions might not have the VERSION export let localVersion = cli.VERSION?.full; if (!localVersion) { try { const localPackageJson = await fs.readFile( path.join(path.dirname(projectLocalCli), '../../package.json'), 'utf-8', ); localVersion = (JSON.parse(localPackageJson) as { version: string }).version; } catch (error) { // eslint-disable-next-line no-console console.error('Version mismatch check skipped. Unable to retrieve local version: ' + error); } } // Ensure older versions of the CLI fully exit const localMajorVersion = major(localVersion); if (localMajorVersion > 0 && localMajorVersion < 14) { forceExit = true; // Versions prior to 14 didn't implement completion command. if (rawCommandName === 'completion') { return null; } } let isGlobalGreater = false; try { isGlobalGreater = localVersion > 0 && globalVersion.compare(localVersion) > 0; } catch (error) { // eslint-disable-next-line no-console console.error('Version mismatch check skipped. Unable to compare local version: ' + error); } // When using the completion command, don't show the warning as otherwise this will break completion. if ( isGlobalGreater && rawCommandName !== '--get-yargs-completions' && rawCommandName !== 'completion' ) { // If using the update command and the global version is greater, use the newer update command // This allows improvements in update to be used in older versions that do not have bootstrapping if ( rawCommandName === 'update' && cli.VERSION && cli.VERSION.major - globalVersion.major <= 1 ) { cli = await import('./cli'); } else if (await isWarningEnabled('versionMismatch')) { // Otherwise, use local version and warn if global is newer than local const warning = `Your global Angular CLI version (${globalVersion}) is greater than your local ` + `version (${localVersion}). The local Angular CLI version is used.\n\n` + 'To disable this warning use "ng config -g cli.warnings.versionMismatch false".'; // eslint-disable-next-line no-console console.error(colors.yellow(warning)); } } } catch { // If there is an error, resolve could not find the ng-cli // library from a package.json. Instead, include it from a relative // path to this script file (which is likely a globally installed // npm package). Most common cause for hitting this is `ng new` cli = await import('./cli'); } if ('default' in cli) { cli = cli['default']; } return cli; })() .then((cli) => cli?.({ cliArgs: process.argv.slice(2), }), ) .then((exitCode = 0) => { if (forceExit) { process.exit(exitCode); } process.exitCode = exitCode; }) .catch((err: Error) => { // eslint-disable-next-line no-console console.error('Unknown error: ' + err.toString()); process.exit(127); });
{ "end_byte": 5473, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular/cli/lib/init.ts" }
angular-cli/packages/angular/cli/lib/cli/index.ts_0_3624
/** * @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 { logging } from '@angular-devkit/core'; import { format, stripVTControlCharacters } from 'node:util'; import { CommandModuleError } from '../../src/command-builder/command-module'; import { runCommand } from '../../src/command-builder/command-runner'; import { colors, supportColor } from '../../src/utilities/color'; import { ngDebug } from '../../src/utilities/environment-options'; import { writeErrorToLogFile } from '../../src/utilities/log-file'; export { VERSION } from '../../src/utilities/version'; const MIN_NODEJS_VERSION = [18, 13] as const; /* eslint-disable no-console */ export default async function (options: { cliArgs: string[] }) { // This node version check ensures that the requirements of the project instance of the CLI are met const [major, minor] = process.versions.node.split('.').map((part) => Number(part)); if ( major < MIN_NODEJS_VERSION[0] || (major === MIN_NODEJS_VERSION[0] && minor < MIN_NODEJS_VERSION[1]) ) { process.stderr.write( `Node.js version ${process.version} detected.\n` + `The Angular CLI requires a minimum of v${MIN_NODEJS_VERSION[0]}.${MIN_NODEJS_VERSION[1]}.\n\n` + 'Please update your Node.js version or visit https://nodejs.org/ for additional instructions.\n', ); return 3; } const colorLevels: Record<string, (message: string) => string> = { info: (s) => s, debug: (s) => s, warn: (s) => colors.bold(colors.yellow(s)), error: (s) => colors.bold(colors.red(s)), fatal: (s) => colors.bold(colors.red(s)), }; const logger = new logging.IndentLogger('cli-main-logger'); const logInfo = console.log; const logError = console.error; const useColor = supportColor(); const loggerFinished = logger.forEach((entry) => { if (!ngDebug && entry.level === 'debug') { return; } const color = useColor ? colorLevels[entry.level] : stripVTControlCharacters; const message = color(entry.message); switch (entry.level) { case 'warn': case 'fatal': case 'error': logError(message); break; default: logInfo(message); break; } }); // Redirect console to logger console.info = console.log = function (...args) { logger.info(format(...args)); }; console.warn = function (...args) { logger.warn(format(...args)); }; console.error = function (...args) { logger.error(format(...args)); }; try { return await runCommand(options.cliArgs, logger); } catch (err) { if (err instanceof CommandModuleError) { logger.fatal(`Error: ${err.message}`); } else if (err instanceof Error) { try { const logPath = writeErrorToLogFile(err); logger.fatal( `An unhandled exception occurred: ${err.message}\n` + `See "${logPath}" for further details.`, ); } catch (e) { logger.fatal( `An unhandled exception occurred: ${err.message}\n` + `Fatal error writing debug log file: ${e}`, ); if (err.stack) { logger.fatal(err.stack); } } return 127; } else if (typeof err === 'string') { logger.fatal(err); } else if (typeof err === 'number') { // Log nothing. } else { logger.fatal(`An unexpected error occurred: ${err}`); } return 1; } finally { logger.complete(); await loggerFinished; } }
{ "end_byte": 3624, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular/cli/lib/cli/index.ts" }
angular-cli/packages/angular/cli/src/typings.ts_0_446
/** * @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 */ declare module 'npm-pick-manifest' { function pickManifest( metadata: import('./utilities/package-metadata').PackageMetadata, selector: string, ): import('./utilities/package-metadata').PackageManifest; export = pickManifest; }
{ "end_byte": 446, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular/cli/src/typings.ts" }
angular-cli/packages/angular/cli/src/utilities/eol.ts_0_555
/** * @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 { EOL } from 'node:os'; const CRLF = '\r\n'; const LF = '\n'; export function getEOL(content: string): string { const newlines = content.match(/(?:\r?\n)/g); if (newlines?.length) { const crlf = newlines.filter((l) => l === CRLF).length; const lf = newlines.length - crlf; return crlf > lf ? CRLF : LF; } return EOL; }
{ "end_byte": 555, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular/cli/src/utilities/eol.ts" }
angular-cli/packages/angular/cli/src/utilities/log-file.ts_0_876
/** * @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 { appendFileSync, mkdtempSync, realpathSync } from 'fs'; import { tmpdir } from 'os'; import { normalize } from 'path'; let logPath: string | undefined; /** * Writes an Error to a temporary log file. * If this method is called multiple times from the same process the same log file will be used. * @returns The path of the generated log file. */ export function writeErrorToLogFile(error: Error): string { if (!logPath) { const tempDirectory = mkdtempSync(realpathSync(tmpdir()) + '/ng-'); logPath = normalize(tempDirectory + '/angular-errors.log'); } appendFileSync(logPath, '[error] ' + (error.stack || error) + '\n\n'); return logPath; }
{ "end_byte": 876, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular/cli/src/utilities/log-file.ts" }
angular-cli/packages/angular/cli/src/utilities/project.ts_0_1559
/** * @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 { normalize } from '@angular-devkit/core'; import * as fs from 'fs'; import * as os from 'os'; import * as path from 'path'; import { findUp } from './find-up'; interface PackageDependencies { dependencies?: Record<string, string>; devDependencies?: Record<string, string>; } export function findWorkspaceFile(currentDirectory = process.cwd()): string | null { const possibleConfigFiles = ['angular.json', '.angular.json']; const configFilePath = findUp(possibleConfigFiles, currentDirectory); if (configFilePath === null) { return null; } const possibleDir = path.dirname(configFilePath); const homedir = os.homedir(); if (normalize(possibleDir) === normalize(homedir)) { const packageJsonPath = path.join(possibleDir, 'package.json'); try { const packageJsonText = fs.readFileSync(packageJsonPath, 'utf-8'); const packageJson = JSON.parse(packageJsonText) as PackageDependencies; if (!containsCliDep(packageJson)) { // No CLI dependency return null; } } catch { // No or invalid package.json return null; } } return configFilePath; } function containsCliDep(obj?: PackageDependencies): boolean { const pkgName = '@angular/cli'; if (!obj) { return false; } return !!(obj.dependencies?.[pkgName] || obj.devDependencies?.[pkgName]); }
{ "end_byte": 1559, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular/cli/src/utilities/project.ts" }
angular-cli/packages/angular/cli/src/utilities/find-up.ts_0_701
/** * @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 { existsSync } from 'fs'; import * as path from 'path'; export function findUp(names: string | string[], from: string) { if (!Array.isArray(names)) { names = [names]; } const root = path.parse(from).root; let currentDir = from; while (currentDir && currentDir !== root) { for (const name of names) { const p = path.join(currentDir, name); if (existsSync(p)) { return p; } } currentDir = path.dirname(currentDir); } return null; }
{ "end_byte": 701, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular/cli/src/utilities/find-up.ts" }
angular-cli/packages/angular/cli/src/utilities/memoize_spec.ts_0_4470
/** * @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 { memoize } from './memoize'; describe('memoize', () => { class Dummy { @memoize get random(): number { return Math.random(); } @memoize getRandom(_parameter?: unknown): number { return Math.random(); } @memoize async getRandomAsync(): Promise<number> { return Math.random(); } } it('should call method once', () => { const dummy = new Dummy(); const val1 = dummy.getRandom(); const val2 = dummy.getRandom(); // Should return same value since memoized expect(val1).toBe(val2); }); it('should call method once (async)', async () => { const dummy = new Dummy(); const [val1, val2] = await Promise.all([dummy.getRandomAsync(), dummy.getRandomAsync()]); // Should return same value since memoized expect(val1).toBe(val2); }); it('should call getter once', () => { const dummy = new Dummy(); const val1 = dummy.random; const val2 = dummy.random; // Should return same value since memoized expect(val2).toBe(val1); }); it('should call method when parameter changes', () => { const dummy = new Dummy(); const val1 = dummy.getRandom(1); const val2 = dummy.getRandom(2); const val3 = dummy.getRandom(1); const val4 = dummy.getRandom(2); // Should return same value since memoized expect(val1).not.toBe(val2); expect(val1).toBe(val3); expect(val2).toBe(val4); }); it('should error when used on non getters and methods', () => { const test = () => { class DummyError { @memoize set random(_value: number) {} } return new DummyError(); }; expect(test).toThrowError('Memoize decorator can only be used on methods or get accessors.'); }); describe('validate method arguments', () => { it('should error when using Map', () => { const test = () => new Dummy().getRandom(new Map()); expect(test).toThrowError(/Argument \[object Map\] is JSON serializable./); }); it('should error when using Symbol', () => { const test = () => new Dummy().getRandom(Symbol('')); expect(test).toThrowError(/Argument Symbol\(\) is JSON serializable/); }); it('should error when using Function', () => { const test = () => new Dummy().getRandom(function () {}); expect(test).toThrowError(/Argument function \(\) { } is JSON serializable/); }); it('should error when using Map in an array', () => { const test = () => new Dummy().getRandom([new Map(), true]); expect(test).toThrowError(/Argument \[object Map\],true is JSON serializable/); }); it('should error when using Map in an Object', () => { const test = () => new Dummy().getRandom({ foo: true, prop: new Map() }); expect(test).toThrowError(/Argument \[object Object\] is JSON serializable/); }); it('should error when using Function in an Object', () => { const test = () => new Dummy().getRandom({ foo: true, prop: function () {} }); expect(test).toThrowError(/Argument \[object Object\] is JSON serializable/); }); it('should not error when using primitive values in an array', () => { const test = () => new Dummy().getRandom([1, true, ['foo']]); expect(test).not.toThrow(); }); it('should not error when using primitive values in an Object', () => { const test = () => new Dummy().getRandom({ foo: true, prop: [1, true] }); expect(test).not.toThrow(); }); it('should not error when using Boolean', () => { const test = () => new Dummy().getRandom(true); expect(test).not.toThrow(); }); it('should not error when using String', () => { const test = () => new Dummy().getRandom('foo'); expect(test).not.toThrow(); }); it('should not error when using Number', () => { const test = () => new Dummy().getRandom(1); expect(test).not.toThrow(); }); it('should not error when using null', () => { const test = () => new Dummy().getRandom(null); expect(test).not.toThrow(); }); it('should not error when using undefined', () => { const test = () => new Dummy().getRandom(undefined); expect(test).not.toThrow(); }); }); });
{ "end_byte": 4470, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular/cli/src/utilities/memoize_spec.ts" }
angular-cli/packages/angular/cli/src/utilities/prompt.ts_0_1495
/** * @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 { isTTY } from './tty'; export async function askConfirmation( message: string, defaultResponse: boolean, noTTYResponse?: boolean, ): Promise<boolean> { if (!isTTY()) { return noTTYResponse ?? defaultResponse; } const { confirm } = await import('@inquirer/prompts'); const answer = await confirm({ message, default: defaultResponse, theme: { prefix: '', }, }); return answer; } export async function askQuestion( message: string, choices: { name: string; value: string | null }[], defaultResponseIndex: number, noTTYResponse: null | string, ): Promise<string | null> { if (!isTTY()) { return noTTYResponse; } const { select } = await import('@inquirer/prompts'); const answer = await select({ message, choices, default: defaultResponseIndex, theme: { prefix: '', }, }); return answer; } export async function askChoices( message: string, choices: { name: string; value: string }[], noTTYResponse: string[] | null, ): Promise<string[] | null> { if (!isTTY()) { return noTTYResponse; } const { checkbox } = await import('@inquirer/prompts'); const answers = await checkbox({ message, choices, theme: { prefix: '', }, }); return answers; }
{ "end_byte": 1495, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular/cli/src/utilities/prompt.ts" }
angular-cli/packages/angular/cli/src/utilities/environment-options.ts_0_1158
/** * @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 */ function isPresent(variable: string | undefined): variable is string { return typeof variable === 'string' && variable !== ''; } function isDisabled(variable: string | undefined): boolean { return isPresent(variable) && (variable === '0' || variable.toLowerCase() === 'false'); } function isEnabled(variable: string | undefined): boolean { return isPresent(variable) && (variable === '1' || variable.toLowerCase() === 'true'); } function optional(variable: string | undefined): boolean | undefined { if (!isPresent(variable)) { return undefined; } return isEnabled(variable); } export const analyticsDisabled = isDisabled(process.env['NG_CLI_ANALYTICS']); export const isCI = isEnabled(process.env['CI']); export const disableVersionCheck = isEnabled(process.env['NG_DISABLE_VERSION_CHECK']); export const ngDebug = isEnabled(process.env['NG_DEBUG']); export const forceAutocomplete = optional(process.env['NG_FORCE_AUTOCOMPLETE']);
{ "end_byte": 1158, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular/cli/src/utilities/environment-options.ts" }
angular-cli/packages/angular/cli/src/utilities/package-tree.ts_0_2394
/** * @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 * as fs from 'fs'; import { dirname, join } from 'path'; import * as resolve from 'resolve'; import { NgAddSaveDependency } from './package-metadata'; interface PackageJson { name: string; version: string; dependencies?: Record<string, string>; devDependencies?: Record<string, string>; peerDependencies?: Record<string, string>; optionalDependencies?: Record<string, string>; 'ng-update'?: { migrations?: string; }; 'ng-add'?: { save?: NgAddSaveDependency; }; } function getAllDependencies(pkg: PackageJson): Set<[string, string]> { return new Set([ ...Object.entries(pkg.dependencies || []), ...Object.entries(pkg.devDependencies || []), ...Object.entries(pkg.peerDependencies || []), ...Object.entries(pkg.optionalDependencies || []), ]); } export interface PackageTreeNode { name: string; version: string; path: string; package: PackageJson | undefined; } export async function readPackageJson(packageJsonPath: string): Promise<PackageJson | undefined> { try { return JSON.parse((await fs.promises.readFile(packageJsonPath)).toString()) as PackageJson; } catch { return undefined; } } export function findPackageJson(workspaceDir: string, packageName: string): string | undefined { try { // avoid require.resolve here, see: https://github.com/angular/angular-cli/pull/18610#issuecomment-681980185 const packageJsonPath = resolve.sync(`${packageName}/package.json`, { basedir: workspaceDir }); return packageJsonPath; } catch { return undefined; } } export async function getProjectDependencies(dir: string): Promise<Map<string, PackageTreeNode>> { const pkg = await readPackageJson(join(dir, 'package.json')); if (!pkg) { throw new Error('Could not find package.json'); } const results = new Map<string, PackageTreeNode>(); for (const [name, version] of getAllDependencies(pkg)) { const packageJsonPath = findPackageJson(dir, name); if (!packageJsonPath) { continue; } results.set(name, { name, version, path: dirname(packageJsonPath), package: await readPackageJson(packageJsonPath), }); } return results; }
{ "end_byte": 2394, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular/cli/src/utilities/package-tree.ts" }
angular-cli/packages/angular/cli/src/utilities/package-metadata.ts_0_7234
/** * @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 { logging } from '@angular-devkit/core'; import * as lockfile from '@yarnpkg/lockfile'; import { existsSync, readFileSync } from 'fs'; import * as ini from 'ini'; import { homedir } from 'os'; import type { Manifest, Packument } from 'pacote'; import * as path from 'path'; export interface PackageMetadata extends Packument, NgPackageManifestProperties { tags: Record<string, PackageManifest>; versions: Record<string, PackageManifest>; } export interface NpmRepositoryPackageJson extends PackageMetadata { requestedName?: string; } export type NgAddSaveDependency = 'dependencies' | 'devDependencies' | boolean; export interface PackageIdentifier { type: 'git' | 'tag' | 'version' | 'range' | 'file' | 'directory' | 'remote'; name: string; scope: string | null; registry: boolean; raw: string; fetchSpec: string; rawSpec: string; } export interface NgPackageManifestProperties { 'ng-add'?: { save?: NgAddSaveDependency; }; 'ng-update'?: { migrations?: string; packageGroup?: string[] | Record<string, string>; packageGroupName?: string; requirements?: string[] | Record<string, string>; }; } export interface PackageManifest extends Manifest, NgPackageManifestProperties { deprecated?: boolean; } interface PackageManagerOptions extends Record<string, unknown> { forceAuth?: Record<string, unknown>; } let npmrc: PackageManagerOptions; const npmPackageJsonCache = new Map<string, Promise<Partial<NpmRepositoryPackageJson>>>(); function ensureNpmrc(logger: logging.LoggerApi, usingYarn: boolean, verbose: boolean): void { if (!npmrc) { try { npmrc = readOptions(logger, false, verbose); } catch {} if (usingYarn) { try { npmrc = { ...npmrc, ...readOptions(logger, true, verbose) }; } catch {} } } } function readOptions( logger: logging.LoggerApi, yarn = false, showPotentials = false, ): PackageManagerOptions { const cwd = process.cwd(); const baseFilename = yarn ? 'yarnrc' : 'npmrc'; const dotFilename = '.' + baseFilename; let globalPrefix: string; if (process.env.PREFIX) { globalPrefix = process.env.PREFIX; } else { globalPrefix = path.dirname(process.execPath); if (process.platform !== 'win32') { globalPrefix = path.dirname(globalPrefix); } } const defaultConfigLocations = [ (!yarn && process.env.NPM_CONFIG_GLOBALCONFIG) || path.join(globalPrefix, 'etc', baseFilename), (!yarn && process.env.NPM_CONFIG_USERCONFIG) || path.join(homedir(), dotFilename), ]; const projectConfigLocations: string[] = [path.join(cwd, dotFilename)]; if (yarn) { const root = path.parse(cwd).root; for (let curDir = path.dirname(cwd); curDir && curDir !== root; curDir = path.dirname(curDir)) { projectConfigLocations.unshift(path.join(curDir, dotFilename)); } } if (showPotentials) { logger.info(`Locating potential ${baseFilename} files:`); } let rcOptions: PackageManagerOptions = {}; for (const location of [...defaultConfigLocations, ...projectConfigLocations]) { if (existsSync(location)) { if (showPotentials) { logger.info(`Trying '${location}'...found.`); } const data = readFileSync(location, 'utf8'); // Normalize RC options that are needed by 'npm-registry-fetch'. // See: https://github.com/npm/npm-registry-fetch/blob/ebddbe78a5f67118c1f7af2e02c8a22bcaf9e850/index.js#L99-L126 const rcConfig: PackageManagerOptions = yarn ? lockfile.parse(data) : ini.parse(data); rcOptions = normalizeOptions(rcConfig, location, rcOptions); } } const envVariablesOptions: PackageManagerOptions = {}; for (const [key, value] of Object.entries(process.env)) { if (!value) { continue; } let normalizedName = key.toLowerCase(); if (normalizedName.startsWith('npm_config_')) { normalizedName = normalizedName.substring(11); } else if (yarn && normalizedName.startsWith('yarn_')) { normalizedName = normalizedName.substring(5); } else { continue; } if ( normalizedName === 'registry' && rcOptions['registry'] && value === 'https://registry.yarnpkg.com' && process.env['npm_config_user_agent']?.includes('yarn') ) { // When running `ng update` using yarn (`yarn ng update`), yarn will set the `npm_config_registry` env variable to `https://registry.yarnpkg.com` // even when an RC file is present with a different repository. // This causes the registry specified in the RC to always be overridden with the below logic. continue; } normalizedName = normalizedName.replace(/(?!^)_/g, '-'); // don't replace _ at the start of the key.s envVariablesOptions[normalizedName] = value; } return normalizeOptions(envVariablesOptions, undefined, rcOptions); } function normalizeOptions( rawOptions: PackageManagerOptions, location = process.cwd(), existingNormalizedOptions: PackageManagerOptions = {}, ): PackageManagerOptions { const options = { ...existingNormalizedOptions }; for (const [key, value] of Object.entries(rawOptions)) { let substitutedValue = value; // Substitute any environment variable references. if (typeof value === 'string') { substitutedValue = value.replace(/\$\{([^}]+)\}/, (_, name) => process.env[name] || ''); } switch (key) { // Unless auth options are scope with the registry url it appears that npm-registry-fetch ignores them, // even though they are documented. // https://github.com/npm/npm-registry-fetch/blob/8954f61d8d703e5eb7f3d93c9b40488f8b1b62ac/README.md // https://github.com/npm/npm-registry-fetch/blob/8954f61d8d703e5eb7f3d93c9b40488f8b1b62ac/auth.js#L45-L91 case '_authToken': case 'token': case 'username': case 'password': case '_auth': case 'auth': options['forceAuth'] ??= {}; options['forceAuth'][key] = substitutedValue; break; case 'noproxy': case 'no-proxy': options['noProxy'] = substitutedValue; break; case 'maxsockets': options['maxSockets'] = substitutedValue; break; case 'https-proxy': case 'proxy': options['proxy'] = substitutedValue; break; case 'strict-ssl': options['strictSSL'] = substitutedValue; break; case 'local-address': options['localAddress'] = substitutedValue; break; case 'cafile': if (typeof substitutedValue === 'string') { const cafile = path.resolve(path.dirname(location), substitutedValue); try { options['ca'] = readFileSync(cafile, 'utf8').replace(/\r?\n/g, '\n'); } catch {} } break; case 'before': options['before'] = typeof substitutedValue === 'string' ? new Date(substitutedValue) : substitutedValue; break; default: options[key] = substitutedValue; break; } } return options; }
{ "end_byte": 7234, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular/cli/src/utilities/package-metadata.ts" }
angular-cli/packages/angular/cli/src/utilities/package-metadata.ts_7236_9865
export async function fetchPackageMetadata( name: string, logger: logging.LoggerApi, options?: { registry?: string; usingYarn?: boolean; verbose?: boolean; }, ): Promise<PackageMetadata> { const { usingYarn, verbose, registry } = { registry: undefined, usingYarn: false, verbose: false, ...options, }; ensureNpmrc(logger, usingYarn, verbose); const { packument } = await import('pacote'); const response = await packument(name, { fullMetadata: true, ...npmrc, ...(registry ? { registry } : {}), }); if (!response.versions) { // While pacote type declares that versions cannot be undefined this is not the case. response.versions = {}; } // Normalize the response const metadata: PackageMetadata = { ...response, tags: {}, }; if (response['dist-tags']) { for (const [tag, version] of Object.entries(response['dist-tags'])) { const manifest = metadata.versions[version]; if (manifest) { metadata.tags[tag] = manifest; } else if (verbose) { logger.warn(`Package ${metadata.name} has invalid version metadata for '${tag}'.`); } } } return metadata; } export async function fetchPackageManifest( name: string, logger: logging.LoggerApi, options: { registry?: string; usingYarn?: boolean; verbose?: boolean; } = {}, ): Promise<PackageManifest> { const { usingYarn = false, verbose = false, registry } = options; ensureNpmrc(logger, usingYarn, verbose); const { manifest } = await import('pacote'); const response = await manifest(name, { fullMetadata: true, ...npmrc, ...(registry ? { registry } : {}), }); return response; } export async function getNpmPackageJson( packageName: string, logger: logging.LoggerApi, options: { registry?: string; usingYarn?: boolean; verbose?: boolean; } = {}, ): Promise<Partial<NpmRepositoryPackageJson>> { const cachedResponse = npmPackageJsonCache.get(packageName); if (cachedResponse) { return cachedResponse; } const { usingYarn = false, verbose = false, registry } = options; ensureNpmrc(logger, usingYarn, verbose); const { packument } = await import('pacote'); const response = packument(packageName, { fullMetadata: true, ...npmrc, ...(registry ? { registry } : {}), }).then((response) => { // While pacote type declares that versions cannot be undefined this is not the case. if (!response.versions) { response.versions = {}; } return response; }); npmPackageJsonCache.set(packageName, response); return response; }
{ "end_byte": 9865, "start_byte": 7236, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular/cli/src/utilities/package-metadata.ts" }
angular-cli/packages/angular/cli/src/utilities/json-file.ts_0_3514
/** * @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 { JsonValue } from '@angular-devkit/core'; import { readFileSync, writeFileSync } from 'fs'; import { Node, ParseError, applyEdits, findNodeAtLocation, getNodeValue, modify, parse, parseTree, printParseErrorCode, } from 'jsonc-parser'; import { getEOL } from './eol'; export type InsertionIndex = (properties: string[]) => number; export type JSONPath = (string | number)[]; /** @internal */ export class JSONFile { content: string; private eol: string; constructor(private readonly path: string) { const buffer = readFileSync(this.path); if (buffer) { this.content = buffer.toString(); } else { throw new Error(`Could not read '${path}'.`); } this.eol = getEOL(this.content); } private _jsonAst: Node | undefined; private get JsonAst(): Node | undefined { if (this._jsonAst) { return this._jsonAst; } const errors: ParseError[] = []; this._jsonAst = parseTree(this.content, errors, { allowTrailingComma: true }); if (errors.length) { formatError(this.path, errors); } return this._jsonAst; } get(jsonPath: JSONPath): unknown { const jsonAstNode = this.JsonAst; if (!jsonAstNode) { return undefined; } if (jsonPath.length === 0) { return getNodeValue(jsonAstNode); } const node = findNodeAtLocation(jsonAstNode, jsonPath); return node === undefined ? undefined : getNodeValue(node); } modify( jsonPath: JSONPath, value: JsonValue | undefined, insertInOrder?: InsertionIndex | false, ): boolean { if (value === undefined && this.get(jsonPath) === undefined) { // Cannot remove a value which doesn't exist. return false; } let getInsertionIndex: InsertionIndex | undefined; if (insertInOrder === undefined) { const property = jsonPath.slice(-1)[0]; getInsertionIndex = (properties) => [...properties, property].sort().findIndex((p) => p === property); } else if (insertInOrder !== false) { getInsertionIndex = insertInOrder; } const edits = modify(this.content, jsonPath, value, { getInsertionIndex, // TODO: use indentation from original file. formattingOptions: { insertSpaces: true, tabSize: 2, eol: this.eol, }, }); if (edits.length === 0) { return false; } this.content = applyEdits(this.content, edits); this._jsonAst = undefined; return true; } save(): void { writeFileSync(this.path, this.content); } } // eslint-disable-next-line @typescript-eslint/no-explicit-any export function readAndParseJson(path: string): any { const errors: ParseError[] = []; const content = parse(readFileSync(path, 'utf-8'), errors, { allowTrailingComma: true }); if (errors.length) { formatError(path, errors); } return content; } function formatError(path: string, errors: ParseError[]): never { const { error, offset } = errors[0]; throw new Error( `Failed to parse "${path}" as JSON AST Object. ${printParseErrorCode( error, )} at location: ${offset}.`, ); } // eslint-disable-next-line @typescript-eslint/no-explicit-any export function parseJson(content: string): any { return parse(content, undefined, { allowTrailingComma: true }); }
{ "end_byte": 3514, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular/cli/src/utilities/json-file.ts" }
angular-cli/packages/angular/cli/src/utilities/completion.ts_0_6667
/** * @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 { json, logging } from '@angular-devkit/core'; import { execFile } from 'child_process'; import { promises as fs } from 'fs'; import * as path from 'path'; import { env } from 'process'; import { colors } from '../utilities/color'; import { getWorkspace } from '../utilities/config'; import { forceAutocomplete } from '../utilities/environment-options'; import { isTTY } from '../utilities/tty'; import { assertIsError } from './error'; import { askConfirmation } from './prompt'; /** Interface for the autocompletion configuration stored in the global workspace. */ interface CompletionConfig { /** * Whether or not the user has been prompted to set up autocompletion. If `true`, should *not* * prompt them again. */ prompted?: boolean; } /** * Checks if it is appropriate to prompt the user to setup autocompletion. If not, does nothing. If * so prompts and sets up autocompletion for the user. Returns an exit code if the program should * terminate, otherwise returns `undefined`. * @returns an exit code if the program should terminate, undefined otherwise. */ export async function considerSettingUpAutocompletion( command: string, logger: logging.Logger, ): Promise<number | undefined> { // Check if we should prompt the user to setup autocompletion. const completionConfig = await getCompletionConfig(); if (!(await shouldPromptForAutocompletionSetup(command, completionConfig))) { return undefined; // Already set up or prompted previously, nothing to do. } // Prompt the user and record their response. const shouldSetupAutocompletion = await promptForAutocompletion(); if (!shouldSetupAutocompletion) { // User rejected the prompt and doesn't want autocompletion. logger.info( ` Ok, you won't be prompted again. Should you change your mind, the following command will set up autocompletion for you: ${colors.yellow(`ng completion`)} `.trim(), ); // Save configuration to remember that the user was prompted and avoid prompting again. await setCompletionConfig({ ...completionConfig, prompted: true }); return undefined; } // User accepted the prompt, set up autocompletion. let rcFile: string; try { rcFile = await initializeAutocomplete(); } catch (err) { assertIsError(err); // Failed to set up autocompeletion, log the error and abort. logger.error(err.message); return 1; } // Notify the user autocompletion was set up successfully. logger.info( ` Appended \`source <(ng completion script)\` to \`${rcFile}\`. Restart your terminal or run the following to autocomplete \`ng\` commands: ${colors.yellow(`source <(ng completion script)`)} `.trim(), ); if (!(await hasGlobalCliInstall())) { logger.warn( 'Setup completed successfully, but there does not seem to be a global install of the' + ' Angular CLI. For autocompletion to work, the CLI will need to be on your `$PATH`, which' + ' is typically done with the `-g` flag in `npm install -g @angular/cli`.' + '\n\n' + 'For more information, see https://angular.dev/cli/completion#global-install', ); } // Save configuration to remember that the user was prompted. await setCompletionConfig({ ...completionConfig, prompted: true }); return undefined; } async function getCompletionConfig(): Promise<CompletionConfig | undefined> { const wksp = await getWorkspace('global'); return wksp?.getCli()?.['completion']; } async function setCompletionConfig(config: CompletionConfig): Promise<void> { const wksp = await getWorkspace('global'); if (!wksp) { throw new Error(`Could not find global workspace`); } wksp.extensions['cli'] ??= {}; const cli = wksp.extensions['cli']; if (!json.isJsonObject(cli)) { throw new Error( `Invalid config found at ${wksp.filePath}. \`extensions.cli\` should be an object.`, ); } cli.completion = config as json.JsonObject; await wksp.save(); } async function shouldPromptForAutocompletionSetup( command: string, config?: CompletionConfig, ): Promise<boolean> { // Force whether or not to prompt for autocomplete to give an easy path for e2e testing to skip. if (forceAutocomplete !== undefined) { return forceAutocomplete; } // Don't prompt on `ng update`, 'ng version' or `ng completion`. if (['version', 'update', 'completion'].includes(command)) { return false; } // Non-interactive and continuous integration systems don't care about autocompletion. if (!isTTY()) { return false; } // Skip prompt if the user has already been prompted. if (config?.prompted) { return false; } // `$HOME` variable is necessary to find RC files to modify. const home = env['HOME']; if (!home) { return false; } // Get possible RC files for the current shell. const shell = env['SHELL']; if (!shell) { return false; } const rcFiles = getShellRunCommandCandidates(shell, home); if (!rcFiles) { return false; // Unknown shell. } // Don't prompt if the user is missing a global CLI install. Autocompletion won't work after setup // anyway and could be annoying for users running one-off commands via `npx` or using `npm start`. if ((await hasGlobalCliInstall()) === false) { return false; } // Check each RC file if they already use `ng completion script` in any capacity and don't prompt. for (const rcFile of rcFiles) { const contents = await fs.readFile(rcFile, 'utf-8').catch(() => undefined); if (contents?.includes('ng completion script')) { return false; } } return true; } async function promptForAutocompletion(): Promise<boolean> { const autocomplete = await askConfirmation( ` Would you like to enable autocompletion? This will set up your terminal so pressing TAB while typing Angular CLI commands will show possible options and autocomplete arguments. (Enabling autocompletion will modify configuration files in your home directory.) ` .split('\n') .join(' ') .trim(), true, ); return autocomplete; } /** * Sets up autocompletion for the user's terminal. This attempts to find the configuration file for * the current shell (`.bashrc`, `.zshrc`, etc.) and append a command which enables autocompletion * for the Angular CLI. Supports only Bash and Zsh. Returns whether or not it was successful. * @return The full path of the configuration file modified. */
{ "end_byte": 6667, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular/cli/src/utilities/completion.ts" }
angular-cli/packages/angular/cli/src/utilities/completion.ts_6668_10970
export async function initializeAutocomplete(): Promise<string> { // Get the currently active `$SHELL` and `$HOME` environment variables. const shell = env['SHELL']; if (!shell) { throw new Error( '`$SHELL` environment variable not set. Angular CLI autocompletion only supports Bash or' + " Zsh. If you're on Windows, Cmd and Powershell don't support command autocompletion," + ' but Git Bash or Windows Subsystem for Linux should work, so please try again in one of' + ' those environments.', ); } const home = env['HOME']; if (!home) { throw new Error( '`$HOME` environment variable not set. Setting up autocompletion modifies configuration files' + ' in the home directory and must be set.', ); } // Get all the files we can add `ng completion` to which apply to the user's `$SHELL`. const runCommandCandidates = getShellRunCommandCandidates(shell, home); if (!runCommandCandidates) { throw new Error( `Unknown \`$SHELL\` environment variable value (${shell}). Angular CLI autocompletion only supports Bash or Zsh.`, ); } // Get the first file that already exists or fallback to a new file of the first candidate. const candidates = await Promise.allSettled( runCommandCandidates.map((rcFile) => fs.access(rcFile).then(() => rcFile)), ); const rcFile = candidates.find( (result): result is PromiseFulfilledResult<string> => result.status === 'fulfilled', )?.value ?? runCommandCandidates[0]; // Append Angular autocompletion setup to RC file. try { await fs.appendFile( rcFile, '\n\n# Load Angular CLI autocompletion.\nsource <(ng completion script)\n', ); } catch (err) { assertIsError(err); throw new Error(`Failed to append autocompletion setup to \`${rcFile}\`:\n${err.message}`); } return rcFile; } /** Returns an ordered list of possible candidates of RC files used by the given shell. */ function getShellRunCommandCandidates(shell: string, home: string): string[] | undefined { if (shell.toLowerCase().includes('bash')) { return ['.bashrc', '.bash_profile', '.profile'].map((file) => path.join(home, file)); } else if (shell.toLowerCase().includes('zsh')) { return ['.zshrc', '.zsh_profile', '.profile'].map((file) => path.join(home, file)); } else { return undefined; } } /** * Returns whether the user has a global CLI install. * Execution from `npx` is *not* considered a global CLI install. * * This does *not* mean the current execution is from a global CLI install, only that a global * install exists on the system. */ export function hasGlobalCliInstall(): Promise<boolean> { // List all binaries with the `ng` name on the user's `$PATH`. return new Promise<boolean>((resolve) => { execFile('which', ['-a', 'ng'], (error, stdout) => { if (error) { // No instances of `ng` on the user's `$PATH` // `which` returns exit code 2 if an invalid option is specified and `-a` doesn't appear to be // supported on all systems. Other exit codes mean unknown errors occurred. Can't tell whether // CLI is globally installed, so treat this as inconclusive. // `which` was killed by a signal and did not exit gracefully. Maybe it hung or something else // went very wrong, so treat this as inconclusive. resolve(false); return; } // Successfully listed all `ng` binaries on the `$PATH`. Look for at least one line which is a // global install. We can't easily identify global installs, but local installs are typically // placed in `node_modules/.bin` by NPM / Yarn. `npx` also currently caches files at // `~/.npm/_npx/*/node_modules/.bin/`, so the same logic applies. const lines = stdout.split('\n').filter((line) => line !== ''); const hasGlobalInstall = lines.some((line) => { // A binary is a local install if it is a direct child of a `node_modules/.bin/` directory. const parent = path.parse(path.parse(line).dir); const grandparent = path.parse(parent.dir); const localInstall = grandparent.base === 'node_modules' && parent.base === '.bin'; return !localInstall; }); return resolve(hasGlobalInstall); }); }); }
{ "end_byte": 10970, "start_byte": 6668, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular/cli/src/utilities/completion.ts" }
angular-cli/packages/angular/cli/src/utilities/version.ts_0_971
/** * @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 { readFileSync } from 'fs'; import { resolve } from 'path'; // Same structure as used in framework packages class Version { public readonly major: string; public readonly minor: string; public readonly patch: string; constructor(public readonly full: string) { const [major, minor, patch] = full.split('-', 1)[0].split('.', 3); this.major = major; this.minor = minor; this.patch = patch; } } // TODO(bazel): Convert this to use build-time version stamping after flipping the build script to use bazel // export const VERSION = new Version('0.0.0-PLACEHOLDER'); export const VERSION = new Version( ( JSON.parse(readFileSync(resolve(__dirname, '../../package.json'), 'utf-8')) as { version: string; } ).version, );
{ "end_byte": 971, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular/cli/src/utilities/version.ts" }
angular-cli/packages/angular/cli/src/utilities/config.ts_0_8113
/** * @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 { json, workspaces } from '@angular-devkit/core'; import { existsSync, promises as fs } from 'fs'; import * as os from 'os'; import * as path from 'path'; import { PackageManager } from '../../lib/config/workspace-schema'; import { findUp } from './find-up'; import { JSONFile, readAndParseJson } from './json-file'; function isJsonObject(value: json.JsonValue | undefined): value is json.JsonObject { return value !== undefined && json.isJsonObject(value); } function createWorkspaceHost(): workspaces.WorkspaceHost { return { readFile(path) { return fs.readFile(path, 'utf-8'); }, async writeFile(path, data) { await fs.writeFile(path, data); }, async isDirectory(path) { try { const stats = await fs.stat(path); return stats.isDirectory(); } catch { return false; } }, async isFile(path) { try { const stats = await fs.stat(path); return stats.isFile(); } catch { return false; } }, }; } export const workspaceSchemaPath = path.join(__dirname, '../../lib/config/schema.json'); const configNames = ['angular.json', '.angular.json']; const globalFileName = '.angular-config.json'; const defaultGlobalFilePath = path.join(os.homedir(), globalFileName); function xdgConfigHome(home: string, configFile?: string): string { // https://specifications.freedesktop.org/basedir-spec/basedir-spec-latest.html const xdgConfigHome = process.env['XDG_CONFIG_HOME'] || path.join(home, '.config'); const xdgAngularHome = path.join(xdgConfigHome, 'angular'); return configFile ? path.join(xdgAngularHome, configFile) : xdgAngularHome; } function xdgConfigHomeOld(home: string): string { // Check the configuration files in the old location that should be: // - $XDG_CONFIG_HOME/.angular-config.json (if XDG_CONFIG_HOME is set) // - $HOME/.config/angular/.angular-config.json (otherwise) const p = process.env['XDG_CONFIG_HOME'] || path.join(home, '.config', 'angular'); return path.join(p, '.angular-config.json'); } function projectFilePath(projectPath?: string): string | null { // Find the configuration, either where specified, in the Angular CLI project // (if it's in node_modules) or from the current process. return ( (projectPath && findUp(configNames, projectPath)) || findUp(configNames, process.cwd()) || findUp(configNames, __dirname) ); } function globalFilePath(): string | null { const home = os.homedir(); if (!home) { return null; } // follow XDG Base Directory spec // note that createGlobalSettings() will continue creating // global file in home directory, with this user will have // choice to move change its location to meet XDG convention const xdgConfig = xdgConfigHome(home, 'config.json'); if (existsSync(xdgConfig)) { return xdgConfig; } // NOTE: This check is for the old configuration location, for more // information see https://github.com/angular/angular-cli/pull/20556 const xdgConfigOld = xdgConfigHomeOld(home); if (existsSync(xdgConfigOld)) { /* eslint-disable no-console */ console.warn( `Old configuration location detected: ${xdgConfigOld}\n` + `Please move the file to the new location ~/.config/angular/config.json`, ); return xdgConfigOld; } if (existsSync(defaultGlobalFilePath)) { return defaultGlobalFilePath; } return null; } export class AngularWorkspace { readonly basePath: string; constructor( private readonly workspace: workspaces.WorkspaceDefinition, readonly filePath: string, ) { this.basePath = path.dirname(filePath); } get extensions(): Record<string, json.JsonValue | undefined> { return this.workspace.extensions; } get projects(): workspaces.ProjectDefinitionCollection { return this.workspace.projects; } // Temporary helper functions to support refactoring // eslint-disable-next-line @typescript-eslint/no-explicit-any getCli(): Record<string, any> | undefined { return this.workspace.extensions['cli'] as Record<string, unknown>; } // eslint-disable-next-line @typescript-eslint/no-explicit-any getProjectCli(projectName: string): Record<string, any> | undefined { const project = this.workspace.projects.get(projectName); return project?.extensions['cli'] as Record<string, unknown>; } save(): Promise<void> { return workspaces.writeWorkspace( this.workspace, createWorkspaceHost(), this.filePath, workspaces.WorkspaceFormat.JSON, ); } static async load(workspaceFilePath: string): Promise<AngularWorkspace> { const result = await workspaces.readWorkspace( workspaceFilePath, createWorkspaceHost(), workspaces.WorkspaceFormat.JSON, ); return new AngularWorkspace(result.workspace, workspaceFilePath); } } const cachedWorkspaces = new Map<string, AngularWorkspace | undefined>(); export async function getWorkspace(level: 'global'): Promise<AngularWorkspace>; export async function getWorkspace(level: 'local'): Promise<AngularWorkspace | undefined>; export async function getWorkspace( level: 'local' | 'global', ): Promise<AngularWorkspace | undefined>; export async function getWorkspace( level: 'local' | 'global', ): Promise<AngularWorkspace | undefined> { if (cachedWorkspaces.has(level)) { return cachedWorkspaces.get(level); } const configPath = level === 'local' ? projectFilePath() : globalFilePath(); if (!configPath) { if (level === 'global') { // Unlike a local config, a global config is not mandatory. // So we create an empty one in memory and keep it as such until it has been modified and saved. const globalWorkspace = new AngularWorkspace( { extensions: {}, projects: new workspaces.ProjectDefinitionCollection() }, defaultGlobalFilePath, ); cachedWorkspaces.set(level, globalWorkspace); return globalWorkspace; } cachedWorkspaces.set(level, undefined); return undefined; } try { const workspace = await AngularWorkspace.load(configPath); cachedWorkspaces.set(level, workspace); return workspace; } catch (error) { throw new Error( `Workspace config file cannot be loaded: ${configPath}` + `\n${error instanceof Error ? error.message : error}`, ); } } /** * This method will load the workspace configuration in raw JSON format. * When `level` is `global` and file doesn't exists, it will be created. * * NB: This method is intended to be used only for `ng config`. */ export async function getWorkspaceRaw( level: 'local' | 'global' = 'local', ): Promise<[JSONFile | null, string | null]> { let configPath = level === 'local' ? projectFilePath() : globalFilePath(); if (!configPath) { if (level === 'global') { configPath = defaultGlobalFilePath; // Config doesn't exist, force create it. const globalWorkspace = await getWorkspace('global'); await globalWorkspace.save(); } else { return [null, null]; } } return [new JSONFile(configPath), configPath]; } export async function validateWorkspace(data: json.JsonObject, isGlobal: boolean): Promise<void> { const schema = readAndParseJson(workspaceSchemaPath); // We should eventually have a dedicated global config schema and use that to validate. const schemaToValidate: json.schema.JsonSchema = isGlobal ? { '$ref': '#/definitions/global', definitions: schema['definitions'], } : schema; const { formats } = await import('@angular-devkit/schematics'); const registry = new json.schema.CoreSchemaRegistry(formats.standardFormats); const validator = await registry.compile(schemaToValidate); const { success, errors } = await validator(data); if (!success) { throw new json.schema.SchemaValidationException(errors); } }
{ "end_byte": 8113, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular/cli/src/utilities/config.ts" }
angular-cli/packages/angular/cli/src/utilities/config.ts_8115_12866
function findProjectByPath(workspace: AngularWorkspace, location: string): string | null { const isInside = (base: string, potential: string): boolean => { const absoluteBase = path.resolve(workspace.basePath, base); const absolutePotential = path.resolve(workspace.basePath, potential); const relativePotential = path.relative(absoluteBase, absolutePotential); if (!relativePotential.startsWith('..') && !path.isAbsolute(relativePotential)) { return true; } return false; }; const projects = Array.from(workspace.projects) .map(([name, project]) => [project.root, name] as [string, string]) .filter((tuple) => isInside(tuple[0], location)) // Sort tuples by depth, with the deeper ones first. Since the first member is a path and // we filtered all invalid paths, the longest will be the deepest (and in case of equality // the sort is stable and the first declared project will win). .sort((a, b) => b[0].length - a[0].length); if (projects.length === 0) { return null; } else if (projects.length > 1) { const found = new Set<string>(); const sameRoots = projects.filter((v) => { if (!found.has(v[0])) { found.add(v[0]); return false; } return true; }); if (sameRoots.length > 0) { // Ambiguous location - cannot determine a project return null; } } return projects[0][1]; } export function getProjectByCwd(workspace: AngularWorkspace): string | null { if (workspace.projects.size === 1) { // If there is only one project, return that one. return Array.from(workspace.projects.keys())[0]; } const project = findProjectByPath(workspace, process.cwd()); if (project) { return project; } return null; } export async function getConfiguredPackageManager(): Promise<PackageManager | null> { const getPackageManager = (source: json.JsonValue | undefined): PackageManager | null => { if (isJsonObject(source)) { const value = source['packageManager']; if (value && typeof value === 'string') { return value as PackageManager; } } return null; }; let result: PackageManager | null = null; const workspace = await getWorkspace('local'); if (workspace) { const project = getProjectByCwd(workspace); if (project) { result = getPackageManager(workspace.projects.get(project)?.extensions['cli']); } result ??= getPackageManager(workspace.extensions['cli']); } if (!result) { const globalOptions = await getWorkspace('global'); result = getPackageManager(globalOptions?.extensions['cli']); } return result; } export async function getSchematicDefaults( collection: string, schematic: string, project?: string | null, ): Promise<{}> { const result = {}; const mergeOptions = (source: json.JsonValue | undefined): void => { if (isJsonObject(source)) { // Merge options from the qualified name Object.assign(result, source[`${collection}:${schematic}`]); // Merge options from nested collection schematics const collectionOptions = source[collection]; if (isJsonObject(collectionOptions)) { Object.assign(result, collectionOptions[schematic]); } } }; // Global level schematic options const globalOptions = await getWorkspace('global'); mergeOptions(globalOptions?.extensions['schematics']); const workspace = await getWorkspace('local'); if (workspace) { // Workspace level schematic options mergeOptions(workspace.extensions['schematics']); project = project || getProjectByCwd(workspace); if (project) { // Project level schematic options mergeOptions(workspace.projects.get(project)?.extensions['schematics']); } } return result; } export async function isWarningEnabled(warning: string): Promise<boolean> { const getWarning = (source: json.JsonValue | undefined): boolean | undefined => { if (isJsonObject(source)) { const warnings = source['warnings']; if (isJsonObject(warnings)) { const value = warnings[warning]; if (typeof value == 'boolean') { return value; } } } }; let result: boolean | undefined; const workspace = await getWorkspace('local'); if (workspace) { const project = getProjectByCwd(workspace); if (project) { result = getWarning(workspace.projects.get(project)?.extensions['cli']); } result = result ?? getWarning(workspace.extensions['cli']); } if (result === undefined) { const globalOptions = await getWorkspace('global'); result = getWarning(globalOptions?.extensions['cli']); } // All warnings are enabled by default return result ?? true; }
{ "end_byte": 12866, "start_byte": 8115, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular/cli/src/utilities/config.ts" }
angular-cli/packages/angular/cli/src/utilities/error.ts_0_597
/** * @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 assert from 'assert'; export function assertIsError(value: unknown): asserts value is Error & { code?: string } { const isError = value instanceof Error || // The following is needing to identify errors coming from RxJs. (typeof value === 'object' && value && 'name' in value && 'message' in value); assert(isError, 'catch clause variable is not an Error instance'); }
{ "end_byte": 597, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular/cli/src/utilities/error.ts" }
angular-cli/packages/angular/cli/src/utilities/color.ts_0_718
/** * @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 { WriteStream } from 'node:tty'; export { color as colors, figures } from 'listr2'; export function supportColor(stream: NodeJS.WritableStream = process.stdout): boolean { if (stream instanceof WriteStream) { return stream.hasColors(); } try { // The hasColors function does not rely on any instance state and should ideally be static return WriteStream.prototype.hasColors(); } catch { return process.env['FORCE_COLOR'] !== undefined && process.env['FORCE_COLOR'] !== '0'; } }
{ "end_byte": 718, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular/cli/src/utilities/color.ts" }
angular-cli/packages/angular/cli/src/utilities/tty.ts_0_709
/** * @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 */ function _isTruthy(value: undefined | string): boolean { // Returns true if value is a string that is anything but 0 or false. return value !== undefined && value !== '0' && value.toUpperCase() !== 'FALSE'; } export function isTTY(stream: NodeJS.WriteStream = process.stdout): boolean { // If we force TTY, we always return true. const force = process.env['NG_FORCE_TTY']; if (force !== undefined) { return _isTruthy(force); } return !!stream.isTTY && !_isTruthy(process.env['CI']); }
{ "end_byte": 709, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular/cli/src/utilities/tty.ts" }
angular-cli/packages/angular/cli/src/utilities/package-manager.ts_0_883
/** * @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 { isJsonObject, json } from '@angular-devkit/core'; import { execSync, spawn } from 'child_process'; import { existsSync, promises as fs, realpathSync, rmSync } from 'fs'; import { tmpdir } from 'os'; import { join } from 'path'; import { PackageManager } from '../../lib/config/workspace-schema'; import { AngularWorkspace, getProjectByCwd } from './config'; import { memoize } from './memoize'; interface PackageManagerOptions { saveDev: string; install: string; installAll?: string; prefix: string; noLockfile: string; } export interface PackageManagerUtilsContext { globalConfiguration: AngularWorkspace; workspace?: AngularWorkspace; root: string; }
{ "end_byte": 883, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular/cli/src/utilities/package-manager.ts" }
angular-cli/packages/angular/cli/src/utilities/package-manager.ts_885_9228
export class PackageManagerUtils { constructor(private readonly context: PackageManagerUtilsContext) {} /** Get the package manager name. */ get name(): PackageManager { return this.getName(); } /** Get the package manager version. */ get version(): string | undefined { return this.getVersion(this.name); } /** Install a single package. */ async install( packageName: string, save: 'dependencies' | 'devDependencies' | true = true, extraArgs: string[] = [], cwd?: string, ): Promise<boolean> { const packageManagerArgs = this.getArguments(); const installArgs: string[] = [packageManagerArgs.install, packageName]; if (save === 'devDependencies') { installArgs.push(packageManagerArgs.saveDev); } return this.run([...installArgs, ...extraArgs], { cwd, silent: true }); } /** Install all packages. */ async installAll(extraArgs: string[] = [], cwd?: string): Promise<boolean> { const packageManagerArgs = this.getArguments(); const installArgs: string[] = []; if (packageManagerArgs.installAll) { installArgs.push(packageManagerArgs.installAll); } return this.run([...installArgs, ...extraArgs], { cwd, silent: true }); } /** Install a single package temporary. */ async installTemp( packageName: string, extraArgs?: string[], ): Promise<{ success: boolean; tempNodeModules: string; }> { const tempPath = await fs.mkdtemp(join(realpathSync(tmpdir()), 'angular-cli-packages-')); // clean up temp directory on process exit process.on('exit', () => { try { rmSync(tempPath, { recursive: true, maxRetries: 3 }); } catch {} }); // NPM will warn when a `package.json` is not found in the install directory // Example: // npm WARN enoent ENOENT: no such file or directory, open '/tmp/.ng-temp-packages-84Qi7y/package.json' // npm WARN .ng-temp-packages-84Qi7y No description // npm WARN .ng-temp-packages-84Qi7y No repository field. // npm WARN .ng-temp-packages-84Qi7y No license field. // While we can use `npm init -y` we will end up needing to update the 'package.json' anyways // because of missing fields. await fs.writeFile( join(tempPath, 'package.json'), JSON.stringify({ name: 'temp-cli-install', description: 'temp-cli-install', repository: 'temp-cli-install', license: 'MIT', }), ); // setup prefix/global modules path const packageManagerArgs = this.getArguments(); const tempNodeModules = join(tempPath, 'node_modules'); // Yarn will not append 'node_modules' to the path const prefixPath = this.name === PackageManager.Yarn ? tempNodeModules : tempPath; const installArgs: string[] = [ ...(extraArgs ?? []), `${packageManagerArgs.prefix}="${prefixPath}"`, packageManagerArgs.noLockfile, ]; return { success: await this.install(packageName, true, installArgs, tempPath), tempNodeModules, }; } private getArguments(): PackageManagerOptions { switch (this.name) { case PackageManager.Yarn: return { saveDev: '--dev', install: 'add', prefix: '--modules-folder', noLockfile: '--no-lockfile', }; case PackageManager.Pnpm: return { saveDev: '--save-dev', install: 'add', installAll: 'install', prefix: '--prefix', noLockfile: '--no-lockfile', }; case PackageManager.Bun: return { saveDev: '--development', install: 'add', installAll: 'install', prefix: '--cwd', noLockfile: '', }; default: return { saveDev: '--save-dev', install: 'install', installAll: 'install', prefix: '--prefix', noLockfile: '--no-package-lock', }; } } private async run( args: string[], options: { cwd?: string; silent?: boolean } = {}, ): Promise<boolean> { const { cwd = process.cwd(), silent = false } = options; return new Promise((resolve) => { const bufferedOutput: { stream: NodeJS.WriteStream; data: Buffer }[] = []; const childProcess = spawn(this.name, args, { // Always pipe stderr to allow for failures to be reported stdio: silent ? ['ignore', 'ignore', 'pipe'] : 'pipe', shell: true, cwd, }).on('close', (code: number) => { if (code === 0) { resolve(true); } else { bufferedOutput.forEach(({ stream, data }) => stream.write(data)); resolve(false); } }); childProcess.stdout?.on('data', (data: Buffer) => bufferedOutput.push({ stream: process.stdout, data: data }), ); childProcess.stderr?.on('data', (data: Buffer) => bufferedOutput.push({ stream: process.stderr, data: data }), ); }); } @memoize private getVersion(name: PackageManager): string | undefined { try { return execSync(`${name} --version`, { encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'], env: { ...process.env, // NPM updater notifier will prevents the child process from closing until it timeout after 3 minutes. NO_UPDATE_NOTIFIER: '1', NPM_CONFIG_UPDATE_NOTIFIER: 'false', }, }).trim(); } catch { return undefined; } } @memoize private getName(): PackageManager { const packageManager = this.getConfiguredPackageManager(); if (packageManager) { return packageManager; } const hasNpmLock = this.hasLockfile(PackageManager.Npm); const hasYarnLock = this.hasLockfile(PackageManager.Yarn); const hasPnpmLock = this.hasLockfile(PackageManager.Pnpm); const hasBunLock = this.hasLockfile(PackageManager.Bun); // PERF NOTE: `this.getVersion` spawns the package a the child_process which can take around ~300ms at times. // Therefore, we should only call this method when needed. IE: don't call `this.getVersion(PackageManager.Pnpm)` unless truly needed. // The result of this method is not stored in a variable because it's memoized. if (hasNpmLock) { // Has NPM lock file. if (!hasYarnLock && !hasPnpmLock && !hasBunLock && this.getVersion(PackageManager.Npm)) { // Only NPM lock file and NPM binary is available. return PackageManager.Npm; } } else { // No NPM lock file. if (hasYarnLock && this.getVersion(PackageManager.Yarn)) { // Yarn lock file and Yarn binary is available. return PackageManager.Yarn; } else if (hasPnpmLock && this.getVersion(PackageManager.Pnpm)) { // PNPM lock file and PNPM binary is available. return PackageManager.Pnpm; } else if (hasBunLock && this.getVersion(PackageManager.Bun)) { // Bun lock file and Bun binary is available. return PackageManager.Bun; } } if (!this.getVersion(PackageManager.Npm)) { // Doesn't have NPM installed. const hasYarn = !!this.getVersion(PackageManager.Yarn); const hasPnpm = !!this.getVersion(PackageManager.Pnpm); const hasBun = !!this.getVersion(PackageManager.Bun); if (hasYarn && !hasPnpm && !hasBun) { return PackageManager.Yarn; } else if (hasPnpm && !hasYarn && !hasBun) { return PackageManager.Pnpm; } else if (hasBun && !hasYarn && !hasPnpm) { return PackageManager.Bun; } } // TODO: This should eventually inform the user of ambiguous package manager usage. // Potentially with a prompt to choose and optionally set as the default. return PackageManager.Npm; } private hasLockfile(packageManager: PackageManager): boolean { let lockfileName: string; switch (packageManager) { case PackageManager.Yarn: lockfileName = 'yarn.lock'; break; case PackageManager.Pnpm: lockfileName = 'pnpm-lock.yaml'; break; case PackageManager.Bun: lockfileName = 'bun.lockb'; break; case PackageManager.Npm: default: lockfileName = 'package-lock.json'; break; } return existsSync(join(this.context.root, lockfileName)); }
{ "end_byte": 9228, "start_byte": 885, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular/cli/src/utilities/package-manager.ts" }
angular-cli/packages/angular/cli/src/utilities/package-manager.ts_9232_10164
private getConfiguredPackageManager(): PackageManager | undefined { const getPackageManager = (source: json.JsonValue | undefined): PackageManager | undefined => { if (source && isJsonObject(source)) { const value = source['packageManager']; if (typeof value === 'string') { return value as PackageManager; } } return undefined; }; let result: PackageManager | undefined; const { workspace: localWorkspace, globalConfiguration: globalWorkspace } = this.context; if (localWorkspace) { const project = getProjectByCwd(localWorkspace); if (project) { result = getPackageManager(localWorkspace.projects.get(project)?.extensions['cli']); } result ??= getPackageManager(localWorkspace.extensions['cli']); } if (!result) { result = getPackageManager(globalWorkspace.extensions['cli']); } return result; } }
{ "end_byte": 10164, "start_byte": 9232, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular/cli/src/utilities/package-manager.ts" }
angular-cli/packages/angular/cli/src/utilities/load-esm.ts_0_1203
/** * @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 */ /** * Lazily compiled dynamic import loader function. */ let load: (<T>(modulePath: string | URL) => Promise<T>) | undefined; /** * This uses a dynamic import to load a module which may be ESM. * CommonJS code can load ESM code via a dynamic import. Unfortunately, TypeScript * will currently, unconditionally downlevel dynamic import into a require call. * require calls cannot load ESM code and will result in a runtime error. To workaround * this, a Function constructor is used to prevent TypeScript from changing the dynamic import. * Once TypeScript provides support for keeping the dynamic import this workaround can * be dropped. * * @param modulePath The path of the module to load. * @returns A Promise that resolves to the dynamically imported module. */ export function loadEsmModule<T>(modulePath: string | URL): Promise<T> { load ??= new Function('modulePath', `return import(modulePath);`) as Exclude< typeof load, undefined >; return load(modulePath); }
{ "end_byte": 1203, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular/cli/src/utilities/load-esm.ts" }
angular-cli/packages/angular/cli/src/utilities/memoize.ts_0_2163
/** * @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 */ /** * A decorator that memoizes methods and getters. * * **Note**: Be cautious where and how to use this decorator as the size of the cache will grow unbounded. * * @see https://en.wikipedia.org/wiki/Memoization */ export function memoize<This, Args extends unknown[], Return>( target: (this: This, ...args: Args) => Return, context: ClassMemberDecoratorContext, ) { if (context.kind !== 'method' && context.kind !== 'getter') { throw new Error('Memoize decorator can only be used on methods or get accessors.'); } const cache = new Map<string, Return>(); return function (this: This, ...args: Args): Return { for (const arg of args) { if (!isJSONSerializable(arg)) { throw new Error( `Argument ${isNonPrimitive(arg) ? arg.toString() : arg} is JSON serializable.`, ); } } const key = JSON.stringify(args); if (cache.has(key)) { return cache.get(key) as Return; } const result = target.apply(this, args); cache.set(key, result); return result; }; } /** Method to check if value is a non primitive. */ function isNonPrimitive(value: unknown): value is object | Function | symbol { return ( (value !== null && typeof value === 'object') || typeof value === 'function' || typeof value === 'symbol' ); } /** Method to check if the values are JSON serializable */ function isJSONSerializable(value: unknown): boolean { if (!isNonPrimitive(value)) { // Can be seralized since it's a primitive. return true; } let nestedValues: unknown[] | undefined; if (Array.isArray(value)) { // It's an array, check each item. nestedValues = value; } else if (Object.prototype.toString.call(value) === '[object Object]') { // It's a plain object, check each value. nestedValues = Object.values(value); } if (!nestedValues || nestedValues.some((v) => !isJSONSerializable(v))) { return false; } return true; }
{ "end_byte": 2163, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular/cli/src/utilities/memoize.ts" }
angular-cli/packages/angular/cli/src/command-builder/schematics-command-module.ts_0_1622
/** * @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 { JsonValue, normalize as devkitNormalize, schema } from '@angular-devkit/core'; import { Collection, UnsuccessfulWorkflowExecution, formats } from '@angular-devkit/schematics'; import { FileSystemCollectionDescription, FileSystemSchematicDescription, NodeWorkflow, } from '@angular-devkit/schematics/tools'; import { relative, resolve } from 'path'; import { Argv } from 'yargs'; import { isPackageNameSafeForAnalytics } from '../analytics/analytics'; import { EventCustomDimension } from '../analytics/analytics-parameters'; import { getProjectByCwd, getSchematicDefaults } from '../utilities/config'; import { assertIsError } from '../utilities/error'; import { memoize } from '../utilities/memoize'; import { isTTY } from '../utilities/tty'; import { CommandModule, CommandModuleImplementation, CommandScope, Options, OtherOptions, } from './command-module'; import { Option, parseJsonSchemaToOptions } from './utilities/json-schema'; import { SchematicEngineHost } from './utilities/schematic-engine-host'; import { subscribeToWorkflow } from './utilities/schematic-workflow'; export const DEFAULT_SCHEMATICS_COLLECTION = '@schematics/angular'; export interface SchematicsCommandArgs { interactive: boolean; force: boolean; 'dry-run': boolean; defaults: boolean; } export interface SchematicsExecutionOptions extends Options<SchematicsCommandArgs> { packageRegistry?: string; }
{ "end_byte": 1622, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular/cli/src/command-builder/schematics-command-module.ts" }
angular-cli/packages/angular/cli/src/command-builder/schematics-command-module.ts_1624_11097
export abstract class SchematicsCommandModule extends CommandModule<SchematicsCommandArgs> implements CommandModuleImplementation<SchematicsCommandArgs> { override scope = CommandScope.In; protected readonly allowPrivateSchematics: boolean = false; async builder(argv: Argv): Promise<Argv<SchematicsCommandArgs>> { return argv .option('interactive', { describe: 'Enable interactive input prompts.', type: 'boolean', default: true, }) .option('dry-run', { describe: 'Run through and reports activity without writing out results.', type: 'boolean', alias: ['d'], default: false, }) .option('defaults', { describe: 'Disable interactive input prompts for options with a default.', type: 'boolean', default: false, }) .option('force', { describe: 'Force overwriting of existing files.', type: 'boolean', default: false, }) .strict(); } /** Get schematic schema options.*/ protected async getSchematicOptions( collection: Collection<FileSystemCollectionDescription, FileSystemSchematicDescription>, schematicName: string, workflow: NodeWorkflow, ): Promise<Option[]> { const schematic = collection.createSchematic(schematicName, true); const { schemaJson } = schematic.description; if (!schemaJson) { return []; } return parseJsonSchemaToOptions(workflow.registry, schemaJson); } @memoize protected getOrCreateWorkflowForBuilder(collectionName: string): NodeWorkflow { return new NodeWorkflow(this.context.root, { resolvePaths: this.getResolvePaths(collectionName), engineHostCreator: (options) => new SchematicEngineHost(options.resolvePaths), }); } @memoize protected async getOrCreateWorkflowForExecution( collectionName: string, options: SchematicsExecutionOptions, ): Promise<NodeWorkflow> { const { logger, root, packageManager } = this.context; const { force, dryRun, packageRegistry } = options; const workflow = new NodeWorkflow(root, { force, dryRun, packageManager: packageManager.name, // A schema registry is required to allow customizing addUndefinedDefaults registry: new schema.CoreSchemaRegistry(formats.standardFormats), packageRegistry, resolvePaths: this.getResolvePaths(collectionName), schemaValidation: true, optionTransforms: [ // Add configuration file defaults async (schematic, current) => { const projectName = typeof current?.project === 'string' ? current.project : this.getProjectName(); return { ...(await getSchematicDefaults(schematic.collection.name, schematic.name, projectName)), ...current, }; }, ], engineHostCreator: (options) => new SchematicEngineHost(options.resolvePaths), }); workflow.registry.addPostTransform(schema.transforms.addUndefinedDefaults); workflow.registry.useXDeprecatedProvider((msg) => logger.warn(msg)); workflow.registry.addSmartDefaultProvider('projectName', () => this.getProjectName()); const workingDir = devkitNormalize(relative(this.context.root, process.cwd())); workflow.registry.addSmartDefaultProvider('workingDirectory', () => workingDir === '' ? undefined : workingDir, ); let shouldReportAnalytics = true; workflow.engineHost.registerOptionsTransform(async (schematic, options) => { // Report analytics if (shouldReportAnalytics) { shouldReportAnalytics = false; const { collection: { name: collectionName }, name: schematicName, } = schematic; const analytics = isPackageNameSafeForAnalytics(collectionName) ? await this.getAnalytics() : undefined; analytics?.reportSchematicRunEvent({ [EventCustomDimension.SchematicCollectionName]: collectionName, [EventCustomDimension.SchematicName]: schematicName, ...this.getAnalyticsParameters(options as unknown as {}), }); } return options; }); if (options.interactive !== false && isTTY()) { workflow.registry.usePromptProvider(async (definitions: Array<schema.PromptDefinition>) => { let prompts: typeof import('@inquirer/prompts') | undefined; const answers: Record<string, JsonValue> = {}; for (const definition of definitions) { if (options.defaults && definition.default !== undefined) { continue; } // Only load prompt package if needed prompts ??= await import('@inquirer/prompts'); switch (definition.type) { case 'confirmation': answers[definition.id] = await prompts.confirm({ message: definition.message, default: definition.default as boolean | undefined, }); break; case 'list': if (!definition.items?.length) { continue; } answers[definition.id] = await ( definition.multiselect ? prompts.checkbox : prompts.select )({ message: definition.message, validate: (values) => { if (!definition.validator) { return true; } return definition.validator(Object.values(values).map(({ value }) => value)); }, default: definition.default, choices: definition.items?.map((item) => typeof item == 'string' ? { name: item, value: item, } : { name: item.label, value: item.value, }, ), }); break; case 'input': { let finalValue: JsonValue | undefined; answers[definition.id] = await prompts.input({ message: definition.message, default: definition.default as string | undefined, async validate(value) { if (definition.validator === undefined) { return true; } let lastValidation: ReturnType<typeof definition.validator> = false; for (const type of definition.propertyTypes) { let potential; switch (type) { case 'string': potential = String(value); break; case 'integer': case 'number': potential = Number(value); break; default: potential = value; break; } lastValidation = await definition.validator(potential); // Can be a string if validation fails if (lastValidation === true) { finalValue = potential; return true; } } return lastValidation; }, }); // Use validated value if present. // This ensures the correct type is inserted into the final schema options. if (finalValue !== undefined) { answers[definition.id] = finalValue; } break; } } } return answers; }); } return workflow; } @memoize protected async getSchematicCollections(): Promise<Set<string>> { // Resolve relative collections from the location of `angular.json` const resolveRelativeCollection = (collectionName: string) => collectionName.charAt(0) === '.' ? resolve(this.context.root, collectionName) : collectionName; const getSchematicCollections = ( configSection: Record<string, unknown> | undefined, ): Set<string> | undefined => { if (!configSection) { return undefined; } const { schematicCollections } = configSection; if (Array.isArray(schematicCollections)) { return new Set(schematicCollections.map((c) => resolveRelativeCollection(c))); } return undefined; }; const { workspace, globalConfiguration } = this.context; if (workspace) { const project = getProjectByCwd(workspace); if (project) { const value = getSchematicCollections(workspace.getProjectCli(project)); if (value) { return value; } } } const value = getSchematicCollections(workspace?.getCli()) ?? getSchematicCollections(globalConfiguration.getCli()); if (value) { return value; } return new Set([DEFAULT_SCHEMATICS_COLLECTION]); } protected parseSchematicInfo( schematic: string | undefined, ): [collectionName: string | undefined, schematicName: string | undefined] { if (schematic?.includes(':')) { const [collectionName, schematicName] = schematic.split(':', 2); return [collectionName, schematicName]; } return [undefined, schematic]; }
{ "end_byte": 11097, "start_byte": 1624, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular/cli/src/command-builder/schematics-command-module.ts" }
angular-cli/packages/angular/cli/src/command-builder/schematics-command-module.ts_11101_13343
protected async runSchematic(options: { executionOptions: SchematicsExecutionOptions; schematicOptions: OtherOptions; collectionName: string; schematicName: string; }): Promise<number> { const { logger } = this.context; const { schematicOptions, executionOptions, collectionName, schematicName } = options; const workflow = await this.getOrCreateWorkflowForExecution(collectionName, executionOptions); if (!schematicName) { throw new Error('schematicName cannot be undefined.'); } const { unsubscribe, files } = subscribeToWorkflow(workflow, logger); try { await workflow .execute({ collection: collectionName, schematic: schematicName, options: schematicOptions, logger, allowPrivate: this.allowPrivateSchematics, }) .toPromise(); if (!files.size) { logger.info('Nothing to be done.'); } if (executionOptions.dryRun) { logger.warn(`\nNOTE: The "--dry-run" option means no changes were made.`); } } catch (err) { // In case the workflow was not successful, show an appropriate error message. if (err instanceof UnsuccessfulWorkflowExecution) { // "See above" because we already printed the error. logger.fatal('The Schematic workflow failed. See above.'); } else { assertIsError(err); logger.fatal(err.message); } return 1; } finally { unsubscribe(); } return 0; } private getProjectName(): string | undefined { const { workspace } = this.context; if (!workspace) { return undefined; } const projectName = getProjectByCwd(workspace); if (projectName) { return projectName; } return undefined; } private getResolvePaths(collectionName: string): string[] { const { workspace, root } = this.context; return workspace ? // Workspace collectionName === DEFAULT_SCHEMATICS_COLLECTION ? // Favor __dirname for @schematics/angular to use the build-in version [__dirname, process.cwd(), root] : [process.cwd(), root, __dirname] : // Global [__dirname, process.cwd()]; } }
{ "end_byte": 13343, "start_byte": 11101, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular/cli/src/command-builder/schematics-command-module.ts" }
angular-cli/packages/angular/cli/src/command-builder/architect-command-module.ts_0_7158
/** * @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 { Target } from '@angular-devkit/architect'; import { workspaces } from '@angular-devkit/core'; import { Argv } from 'yargs'; import { getProjectByCwd } from '../utilities/config'; import { memoize } from '../utilities/memoize'; import { ArchitectBaseCommandModule } from './architect-base-command-module'; import { CommandModuleError, CommandModuleImplementation, Options, OtherOptions, } from './command-module'; export interface ArchitectCommandArgs { configuration?: string; project?: string; } export abstract class ArchitectCommandModule extends ArchitectBaseCommandModule<ArchitectCommandArgs> implements CommandModuleImplementation<ArchitectCommandArgs> { abstract readonly multiTarget: boolean; findDefaultBuilderName?( project: workspaces.ProjectDefinition, target: Target, ): Promise<string | undefined>; async builder(argv: Argv): Promise<Argv<ArchitectCommandArgs>> { const target = this.getArchitectTarget(); // Add default builder if target is not in project and a command default is provided if (this.findDefaultBuilderName && this.context.workspace) { for (const [project, projectDefinition] of this.context.workspace.projects) { if (projectDefinition.targets.has(target)) { continue; } const defaultBuilder = await this.findDefaultBuilderName(projectDefinition, { project, target, }); if (defaultBuilder) { projectDefinition.targets.set(target, { builder: defaultBuilder, }); } } } const project = this.getArchitectProject(); const { jsonHelp, getYargsCompletions, help } = this.context.args.options; const localYargs: Argv<ArchitectCommandArgs> = argv .positional('project', { describe: 'The name of the project to build. Can be an application or a library.', type: 'string', // Hide choices from JSON help so that we don't display them in AIO. choices: jsonHelp ? undefined : this.getProjectChoices(), }) .option('configuration', { describe: `One or more named builder configurations as a comma-separated ` + `list as specified in the "configurations" section in angular.json.\n` + `The builder uses the named configurations to run the given target.\n` + `For more information, see https://angular.dev/reference/configs/workspace-config#alternate-build-configurations.`, alias: 'c', type: 'string', // Show only in when using --help and auto completion because otherwise comma seperated configuration values will be invalid. // Also, hide choices from JSON help so that we don't display them in AIO. choices: (getYargsCompletions || help) && !jsonHelp && project ? this.getConfigurationChoices(project) : undefined, }) .strict(); if (!project) { return localYargs; } const schemaOptions = await this.getArchitectTargetOptions({ project, target, }); return this.addSchemaOptionsToCommand(localYargs, schemaOptions); } async run(options: Options<ArchitectCommandArgs> & OtherOptions): Promise<number | void> { const target = this.getArchitectTarget(); const { configuration = '', project, ...architectOptions } = options; if (!project) { // This runs each target sequentially. // Running them in parallel would jumble the log messages. let result = 0; const projectNames = this.getProjectNamesByTarget(target); if (!projectNames) { return this.onMissingTarget('Cannot determine project or target for command.'); } for (const project of projectNames) { result |= await this.runSingleTarget({ configuration, target, project }, architectOptions); } return result; } else { return await this.runSingleTarget({ configuration, target, project }, architectOptions); } } private getArchitectProject(): string | undefined { const { options, positional } = this.context.args; const [, projectName] = positional; if (projectName) { return projectName; } // Yargs allows positional args to be used as flags. if (typeof options['project'] === 'string') { return options['project']; } const target = this.getArchitectTarget(); const projectFromTarget = this.getProjectNamesByTarget(target); return projectFromTarget?.length ? projectFromTarget[0] : undefined; } @memoize private getProjectNamesByTarget(target: string): string[] | undefined { const workspace = this.getWorkspaceOrThrow(); const allProjectsForTargetName: string[] = []; for (const [name, project] of workspace.projects) { if (project.targets.has(target)) { allProjectsForTargetName.push(name); } } if (allProjectsForTargetName.length === 0) { return undefined; } if (this.multiTarget) { // For multi target commands, we always list all projects that have the target. return allProjectsForTargetName; } else { if (allProjectsForTargetName.length === 1) { return allProjectsForTargetName; } const maybeProject = getProjectByCwd(workspace); if (maybeProject) { return allProjectsForTargetName.includes(maybeProject) ? [maybeProject] : undefined; } const { getYargsCompletions, help } = this.context.args.options; if (!getYargsCompletions && !help) { // Only issue the below error when not in help / completion mode. throw new CommandModuleError( 'Cannot determine project for command.\n' + 'This is a multi-project workspace and more than one project supports this command. ' + `Run "ng ${this.command}" to execute the command for a specific project or change the current ` + 'working directory to a project directory.\n\n' + `Available projects are:\n${allProjectsForTargetName .sort() .map((p) => `- ${p}`) .join('\n')}`, ); } } return undefined; } /** @returns a sorted list of project names to be used for auto completion. */ private getProjectChoices(): string[] | undefined { const { workspace } = this.context; return workspace ? [...workspace.projects.keys()].sort() : undefined; } /** @returns a sorted list of configuration names to be used for auto completion. */ private getConfigurationChoices(project: string): string[] | undefined { const projectDefinition = this.context.workspace?.projects.get(project); if (!projectDefinition) { return undefined; } const target = this.getArchitectTarget(); const configurations = projectDefinition.targets.get(target)?.configurations; return configurations ? Object.keys(configurations).sort() : undefined; } }
{ "end_byte": 7158, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular/cli/src/command-builder/architect-command-module.ts" }
angular-cli/packages/angular/cli/src/command-builder/command-module.ts_0_2635
/** * @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 { logging, schema } from '@angular-devkit/core'; import { readFileSync } from 'fs'; import * as path from 'path'; import yargs, { ArgumentsCamelCase, Argv, CamelCaseKey, CommandModule as YargsCommandModule, } from 'yargs'; import { Parser as yargsParser } from 'yargs/helpers'; import { getAnalyticsUserId } from '../analytics/analytics'; import { AnalyticsCollector } from '../analytics/analytics-collector'; import { EventCustomDimension, EventCustomMetric } from '../analytics/analytics-parameters'; import { considerSettingUpAutocompletion } from '../utilities/completion'; import { AngularWorkspace } from '../utilities/config'; import { memoize } from '../utilities/memoize'; import { PackageManagerUtils } from '../utilities/package-manager'; import { Option, addSchemaOptionsToCommand } from './utilities/json-schema'; export type Options<T> = { [key in keyof T as CamelCaseKey<key>]: T[key] }; export enum CommandScope { /** Command can only run inside an Angular workspace. */ In, /** Command can only run outside an Angular workspace. */ Out, /** Command can run inside and outside an Angular workspace. */ Both, } export interface CommandContext { currentDirectory: string; root: string; workspace?: AngularWorkspace; globalConfiguration: AngularWorkspace; logger: logging.Logger; packageManager: PackageManagerUtils; /** Arguments parsed in free-from without parser configuration. */ args: { positional: string[]; options: { help: boolean; jsonHelp: boolean; getYargsCompletions: boolean; } & Record<string, unknown>; }; } export type OtherOptions = Record<string, unknown>; export interface CommandModuleImplementation<T extends {} = {}> extends Omit<YargsCommandModule<{}, T>, 'builder' | 'handler'> { /** Scope in which the command can be executed in. */ scope: CommandScope; /** Path used to load the long description for the command in JSON help text. */ longDescriptionPath?: string; /** Object declaring the options the command accepts, or a function accepting and returning a yargs instance. */ builder(argv: Argv): Promise<Argv<T>> | Argv<T>; /** A function which will be passed the parsed argv. */ run(options: Options<T> & OtherOptions): Promise<number | void> | number | void; } export interface FullDescribe { describe?: string; longDescription?: string; longDescriptionRelativePath?: string; }
{ "end_byte": 2635, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular/cli/src/command-builder/command-module.ts" }
angular-cli/packages/angular/cli/src/command-builder/command-module.ts_2637_9788
export abstract class CommandModule<T extends {} = {}> implements CommandModuleImplementation<T> { abstract readonly command: string; abstract readonly describe: string | false; abstract readonly longDescriptionPath?: string; protected readonly shouldReportAnalytics: boolean = true; readonly scope: CommandScope = CommandScope.Both; private readonly optionsWithAnalytics = new Map<string, string>(); constructor(protected readonly context: CommandContext) {} /** * Description object which contains the long command descroption. * This is used to generate JSON help wich is used in AIO. * * `false` will result in a hidden command. */ public get fullDescribe(): FullDescribe | false { return this.describe === false ? false : { describe: this.describe, ...(this.longDescriptionPath ? { longDescriptionRelativePath: path .relative(path.join(__dirname, '../../../../'), this.longDescriptionPath) .replace(/\\/g, path.posix.sep), longDescription: readFileSync(this.longDescriptionPath, 'utf8').replace( /\r\n/g, '\n', ), } : {}), }; } protected get commandName(): string { return this.command.split(' ', 1)[0]; } abstract builder(argv: Argv): Promise<Argv<T>> | Argv<T>; abstract run(options: Options<T> & OtherOptions): Promise<number | void> | number | void; async handler(args: ArgumentsCamelCase<T> & OtherOptions): Promise<void> { const { _, $0, ...options } = args; // Camelize options as yargs will return the object in kebab-case when camel casing is disabled. const camelCasedOptions: Record<string, unknown> = {}; for (const [key, value] of Object.entries(options)) { camelCasedOptions[yargsParser.camelCase(key)] = value; } // Set up autocompletion if appropriate. const autocompletionExitCode = await considerSettingUpAutocompletion( this.commandName, this.context.logger, ); if (autocompletionExitCode !== undefined) { process.exitCode = autocompletionExitCode; return; } // Gather and report analytics. const analytics = await this.getAnalytics(); const stopPeriodicFlushes = analytics && analytics.periodFlush(); let exitCode: number | void | undefined; try { if (analytics) { this.reportCommandRunAnalytics(analytics); this.reportWorkspaceInfoAnalytics(analytics); } exitCode = await this.run(camelCasedOptions as Options<T> & OtherOptions); } catch (e) { if (e instanceof schema.SchemaValidationException) { this.context.logger.fatal(`Error: ${e.message}`); exitCode = 1; } else { throw e; } } finally { await stopPeriodicFlushes?.(); if (typeof exitCode === 'number' && exitCode > 0) { process.exitCode = exitCode; } } } @memoize protected async getAnalytics(): Promise<AnalyticsCollector | undefined> { if (!this.shouldReportAnalytics) { return undefined; } const userId = await getAnalyticsUserId( this.context, // Don't prompt on `ng update`, 'ng version' or `ng analytics`. ['version', 'update', 'analytics'].includes(this.commandName), ); return userId ? new AnalyticsCollector(this.context, userId) : undefined; } /** * Adds schema options to a command also this keeps track of options that are required for analytics. * **Note:** This method should be called from the command bundler method. */ protected addSchemaOptionsToCommand<T>(localYargs: Argv<T>, options: Option[]): Argv<T> { const optionsWithAnalytics = addSchemaOptionsToCommand( localYargs, options, // This should only be done when `--help` is used otherwise default will override options set in angular.json. /* includeDefaultValues= */ this.context.args.options.help, ); // Record option of analytics. for (const [name, userAnalytics] of optionsWithAnalytics) { this.optionsWithAnalytics.set(name, userAnalytics); } return localYargs; } protected getWorkspaceOrThrow(): AngularWorkspace { const { workspace } = this.context; if (!workspace) { throw new CommandModuleError('A workspace is required for this command.'); } return workspace; } /** * Flush on an interval (if the event loop is waiting). * * @returns a method that when called will terminate the periodic * flush and call flush one last time. */ protected getAnalyticsParameters( options: (Options<T> & OtherOptions) | OtherOptions, ): Partial<Record<EventCustomDimension | EventCustomMetric, string | boolean | number>> { const parameters: Partial< Record<EventCustomDimension | EventCustomMetric, string | boolean | number> > = {}; const validEventCustomDimensionAndMetrics = new Set([ ...Object.values(EventCustomDimension), ...Object.values(EventCustomMetric), ]); for (const [name, ua] of this.optionsWithAnalytics) { const value = options[name]; if ( (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') && validEventCustomDimensionAndMetrics.has(ua as EventCustomDimension | EventCustomMetric) ) { parameters[ua as EventCustomDimension | EventCustomMetric] = value; } } return parameters; } private reportCommandRunAnalytics(analytics: AnalyticsCollector): void { // eslint-disable-next-line @typescript-eslint/no-explicit-any const internalMethods = (yargs as any).getInternalMethods(); // $0 generate component [name] -> generate_component // $0 add <collection> -> add const fullCommand = (internalMethods.getUsageInstance().getUsage()[0][0] as string) .split(' ') .filter((x) => { const code = x.charCodeAt(0); return code >= 97 && code <= 122; }) .join('_'); analytics.reportCommandRunEvent(fullCommand); } private reportWorkspaceInfoAnalytics(analytics: AnalyticsCollector): void { const { workspace } = this.context; if (!workspace) { return; } let applicationProjectsCount = 0; let librariesProjectsCount = 0; for (const project of workspace.projects.values()) { switch (project.extensions['projectType']) { case 'application': applicationProjectsCount++; break; case 'library': librariesProjectsCount++; break; } } analytics.reportWorkspaceInfoEvent({ [EventCustomMetric.AllProjectsCount]: librariesProjectsCount + applicationProjectsCount, [EventCustomMetric.ApplicationProjectsCount]: applicationProjectsCount, [EventCustomMetric.LibraryProjectsCount]: librariesProjectsCount, }); } } /** * Creates an known command module error. * This is used so during executation we can filter between known validation error and real non handled errors. */ export class CommandModuleError extends Error {}
{ "end_byte": 9788, "start_byte": 2637, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular/cli/src/command-builder/command-module.ts" }
angular-cli/packages/angular/cli/src/command-builder/architect-base-command-module.ts_0_8371
/** * @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 { Architect, Target } from '@angular-devkit/architect'; import { NodeModulesBuilderInfo, WorkspaceNodeModulesArchitectHost, } from '@angular-devkit/architect/node'; import { json } from '@angular-devkit/core'; import { existsSync } from 'node:fs'; import { resolve } from 'node:path'; import { isPackageNameSafeForAnalytics } from '../analytics/analytics'; import { EventCustomDimension, EventCustomMetric } from '../analytics/analytics-parameters'; import { assertIsError } from '../utilities/error'; import { askConfirmation, askQuestion } from '../utilities/prompt'; import { isTTY } from '../utilities/tty'; import { CommandModule, CommandModuleError, CommandModuleImplementation, CommandScope, OtherOptions, } from './command-module'; import { Option, parseJsonSchemaToOptions } from './utilities/json-schema'; export interface MissingTargetChoice { name: string; value: string; } export abstract class ArchitectBaseCommandModule<T extends object> extends CommandModule<T> implements CommandModuleImplementation<T> { override scope = CommandScope.In; protected readonly missingTargetChoices: MissingTargetChoice[] | undefined; protected async runSingleTarget(target: Target, options: OtherOptions): Promise<number> { const architectHost = this.getArchitectHost(); let builderName: string; try { builderName = await architectHost.getBuilderNameForTarget(target); } catch (e) { assertIsError(e); return this.onMissingTarget(e.message); } const { logger } = this.context; const run = await this.getArchitect().scheduleTarget(target, options as json.JsonObject, { logger, }); const analytics = isPackageNameSafeForAnalytics(builderName) ? await this.getAnalytics() : undefined; let outputSubscription; if (analytics) { analytics.reportArchitectRunEvent({ [EventCustomDimension.BuilderTarget]: builderName, }); let firstRun = true; outputSubscription = run.output.subscribe(({ stats }) => { const parameters = this.builderStatsToAnalyticsParameters(stats, builderName); if (!parameters) { return; } if (firstRun) { firstRun = false; analytics.reportBuildRunEvent(parameters); } else { analytics.reportRebuildRunEvent(parameters); } }); } try { const { error, success } = await run.lastOutput; if (error) { logger.error(error); } return success ? 0 : 1; } finally { await run.stop(); outputSubscription?.unsubscribe(); } } private builderStatsToAnalyticsParameters( stats: json.JsonValue, builderName: string, ): Partial< | Record<EventCustomDimension & EventCustomMetric, string | number | undefined | boolean> | undefined > { if (!stats || typeof stats !== 'object' || !('durationInMs' in stats)) { return undefined; } const { optimization, allChunksCount, aot, lazyChunksCount, initialChunksCount, durationInMs, changedChunksCount, cssSizeInBytes, jsSizeInBytes, ngComponentCount, } = stats; return { [EventCustomDimension.BuilderTarget]: builderName, [EventCustomDimension.Aot]: aot, [EventCustomDimension.Optimization]: optimization, [EventCustomMetric.AllChunksCount]: allChunksCount, [EventCustomMetric.LazyChunksCount]: lazyChunksCount, [EventCustomMetric.InitialChunksCount]: initialChunksCount, [EventCustomMetric.ChangedChunksCount]: changedChunksCount, [EventCustomMetric.DurationInMs]: durationInMs, [EventCustomMetric.JsSizeInBytes]: jsSizeInBytes, [EventCustomMetric.CssSizeInBytes]: cssSizeInBytes, [EventCustomMetric.NgComponentCount]: ngComponentCount, }; } private _architectHost: WorkspaceNodeModulesArchitectHost | undefined; protected getArchitectHost(): WorkspaceNodeModulesArchitectHost { if (this._architectHost) { return this._architectHost; } const workspace = this.getWorkspaceOrThrow(); return (this._architectHost = new WorkspaceNodeModulesArchitectHost( workspace, workspace.basePath, )); } private _architect: Architect | undefined; protected getArchitect(): Architect { if (this._architect) { return this._architect; } const registry = new json.schema.CoreSchemaRegistry(); registry.addPostTransform(json.schema.transforms.addUndefinedDefaults); registry.useXDeprecatedProvider((msg) => this.context.logger.warn(msg)); const architectHost = this.getArchitectHost(); return (this._architect = new Architect(architectHost, registry)); } protected async getArchitectTargetOptions(target: Target): Promise<Option[]> { const architectHost = this.getArchitectHost(); let builderConf: string; try { builderConf = await architectHost.getBuilderNameForTarget(target); } catch { return []; } let builderDesc: NodeModulesBuilderInfo; try { builderDesc = await architectHost.resolveBuilder(builderConf); } catch (e) { assertIsError(e); if (e.code === 'MODULE_NOT_FOUND') { this.warnOnMissingNodeModules(); throw new CommandModuleError(`Could not find the '${builderConf}' builder's node package.`); } throw e; } return parseJsonSchemaToOptions( new json.schema.CoreSchemaRegistry(), builderDesc.optionSchema as json.JsonObject, true, ); } private warnOnMissingNodeModules(): void { const basePath = this.context.workspace?.basePath; if (!basePath) { return; } // Check if yarn PnP is used. https://yarnpkg.com/advanced/pnpapi#processversionspnp if (process.versions.pnp) { return; } // Check for a `node_modules` directory (npm, yarn non-PnP, etc.) if (existsSync(resolve(basePath, 'node_modules'))) { return; } this.context.logger.warn( `Node packages may not be installed. Try installing with '${this.context.packageManager.name} install'.`, ); } protected getArchitectTarget(): string { return this.commandName; } protected async onMissingTarget(defaultMessage: string): Promise<1> { const { logger } = this.context; const choices = this.missingTargetChoices; if (!choices?.length) { logger.error(defaultMessage); return 1; } const missingTargetMessage = `Cannot find "${this.getArchitectTarget()}" target for the specified project.\n` + `You can add a package that implements these capabilities.\n\n` + `For example:\n` + choices.map(({ name, value }) => ` ${name}: ng add ${value}`).join('\n') + '\n'; if (isTTY()) { // Use prompts to ask the user if they'd like to install a package. logger.warn(missingTargetMessage); const packageToInstall = await this.getMissingTargetPackageToInstall(choices); if (packageToInstall) { // Example run: `ng add @angular-eslint/schematics`. const AddCommandModule = (await import('../commands/add/cli')).default; await new AddCommandModule(this.context).run({ interactive: true, force: false, dryRun: false, defaults: false, collection: packageToInstall, }); } } else { // Non TTY display error message. logger.error(missingTargetMessage); } return 1; } private async getMissingTargetPackageToInstall( choices: MissingTargetChoice[], ): Promise<string | null> { if (choices.length === 1) { // Single choice const { name, value } = choices[0]; if (await askConfirmation(`Would you like to add ${name} now?`, true, false)) { return value; } return null; } // Multiple choice return askQuestion( `Would you like to add a package with "${this.getArchitectTarget()}" capabilities now?`, [ { name: 'No', value: null, }, ...choices, ], 0, null, ); } }
{ "end_byte": 8371, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular/cli/src/command-builder/architect-base-command-module.ts" }
angular-cli/packages/angular/cli/src/command-builder/command-runner.ts_0_5308
/** * @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 { logging } from '@angular-devkit/core'; import yargs from 'yargs'; import { Parser } from 'yargs/helpers'; import { CommandConfig, CommandNames, RootCommands, RootCommandsAliases, } from '../commands/command-config'; import { colors } from '../utilities/color'; import { AngularWorkspace, getWorkspace } from '../utilities/config'; import { assertIsError } from '../utilities/error'; import { PackageManagerUtils } from '../utilities/package-manager'; import { VERSION } from '../utilities/version'; import { CommandContext, CommandModuleError } from './command-module'; import { CommandModuleConstructor, addCommandModuleToYargs, demandCommandFailureMessage, } from './utilities/command'; import { jsonHelpUsage } from './utilities/json-help'; import { normalizeOptionsMiddleware } from './utilities/normalize-options-middleware'; const yargsParser = Parser as unknown as typeof Parser.default; export async function runCommand(args: string[], logger: logging.Logger): Promise<number> { const { $0, _, help = false, jsonHelp = false, getYargsCompletions = false, ...rest } = yargsParser(args, { boolean: ['help', 'json-help', 'get-yargs-completions'], alias: { 'collection': 'c' }, }); // When `getYargsCompletions` is true the scriptName 'ng' at index 0 is not removed. const positional = getYargsCompletions ? _.slice(1) : _; let workspace: AngularWorkspace | undefined; let globalConfiguration: AngularWorkspace; try { [workspace, globalConfiguration] = await Promise.all([ getWorkspace('local'), getWorkspace('global'), ]); } catch (e) { assertIsError(e); logger.fatal(e.message); return 1; } const root = workspace?.basePath ?? process.cwd(); const context: CommandContext = { globalConfiguration, workspace, logger, currentDirectory: process.cwd(), root, packageManager: new PackageManagerUtils({ globalConfiguration, workspace, root }), args: { positional: positional.map((v) => v.toString()), options: { help, jsonHelp, getYargsCompletions, ...rest, }, }, }; let localYargs = yargs(args); for (const CommandModule of await getCommandsToRegister(positional[0])) { localYargs = addCommandModuleToYargs(localYargs, CommandModule, context); } if (jsonHelp) { // eslint-disable-next-line @typescript-eslint/no-explicit-any const usageInstance = (localYargs as any).getInternalMethods().getUsageInstance(); usageInstance.help = () => jsonHelpUsage(); } // Add default command to support version option when no subcommand is specified localYargs.command('*', false, (builder) => builder.version('version', 'Show Angular CLI version.', VERSION.full), ); await localYargs .scriptName('ng') // https://github.com/yargs/yargs/blob/main/docs/advanced.md#customizing-yargs-parser .parserConfiguration({ 'populate--': true, 'unknown-options-as-args': false, 'dot-notation': false, 'boolean-negation': true, 'strip-aliased': true, 'strip-dashed': true, 'camel-case-expansion': false, }) .option('json-help', { describe: 'Show help in JSON format.', implies: ['help'], hidden: true, type: 'boolean', }) .help('help', 'Shows a help message for this command in the console.') // A complete list of strings can be found: https://github.com/yargs/yargs/blob/main/locales/en.json .updateStrings({ 'Commands:': colors.cyan('Commands:'), 'Options:': colors.cyan('Options:'), 'Positionals:': colors.cyan('Arguments:'), 'deprecated': colors.yellow('deprecated'), 'deprecated: %s': colors.yellow('deprecated:') + ' %s', 'Did you mean %s?': 'Unknown command. Did you mean %s?', }) .epilogue('For more information, see https://angular.dev/cli/.\n') .demandCommand(1, demandCommandFailureMessage) .recommendCommands() .middleware(normalizeOptionsMiddleware) .version(false) .showHelpOnFail(false) .strict() .fail((msg, err) => { throw msg ? // Validation failed example: `Unknown argument:` new CommandModuleError(msg) : // Unknown exception, re-throw. err; }) .wrap(yargs.terminalWidth()) .parseAsync(); return process.exitCode ?? 0; } /** * Get the commands that need to be registered. * @returns One or more command factories that needs to be registered. */ async function getCommandsToRegister( commandName: string | number, ): Promise<CommandModuleConstructor[]> { const commands: CommandConfig[] = []; if (commandName in RootCommands) { commands.push(RootCommands[commandName as CommandNames]); } else if (commandName in RootCommandsAliases) { commands.push(RootCommandsAliases[commandName]); } else { // Unknown command, register every possible command. Object.values(RootCommands).forEach((c) => commands.push(c)); } return Promise.all(commands.map((command) => command.factory().then((m) => m.default))); }
{ "end_byte": 5308, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular/cli/src/command-builder/command-runner.ts" }
angular-cli/packages/angular/cli/src/command-builder/utilities/json-schema_spec.ts_0_6394
/** * @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 { json, schema } from '@angular-devkit/core'; import yargs, { positional } from 'yargs'; import { addSchemaOptionsToCommand, parseJsonSchemaToOptions } from './json-schema'; const YError = (() => { try { const y = yargs().strict().fail(false).exitProcess(false).parse(['--forced-failure']); } catch (e) { if (!(e instanceof Error)) { throw new Error('Unexpected non-Error thrown'); } return e.constructor as typeof Error; } throw new Error('Expected parse to fail'); })(); interface ParseFunction { (argv: string[]): unknown; } function withParseForSchema( jsonSchema: json.JsonObject, { interactive = true, includeDefaultValues = true, }: { interactive?: boolean; includeDefaultValues?: boolean } = {}, ): ParseFunction { let actualParse: ParseFunction = () => { throw new Error('Called before init'); }; const parse: ParseFunction = (args) => { return actualParse(args); }; beforeEach(async () => { const registry = new schema.CoreSchemaRegistry(); const options = await parseJsonSchemaToOptions(registry, jsonSchema, interactive); actualParse = async (args: string[]) => { // Create a fresh yargs for each call. The yargs object is stateful and // calling .parse multiple times on the same instance isn't safe. const localYargs = yargs().exitProcess(false).strict().fail(false); addSchemaOptionsToCommand(localYargs, options, includeDefaultValues); // Yargs only exposes the parse errors as proper errors when using the // callback syntax. This unwraps that ugly workaround so tests can just // use simple .toThrow/.toEqual assertions. return localYargs.parseAsync(args); }; }); return parse; } describe('parseJsonSchemaToOptions', () => { describe('without required fields in schema', () => { const parse = withParseForSchema({ 'type': 'object', 'properties': { 'maxSize': { 'type': 'number', }, 'ssr': { 'type': 'string', 'enum': ['always', 'surprise-me', 'never'], }, 'extendable': { 'type': 'object', 'properties': {}, 'additionalProperties': { 'type': 'string', }, }, 'someDefine': { 'type': 'object', 'additionalProperties': { 'type': 'string', }, }, }, }); describe('type=number', () => { it('parses valid option value', async () => { expect(await parse(['--max-size', '42'])).toEqual( jasmine.objectContaining({ 'maxSize': 42, }), ); }); }); describe('type=string, enum', () => { it('parses valid option value', async () => { expect(await parse(['--ssr', 'never'])).toEqual( jasmine.objectContaining({ 'ssr': 'never', }), ); }); it('rejects non-enum values', async () => { await expectAsync(parse(['--ssr', 'yes'])).toBeRejectedWithError( /Argument: ssr, Given: "yes", Choices:/, ); }); }); describe('type=object', () => { it('ignores fields that define specific properties', async () => { await expectAsync(parse(['--extendable', 'a=b'])).toBeRejectedWithError( /Unknown argument: extendable/, ); }); it('rejects invalid values for string maps', async () => { await expectAsync(parse(['--some-define', 'foo'])).toBeRejectedWithError( YError, /Invalid value for argument: some-define, Given: 'foo', Expected key=value pair/, ); await expectAsync(parse(['--some-define', '42'])).toBeRejectedWithError( YError, /Invalid value for argument: some-define, Given: '42', Expected key=value pair/, ); }); it('aggregates an object value', async () => { expect( await parse([ '--some-define', 'A_BOOLEAN=true', '--some-define', 'AN_INTEGER=42', // Ensure we can handle '=' inside of string values. '--some-define=A_STRING="❤️=❤️"', '--some-define', 'AN_UNQUOTED_STRING=❤️=❤️', ]), ).toEqual( jasmine.objectContaining({ 'someDefine': { 'A_BOOLEAN': 'true', 'AN_INTEGER': '42', 'A_STRING': '"❤️=❤️"', 'AN_UNQUOTED_STRING': '❤️=❤️', }, }), ); }); }); }); describe('with required positional argument', () => { it('marks the required argument as required', async () => { const jsonSchema = JSON.parse(` { "$id": "FakeSchema", "title": "Fake Schema", "type": "object", "required": ["a"], "properties": { "b": { "type": "string", "description": "b.", "$default": { "$source": "argv", "index": 1 } }, "a": { "type": "string", "description": "a.", "$default": { "$source": "argv", "index": 0 } }, "optC": { "type": "string", "description": "optC" }, "optA": { "type": "string", "description": "optA" }, "optB": { "type": "string", "description": "optB" } } }`) as json.JsonObject; const registry = new schema.CoreSchemaRegistry(); const options = await parseJsonSchemaToOptions(registry, jsonSchema, /* interactive= */ true); expect(options.find((opt) => opt.name === 'a')).toEqual( jasmine.objectContaining({ name: 'a', positional: 0, required: true, }), ); expect(options.find((opt) => opt.name === 'b')).toEqual( jasmine.objectContaining({ name: 'b', positional: 1, required: false, }), ); }); }); });
{ "end_byte": 6394, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular/cli/src/command-builder/utilities/json-schema_spec.ts" }
angular-cli/packages/angular/cli/src/command-builder/utilities/schematic-engine-host.ts_0_8171
/** * @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 { RuleFactory, SchematicsException, Tree } from '@angular-devkit/schematics'; import { FileSystemCollectionDesc, NodeModulesEngineHost } from '@angular-devkit/schematics/tools'; import { readFileSync } from 'fs'; import { parse as parseJson } from 'jsonc-parser'; import { Module, createRequire } from 'module'; import { dirname, resolve } from 'path'; import { Script } from 'vm'; import { assertIsError } from '../../utilities/error'; /** * Environment variable to control schematic package redirection */ const schematicRedirectVariable = process.env['NG_SCHEMATIC_REDIRECT']?.toLowerCase(); function shouldWrapSchematic(schematicFile: string, schematicEncapsulation: boolean): boolean { // Check environment variable if present switch (schematicRedirectVariable) { case '0': case 'false': case 'off': case 'none': return false; case 'all': return true; } const normalizedSchematicFile = schematicFile.replace(/\\/g, '/'); // Never wrap the internal update schematic when executed directly // It communicates with the update command via `global` // But we still want to redirect schematics located in `@angular/cli/node_modules`. if ( normalizedSchematicFile.includes('node_modules/@angular/cli/') && !normalizedSchematicFile.includes('node_modules/@angular/cli/node_modules/') ) { return false; } // @angular/pwa uses dynamic imports which causes `[1] 2468039 segmentation fault` when wrapped. // We should remove this when make `importModuleDynamically` work. // See: https://nodejs.org/docs/latest-v14.x/api/vm.html if (normalizedSchematicFile.includes('@angular/pwa')) { return false; } // Check for first-party Angular schematic packages // Angular schematics are safe to use in the wrapped VM context if (/\/node_modules\/@(?:angular|schematics|nguniversal)\//.test(normalizedSchematicFile)) { return true; } // Otherwise use the value of the schematic collection's encapsulation option (current default of false) return schematicEncapsulation; } export class SchematicEngineHost extends NodeModulesEngineHost { protected override _resolveReferenceString( refString: string, parentPath: string, collectionDescription?: FileSystemCollectionDesc, ) { const [path, name] = refString.split('#', 2); // Mimic behavior of ExportStringRef class used in default behavior const fullPath = path[0] === '.' ? resolve(parentPath ?? process.cwd(), path) : path; const referenceRequire = createRequire(__filename); const schematicFile = referenceRequire.resolve(fullPath, { paths: [parentPath] }); if (shouldWrapSchematic(schematicFile, !!collectionDescription?.encapsulation)) { const schematicPath = dirname(schematicFile); const moduleCache = new Map<string, unknown>(); const factoryInitializer = wrap( schematicFile, schematicPath, moduleCache, name || 'default', ) as () => RuleFactory<{}>; const factory = factoryInitializer(); if (!factory || typeof factory !== 'function') { return null; } return { ref: factory, path: schematicPath }; } // All other schematics use default behavior return super._resolveReferenceString(refString, parentPath, collectionDescription); } } /** * Minimal shim modules for legacy deep imports of `@schematics/angular` */ const legacyModules: Record<string, unknown> = { '@schematics/angular/utility/config': { getWorkspace(host: Tree) { const path = '/.angular.json'; const data = host.read(path); if (!data) { throw new SchematicsException(`Could not find (${path})`); } return parseJson(data.toString(), [], { allowTrailingComma: true }); }, }, '@schematics/angular/utility/project': { buildDefaultPath(project: { sourceRoot?: string; root: string; projectType: string }): string { const root = project.sourceRoot ? `/${project.sourceRoot}/` : `/${project.root}/src/`; return `${root}${project.projectType === 'application' ? 'app' : 'lib'}`; }, }, }; /** * Wrap a JavaScript file in a VM context to allow specific Angular dependencies to be redirected. * This VM setup is ONLY intended to redirect dependencies. * * @param schematicFile A JavaScript schematic file path that should be wrapped. * @param schematicDirectory A directory that will be used as the location of the JavaScript file. * @param moduleCache A map to use for caching repeat module usage and proper `instanceof` support. * @param exportName An optional name of a specific export to return. Otherwise, return all exports. */ function wrap( schematicFile: string, schematicDirectory: string, moduleCache: Map<string, unknown>, exportName?: string, ): () => unknown { const hostRequire = createRequire(__filename); const schematicRequire = createRequire(schematicFile); const customRequire = function (id: string) { if (legacyModules[id]) { // Provide compatibility modules for older versions of @angular/cdk return legacyModules[id]; } else if (id.startsWith('schematics:')) { // Schematics built-in modules use the `schematics` scheme (similar to the Node.js `node` scheme) const builtinId = id.slice(11); const builtinModule = loadBuiltinModule(builtinId); if (!builtinModule) { throw new Error( `Unknown schematics built-in module '${id}' requested from schematic '${schematicFile}'`, ); } return builtinModule; } else if (id.startsWith('@angular-devkit/') || id.startsWith('@schematics/')) { // Files should not redirect `@angular/core` and instead use the direct // dependency if available. This allows old major version migrations to continue to function // even though the latest major version may have breaking changes in `@angular/core`. if (id.startsWith('@angular-devkit/core')) { try { return schematicRequire(id); } catch (e) { assertIsError(e); if (e.code !== 'MODULE_NOT_FOUND') { throw e; } } } // Resolve from inside the `@angular/cli` project return hostRequire(id); } else if (id.startsWith('.') || id.startsWith('@angular/cdk')) { // Wrap relative files inside the schematic collection // Also wrap `@angular/cdk`, it contains helper utilities that import core schematic packages // Resolve from the original file const modulePath = schematicRequire.resolve(id); // Use cached module if available const cachedModule = moduleCache.get(modulePath); if (cachedModule) { return cachedModule; } // Do not wrap vendored third-party packages or JSON files if ( !/[/\\]node_modules[/\\]@schematics[/\\]angular[/\\]third_party[/\\]/.test(modulePath) && !modulePath.endsWith('.json') ) { // Wrap module and save in cache const wrappedModule = wrap(modulePath, dirname(modulePath), moduleCache)(); moduleCache.set(modulePath, wrappedModule); return wrappedModule; } } // All others are required directly from the original file return schematicRequire(id); }; // Setup a wrapper function to capture the module's exports const schematicCode = readFileSync(schematicFile, 'utf8'); const script = new Script(Module.wrap(schematicCode), { filename: schematicFile, lineOffset: 1, }); const schematicModule = new Module(schematicFile); const moduleFactory = script.runInThisContext(); return () => { moduleFactory( schematicModule.exports, customRequire, schematicModule, schematicFile, schematicDirectory, ); return exportName ? schematicModule.exports[exportName] : schematicModule.exports; }; } function loadBuiltinModule(id: string): unknown { return undefined; }
{ "end_byte": 8171, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular/cli/src/command-builder/utilities/schematic-engine-host.ts" }
angular-cli/packages/angular/cli/src/command-builder/utilities/json-schema.ts_0_7926
/** * @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 { json, strings } from '@angular-devkit/core'; import yargs, { Arguments, Argv, PositionalOptions, Options as YargsOptions } from 'yargs'; /** * An option description. */ export interface Option extends yargs.Options { /** * The name of the option. */ name: string; /** * Whether this option is required or not. */ required?: boolean; /** * Format field of this option. */ format?: string; /** * Whether this option should be hidden from the help output. It will still show up in JSON help. */ hidden?: boolean; /** * If this option can be used as an argument, the position of the argument. Otherwise omitted. */ positional?: number; /** * Whether or not to report this option to the Angular Team, and which custom field to use. * If this is falsey, do not report this option. */ userAnalytics?: string; /** * Type of the values in a key/value pair field. */ itemValueType?: 'string'; } function coerceToStringMap( dashedName: string, value: (string | undefined)[], ): Record<string, string> | Promise<never> { const stringMap: Record<string, string> = {}; for (const pair of value) { // This happens when the flag isn't passed at all. if (pair === undefined) { continue; } const eqIdx = pair.indexOf('='); if (eqIdx === -1) { // TODO: Remove workaround once yargs properly handles thrown errors from coerce. // Right now these sometimes end up as uncaught exceptions instead of proper validation // errors with usage output. return Promise.reject( new Error( `Invalid value for argument: ${dashedName}, Given: '${pair}', Expected key=value pair`, ), ); } const key = pair.slice(0, eqIdx); const value = pair.slice(eqIdx + 1); stringMap[key] = value; } return stringMap; } function isStringMap(node: json.JsonObject): boolean { // Exclude fields with more specific kinds of properties. if (node.properties || node.patternProperties) { return false; } // Restrict to additionalProperties with string values. return ( json.isJsonObject(node.additionalProperties) && !node.additionalProperties.enum && node.additionalProperties.type === 'string' ); } export async function parseJsonSchemaToOptions( registry: json.schema.SchemaRegistry, schema: json.JsonObject, interactive = true, ): Promise<Option[]> { const options: Option[] = []; function visitor( current: json.JsonObject | json.JsonArray, pointer: json.schema.JsonPointer, parentSchema?: json.JsonObject | json.JsonArray, ) { if (!parentSchema) { // Ignore root. return; } else if (pointer.split(/\/(?:properties|items|definitions)\//g).length > 2) { // Ignore subitems (objects or arrays). return; } else if (json.isJsonArray(current)) { return; } if (pointer.indexOf('/not/') != -1) { // We don't support anyOf/not. throw new Error('The "not" keyword is not supported in JSON Schema.'); } const ptr = json.schema.parseJsonPointer(pointer); const name = ptr[ptr.length - 1]; if (ptr[ptr.length - 2] != 'properties') { // Skip any non-property items. return; } const typeSet = json.schema.getTypesOfSchema(current); if (typeSet.size == 0) { throw new Error('Cannot find type of schema.'); } // We only support number, string or boolean (or array of those), so remove everything else. const types = [...typeSet].filter((x) => { switch (x) { case 'boolean': case 'number': case 'string': return true; case 'array': // Only include arrays if they're boolean, string or number. if ( json.isJsonObject(current.items) && typeof current.items.type == 'string' && ['boolean', 'number', 'string'].includes(current.items.type) ) { return true; } return false; case 'object': return isStringMap(current); default: return false; } }) as ('string' | 'number' | 'boolean' | 'array' | 'object')[]; if (types.length == 0) { // This means it's not usable on the command line. e.g. an Object. return; } // Only keep enum values we support (booleans, numbers and strings). const enumValues = ((json.isJsonArray(current.enum) && current.enum) || []).filter((x) => { switch (typeof x) { case 'boolean': case 'number': case 'string': return true; default: return false; } }) as (string | true | number)[]; let defaultValue: string | number | boolean | undefined = undefined; if (current.default !== undefined) { switch (types[0]) { case 'string': if (typeof current.default == 'string') { defaultValue = current.default; } break; case 'number': if (typeof current.default == 'number') { defaultValue = current.default; } break; case 'boolean': if (typeof current.default == 'boolean') { defaultValue = current.default; } break; } } const $default = current.$default; const $defaultIndex = json.isJsonObject($default) && $default['$source'] == 'argv' ? $default['index'] : undefined; const positional: number | undefined = typeof $defaultIndex == 'number' ? $defaultIndex : undefined; let required = json.isJsonArray(schema.required) ? schema.required.includes(name) : false; if (required && interactive && current['x-prompt']) { required = false; } const alias = json.isJsonArray(current.aliases) ? [...current.aliases].map((x) => '' + x) : current.alias ? ['' + current.alias] : []; const format = typeof current.format == 'string' ? current.format : undefined; const visible = current.visible === undefined || current.visible === true; const hidden = !!current.hidden || !visible; const xUserAnalytics = current['x-user-analytics']; const userAnalytics = typeof xUserAnalytics === 'string' ? xUserAnalytics : undefined; // Deprecated is set only if it's true or a string. const xDeprecated = current['x-deprecated']; const deprecated = xDeprecated === true || typeof xDeprecated === 'string' ? xDeprecated : undefined; const option: Option = { name, description: '' + (current.description === undefined ? '' : current.description), default: defaultValue, choices: enumValues.length ? enumValues : undefined, required, alias, format, hidden, userAnalytics, deprecated, positional, ...(types[0] === 'object' ? { type: 'array', itemValueType: 'string', } : { type: types[0], }), }; options.push(option); } const flattenedSchema = await registry.ɵflatten(schema); json.schema.visitJsonSchema(flattenedSchema, visitor); // Sort by positional and name. return options.sort((a, b) => { if (a.positional) { return b.positional ? a.positional - b.positional : a.name.localeCompare(b.name); } else if (b.positional) { return -1; } return a.name.localeCompare(b.name); }); } /** * Adds schema options to a command also this keeps track of options that are required for analytics. * **Note:** This method should be called from the command bundler method. * * @returns A map from option name to analytics configuration. */
{ "end_byte": 7926, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular/cli/src/command-builder/utilities/json-schema.ts" }
angular-cli/packages/angular/cli/src/command-builder/utilities/json-schema.ts_7927_10189
xport function addSchemaOptionsToCommand<T>( localYargs: Argv<T>, options: Option[], includeDefaultValues: boolean, ): Map<string, string> { const booleanOptionsWithNoPrefix = new Set<string>(); const keyValuePairOptions = new Set<string>(); const optionsWithAnalytics = new Map<string, string>(); for (const option of options) { const { default: defaultVal, positional, deprecated, description, alias, userAnalytics, type, itemValueType, hidden, name, choices, } = option; let dashedName = strings.dasherize(name); // Handle options which have been defined in the schema with `no` prefix. if (type === 'boolean' && dashedName.startsWith('no-')) { dashedName = dashedName.slice(3); booleanOptionsWithNoPrefix.add(dashedName); } if (itemValueType) { keyValuePairOptions.add(name); } const sharedOptions: YargsOptions & PositionalOptions = { alias, hidden, description, deprecated, choices, coerce: itemValueType ? coerceToStringMap.bind(null, dashedName) : undefined, // This should only be done when `--help` is used otherwise default will override options set in angular.json. ...(includeDefaultValues ? { default: defaultVal } : {}), }; if (positional === undefined) { localYargs = localYargs.option(dashedName, { array: itemValueType ? true : undefined, type: itemValueType ?? type, ...sharedOptions, }); } else { localYargs = localYargs.positional(dashedName, { type: type === 'array' || type === 'count' ? 'string' : type, ...sharedOptions, }); } // Record option of analytics. if (userAnalytics !== undefined) { optionsWithAnalytics.set(name, userAnalytics); } } // Handle options which have been defined in the schema with `no` prefix. if (booleanOptionsWithNoPrefix.size) { localYargs.middleware((options: Arguments) => { for (const key of booleanOptionsWithNoPrefix) { if (key in options) { options[`no-${key}`] = !options[key]; delete options[key]; } } }, false); } return optionsWithAnalytics; }
{ "end_byte": 10189, "start_byte": 7927, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular/cli/src/command-builder/utilities/json-schema.ts" }
angular-cli/packages/angular/cli/src/command-builder/utilities/schematic-workflow.ts_0_2231
/** * @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 { logging } from '@angular-devkit/core'; import { NodeWorkflow } from '@angular-devkit/schematics/tools'; import { colors } from '../../utilities/color'; function removeLeadingSlash(value: string): string { return value[0] === '/' ? value.slice(1) : value; } export function subscribeToWorkflow( workflow: NodeWorkflow, logger: logging.LoggerApi, ): { files: Set<string>; error: boolean; unsubscribe: () => void; } { const files = new Set<string>(); let error = false; let logs: string[] = []; const reporterSubscription = workflow.reporter.subscribe((event) => { // Strip leading slash to prevent confusion. const eventPath = removeLeadingSlash(event.path); switch (event.kind) { case 'error': error = true; logger.error( `ERROR! ${eventPath} ${event.description == 'alreadyExist' ? 'already exists' : 'does not exist'}.`, ); break; case 'update': logs.push(`${colors.cyan('UPDATE')} ${eventPath} (${event.content.length} bytes)`); files.add(eventPath); break; case 'create': logs.push(`${colors.green('CREATE')} ${eventPath} (${event.content.length} bytes)`); files.add(eventPath); break; case 'delete': logs.push(`${colors.yellow('DELETE')} ${eventPath}`); files.add(eventPath); break; case 'rename': logs.push(`${colors.blue('RENAME')} ${eventPath} => ${removeLeadingSlash(event.to)}`); files.add(eventPath); break; } }); const lifecycleSubscription = workflow.lifeCycle.subscribe((event) => { if (event.kind == 'end' || event.kind == 'post-tasks-start') { if (!error) { // Output the logging queue, no error happened. logs.forEach((log) => logger.info(log)); } logs = []; error = false; } }); return { files, error, unsubscribe: () => { reporterSubscription.unsubscribe(); lifecycleSubscription.unsubscribe(); }, }; }
{ "end_byte": 2231, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular/cli/src/command-builder/utilities/schematic-workflow.ts" }
angular-cli/packages/angular/cli/src/command-builder/utilities/normalize-options-middleware.ts_0_1474
/** * @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 * as yargs from 'yargs'; /** * A Yargs middleware that normalizes non Array options when the argument has been provided multiple times. * * By default, when an option is non array and it is provided multiple times in the command line, yargs * will not override it's value but instead it will be changed to an array unless `duplicate-arguments-array` is disabled. * But this option also have an effect on real array options which isn't desired. * * See: https://github.com/yargs/yargs-parser/pull/163#issuecomment-516566614 */ export function normalizeOptionsMiddleware(args: yargs.Arguments): void { // `getOptions` is not included in the types even though it's public API. // https://github.com/yargs/yargs/issues/2098 // eslint-disable-next-line @typescript-eslint/no-explicit-any const { array } = (yargs as any).getOptions(); const arrayOptions = new Set(array); for (const [key, value] of Object.entries(args)) { if (key !== '_' && Array.isArray(value) && !arrayOptions.has(key)) { const newValue = value.pop(); // eslint-disable-next-line no-console console.warn( `Option '${key}' has been specified multiple times. The value '${newValue}' will be used.`, ); args[key] = newValue; } } }
{ "end_byte": 1474, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular/cli/src/command-builder/utilities/normalize-options-middleware.ts" }
angular-cli/packages/angular/cli/src/command-builder/utilities/json-help.ts_0_4438
/** * @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 yargs from 'yargs'; import { FullDescribe } from '../command-module'; interface JsonHelpOption { name: string; type?: string; deprecated: boolean | string; aliases?: string[]; default?: string; required?: boolean; positional?: number; enum?: string[]; description?: string; } interface JsonHelpDescription { shortDescription?: string; longDescription?: string; longDescriptionRelativePath?: string; } interface JsonHelpSubcommand extends JsonHelpDescription { name: string; aliases: string[]; deprecated: string | boolean; } export interface JsonHelp extends JsonHelpDescription { name: string; command: string; options: JsonHelpOption[]; subcommands?: JsonHelpSubcommand[]; } const yargsDefaultCommandRegExp = /^\$0|\*/; export function jsonHelpUsage(): string { // eslint-disable-next-line @typescript-eslint/no-explicit-any const localYargs = yargs as any; const { deprecatedOptions, alias: aliases, array, string, boolean, number, choices, demandedOptions, default: defaultVal, hiddenOptions = [], } = localYargs.getOptions(); const internalMethods = localYargs.getInternalMethods(); const usageInstance = internalMethods.getUsageInstance(); const context = internalMethods.getContext(); const descriptions = usageInstance.getDescriptions(); const groups = localYargs.getGroups(); const positional = groups[usageInstance.getPositionalGroupName()] as string[] | undefined; const hidden = new Set(hiddenOptions); const normalizeOptions: JsonHelpOption[] = []; const allAliases = new Set([...Object.values<string[]>(aliases).flat()]); for (const [names, type] of [ [array, 'array'], [string, 'string'], [boolean, 'boolean'], [number, 'number'], ]) { for (const name of names) { if (allAliases.has(name) || hidden.has(name)) { // Ignore hidden, aliases and already visited option. continue; } const positionalIndex = positional?.indexOf(name) ?? -1; const alias = aliases[name]; normalizeOptions.push({ name, type, deprecated: deprecatedOptions[name], aliases: alias?.length > 0 ? alias : undefined, default: defaultVal[name], required: demandedOptions[name], enum: choices[name], description: descriptions[name]?.replace('__yargsString__:', ''), positional: positionalIndex >= 0 ? positionalIndex : undefined, }); } } // https://github.com/yargs/yargs/blob/00e4ebbe3acd438e73fdb101e75b4f879eb6d345/lib/usage.ts#L124 const subcommands = ( usageInstance.getCommands() as [ name: string, description: string, isDefault: boolean, aliases: string[], deprecated: string | boolean, ][] ) .map(([name, rawDescription, isDefault, aliases, deprecated]) => ({ name: name.split(' ', 1)[0].replace(yargsDefaultCommandRegExp, ''), command: name.replace(yargsDefaultCommandRegExp, ''), default: isDefault || undefined, ...parseDescription(rawDescription), aliases, deprecated, })) .sort((a, b) => a.name.localeCompare(b.name)); const [command, rawDescription] = usageInstance.getUsage()[0] ?? []; const defaultSubCommand = subcommands.find((x) => x.default)?.command ?? ''; const otherSubcommands = subcommands.filter((s) => !s.default); const output: JsonHelp = { name: [...context.commands].pop(), command: `${command?.replace(yargsDefaultCommandRegExp, localYargs['$0'])}${defaultSubCommand}`, ...parseDescription(rawDescription), options: normalizeOptions.sort((a, b) => a.name.localeCompare(b.name)), subcommands: otherSubcommands.length ? otherSubcommands : undefined, }; return JSON.stringify(output, undefined, 2); } function parseDescription(rawDescription: string): JsonHelpDescription { try { const { longDescription, describe: shortDescription, longDescriptionRelativePath, } = JSON.parse(rawDescription) as FullDescribe; return { shortDescription, longDescriptionRelativePath, longDescription, }; } catch { return { shortDescription: rawDescription, }; } }
{ "end_byte": 4438, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular/cli/src/command-builder/utilities/json-help.ts" }
angular-cli/packages/angular/cli/src/command-builder/utilities/command.ts_0_2147
/** * @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 { Argv } from 'yargs'; import { CommandContext, CommandModule, CommandModuleError, CommandModuleImplementation, CommandScope, } from '../command-module'; export const demandCommandFailureMessage = `You need to specify a command before moving on. Use '--help' to view the available commands.`; export type CommandModuleConstructor = Partial<CommandModuleImplementation> & { new (context: CommandContext): Partial<CommandModuleImplementation> & CommandModule; }; export function addCommandModuleToYargs<T extends object, U extends CommandModuleConstructor>( localYargs: Argv<T>, commandModule: U, context: CommandContext, ): Argv<T> { const cmd = new commandModule(context); const { args: { options: { jsonHelp }, }, workspace, } = context; const describe = jsonHelp ? cmd.fullDescribe : cmd.describe; return localYargs.command({ command: cmd.command, aliases: cmd.aliases, describe: // We cannot add custom fields in help, such as long command description which is used in AIO. // Therefore, we get around this by adding a complex object as a string which we later parse when generating the help files. typeof describe === 'object' ? JSON.stringify(describe) : describe, deprecated: cmd.deprecated, builder: (argv) => { // Skip scope validation when running with '--json-help' since it's easier to generate the output for all commands this way. const isInvalidScope = !jsonHelp && ((cmd.scope === CommandScope.In && !workspace) || (cmd.scope === CommandScope.Out && workspace)); if (isInvalidScope) { throw new CommandModuleError( `This command is not available when running the Angular CLI ${ workspace ? 'inside' : 'outside' } a workspace.`, ); } return cmd.builder(argv) as Argv<T>; }, handler: (args) => cmd.handler(args), }); }
{ "end_byte": 2147, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular/cli/src/command-builder/utilities/command.ts" }
angular-cli/packages/angular/cli/src/commands/command-config.ts_0_2319
/** * @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 { CommandModuleConstructor } from '../command-builder/utilities/command'; export type CommandNames = | 'add' | 'analytics' | 'build' | 'cache' | 'completion' | 'config' | 'deploy' | 'e2e' | 'extract-i18n' | 'generate' | 'lint' | 'make-this-awesome' | 'new' | 'run' | 'serve' | 'test' | 'update' | 'version'; export interface CommandConfig { aliases?: string[]; factory: () => Promise<{ default: CommandModuleConstructor }>; } export const RootCommands: Record< /* Command */ CommandNames & string, /* Command Config */ CommandConfig > = { 'add': { factory: () => import('./add/cli'), }, 'analytics': { factory: () => import('./analytics/cli'), }, 'build': { factory: () => import('./build/cli'), aliases: ['b'], }, 'cache': { factory: () => import('./cache/cli'), }, 'completion': { factory: () => import('./completion/cli'), }, 'config': { factory: () => import('./config/cli'), }, 'deploy': { factory: () => import('./deploy/cli'), }, 'e2e': { factory: () => import('./e2e/cli'), aliases: ['e'], }, 'extract-i18n': { factory: () => import('./extract-i18n/cli'), }, 'generate': { factory: () => import('./generate/cli'), aliases: ['g'], }, 'lint': { factory: () => import('./lint/cli'), }, 'make-this-awesome': { factory: () => import('./make-this-awesome/cli'), }, 'new': { factory: () => import('./new/cli'), aliases: ['n'], }, 'run': { factory: () => import('./run/cli'), }, 'serve': { factory: () => import('./serve/cli'), aliases: ['dev', 's'], }, 'test': { factory: () => import('./test/cli'), aliases: ['t'], }, 'update': { factory: () => import('./update/cli'), }, 'version': { factory: () => import('./version/cli'), aliases: ['v'], }, }; export const RootCommandsAliases = Object.values(RootCommands).reduce( (prev, current) => { current.aliases?.forEach((alias) => { prev[alias] = current; }); return prev; }, {} as Record<string, CommandConfig>, );
{ "end_byte": 2319, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular/cli/src/commands/command-config.ts" }
angular-cli/packages/angular/cli/src/commands/lint/cli.ts_0_964
/** * @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 { join } from 'path'; import { MissingTargetChoice } from '../../command-builder/architect-base-command-module'; import { ArchitectCommandModule } from '../../command-builder/architect-command-module'; import { CommandModuleImplementation } from '../../command-builder/command-module'; export default class LintCommandModule extends ArchitectCommandModule implements CommandModuleImplementation { override missingTargetChoices: MissingTargetChoice[] = [ { name: 'ESLint', value: '@angular-eslint/schematics', }, ]; multiTarget = true; command = 'lint [project]'; longDescriptionPath = join(__dirname, 'long-description.md'); describe = 'Runs linting tools on Angular application code in a given project folder.'; }
{ "end_byte": 964, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular/cli/src/commands/lint/cli.ts" }
angular-cli/packages/angular/cli/src/commands/lint/long-description.md_0_644
The command takes an optional project name, as specified in the `projects` section of the `angular.json` workspace configuration file. When a project name is not supplied, executes the `lint` builder for all projects. To use the `ng lint` command, use `ng add` to add a package that implements linting capabilities. Adding the package automatically updates your workspace configuration, adding a lint [CLI builder](tools/cli/cli-builder). For example: ```json "projects": { "my-project": { ... "architect": { ... "lint": { "builder": "@angular-eslint/builder:lint", "options": {} } } } } ```
{ "end_byte": 644, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular/cli/src/commands/lint/long-description.md" }
angular-cli/packages/angular/cli/src/commands/cache/utilities.ts_0_1699
/** * @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 { isJsonObject } from '@angular-devkit/core'; import { resolve } from 'path'; import { Cache, Environment } from '../../../lib/config/workspace-schema'; import { AngularWorkspace } from '../../utilities/config'; export function updateCacheConfig<K extends keyof Cache>( workspace: AngularWorkspace, key: K, value: Cache[K], ): Promise<void> { const cli = (workspace.extensions['cli'] ??= {}) as Record<string, Record<string, unknown>>; const cache = (cli['cache'] ??= {}); cache[key] = value; return workspace.save(); } export function getCacheConfig(workspace: AngularWorkspace | undefined): Required<Cache> { if (!workspace) { throw new Error(`Cannot retrieve cache configuration as workspace is not defined.`); } const defaultSettings: Required<Cache> = { path: resolve(workspace.basePath, '.angular/cache'), environment: Environment.Local, enabled: true, }; const cliSetting = workspace.extensions['cli']; if (!cliSetting || !isJsonObject(cliSetting)) { return defaultSettings; } const cacheSettings = cliSetting['cache']; if (!isJsonObject(cacheSettings)) { return defaultSettings; } const { path = defaultSettings.path, environment = defaultSettings.environment, enabled = defaultSettings.enabled, // eslint-disable-next-line @typescript-eslint/no-explicit-any } = cacheSettings as Record<string, any>; return { path: resolve(workspace.basePath, path), environment, enabled, }; }
{ "end_byte": 1699, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular/cli/src/commands/cache/utilities.ts" }
angular-cli/packages/angular/cli/src/commands/cache/cli.ts_0_1423
/** * @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 { join } from 'path'; import { Argv } from 'yargs'; import { CommandModule, CommandModuleImplementation, CommandScope, Options, } from '../../command-builder/command-module'; import { addCommandModuleToYargs, demandCommandFailureMessage, } from '../../command-builder/utilities/command'; import { CacheCleanModule } from './clean/cli'; import { CacheInfoCommandModule } from './info/cli'; import { CacheDisableModule, CacheEnableModule } from './settings/cli'; export default class CacheCommandModule extends CommandModule implements CommandModuleImplementation { command = 'cache'; describe = 'Configure persistent disk cache and retrieve cache statistics.'; longDescriptionPath = join(__dirname, 'long-description.md'); override scope = CommandScope.In; builder(localYargs: Argv): Argv { const subcommands = [ CacheEnableModule, CacheDisableModule, CacheCleanModule, CacheInfoCommandModule, ].sort(); for (const module of subcommands) { localYargs = addCommandModuleToYargs(localYargs, module, this.context); } return localYargs.demandCommand(1, demandCommandFailureMessage).strict(); } run(_options: Options<{}>): void {} }
{ "end_byte": 1423, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular/cli/src/commands/cache/cli.ts" }
angular-cli/packages/angular/cli/src/commands/cache/long-description.md_0_1722
Angular CLI saves a number of cachable operations on disk by default. 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. To amend the default cache settings, add the `cli.cache` object to your [Workspace Configuration](reference/configs/workspace-config). The object goes under `cli.cache` at the top level of the file, outside the `projects` sections. ```jsonc { "$schema": "./node_modules/@angular/cli/lib/config/schema.json", "version": 1, "cli": { "cache": { // ... }, }, "projects": {}, } ``` For more information, see [cache options](reference/configs/workspace-config#cache-options). ### Cache environments By default, disk cache is only enabled for local environments. The value of environment can be one of the following: - `all` - allows disk cache on all machines. - `local` - allows disk cache only on development machines. - `ci` - allows disk cache only on continuous integration (CI) systems. To change the environment setting to `all`, run the following command: ```bash ng config cli.cache.environment all ``` For more information, see `environment` in [cache options](reference/configs/workspace-config#cache-options). <div class="alert is-helpful"> The Angular CLI checks for the presence and value of the `CI` environment variable to determine in which environment it is running. </div> ### Cache path By default, `.angular/cache` is used as a base directory to store cache results. To change this path to `.cache/ng`, run the following command: ```bash ng config cli.cache.path ".cache/ng" ```
{ "end_byte": 1722, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular/cli/src/commands/cache/long-description.md" }
angular-cli/packages/angular/cli/src/commands/cache/settings/cli.ts_0_1333
/** * @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 { Argv } from 'yargs'; import { CommandModule, CommandModuleImplementation, CommandScope, } from '../../../command-builder/command-module'; import { updateCacheConfig } from '../utilities'; export class CacheDisableModule extends CommandModule implements CommandModuleImplementation { command = 'disable'; aliases = 'off'; describe = 'Disables persistent disk cache for all projects in the workspace.'; longDescriptionPath: string | undefined; override scope = CommandScope.In; builder(localYargs: Argv): Argv { return localYargs; } run(): Promise<void> { return updateCacheConfig(this.getWorkspaceOrThrow(), 'enabled', false); } } export class CacheEnableModule extends CommandModule implements CommandModuleImplementation { command = 'enable'; aliases = 'on'; describe = 'Enables disk cache for all projects in the workspace.'; longDescriptionPath: string | undefined; override scope = CommandScope.In; builder(localYargs: Argv): Argv { return localYargs; } run(): Promise<void> { return updateCacheConfig(this.getWorkspaceOrThrow(), 'enabled', true); } }
{ "end_byte": 1333, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular/cli/src/commands/cache/settings/cli.ts" }
angular-cli/packages/angular/cli/src/commands/cache/info/cli.ts_0_2809
/** * @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 { tags } from '@angular-devkit/core'; import { promises as fs } from 'fs'; import { join } from 'path'; import { Argv } from 'yargs'; import { CommandModule, CommandModuleImplementation, CommandScope, } from '../../../command-builder/command-module'; import { isCI } from '../../../utilities/environment-options'; import { getCacheConfig } from '../utilities'; export class CacheInfoCommandModule extends CommandModule implements CommandModuleImplementation { command = 'info'; describe = 'Prints persistent disk cache configuration and statistics in the console.'; longDescriptionPath?: string | undefined; override scope = CommandScope.In; builder(localYargs: Argv): Argv { return localYargs.strict(); } async run(): Promise<void> { const { path, environment, enabled } = getCacheConfig(this.context.workspace); this.context.logger.info(tags.stripIndents` Enabled: ${enabled ? 'yes' : 'no'} Environment: ${environment} Path: ${path} Size on disk: ${await this.getSizeOfDirectory(path)} Effective status on current machine: ${this.effectiveEnabledStatus() ? 'enabled' : 'disabled'} `); } private async getSizeOfDirectory(path: string): Promise<string> { const directoriesStack = [path]; let size = 0; while (directoriesStack.length) { // eslint-disable-next-line @typescript-eslint/no-non-null-assertion const dirPath = directoriesStack.pop()!; let entries: string[] = []; try { entries = await fs.readdir(dirPath); } catch {} for (const entry of entries) { const entryPath = join(dirPath, entry); const stats = await fs.stat(entryPath); if (stats.isDirectory()) { directoriesStack.push(entryPath); } size += stats.size; } } return this.formatSize(size); } private formatSize(size: number): string { if (size <= 0) { return '0 bytes'; } const abbreviations = ['bytes', 'kB', 'MB', 'GB']; const index = Math.floor(Math.log(size) / Math.log(1024)); const roundedSize = size / Math.pow(1024, index); // bytes don't have a fraction const fractionDigits = index === 0 ? 0 : 2; return `${roundedSize.toFixed(fractionDigits)} ${abbreviations[index]}`; } private effectiveEnabledStatus(): boolean { const { enabled, environment } = getCacheConfig(this.context.workspace); if (enabled) { switch (environment) { case 'ci': return isCI; case 'local': return !isCI; } } return enabled; } }
{ "end_byte": 2809, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular/cli/src/commands/cache/info/cli.ts" }
angular-cli/packages/angular/cli/src/commands/cache/clean/cli.ts_0_955
/** * @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 { promises as fs } from 'fs'; import { Argv } from 'yargs'; import { CommandModule, CommandModuleImplementation, CommandScope, } from '../../../command-builder/command-module'; import { getCacheConfig } from '../utilities'; export class CacheCleanModule extends CommandModule implements CommandModuleImplementation { command = 'clean'; describe = 'Deletes persistent disk cache from disk.'; longDescriptionPath: string | undefined; override scope = CommandScope.In; builder(localYargs: Argv): Argv { return localYargs.strict(); } run(): Promise<void> { const { path } = getCacheConfig(this.context.workspace); return fs.rm(path, { force: true, recursive: true, maxRetries: 3, }); } }
{ "end_byte": 955, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular/cli/src/commands/cache/clean/cli.ts" }
angular-cli/packages/angular/cli/src/commands/test/cli.ts_0_778
/** * @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 { join } from 'path'; import { ArchitectCommandModule } from '../../command-builder/architect-command-module'; import { CommandModuleImplementation } from '../../command-builder/command-module'; import { RootCommands } from '../command-config'; export default class TestCommandModule extends ArchitectCommandModule implements CommandModuleImplementation { multiTarget = true; command = 'test [project]'; aliases = RootCommands['test'].aliases; describe = 'Runs unit tests in a project.'; longDescriptionPath = join(__dirname, 'long-description.md'); }
{ "end_byte": 778, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular/cli/src/commands/test/cli.ts" }
angular-cli/packages/angular/cli/src/commands/test/long-description.md_0_193
Takes the name of the project, as specified in the `projects` section of the `angular.json` workspace configuration file. When a project name is not supplied, it will execute for all projects.
{ "end_byte": 193, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular/cli/src/commands/test/long-description.md" }
angular-cli/packages/angular/cli/src/commands/update/cli.ts_0_2658
/** * @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 { SchematicDescription, UnsuccessfulWorkflowExecution } from '@angular-devkit/schematics'; import { FileSystemCollectionDescription, FileSystemSchematicDescription, NodeWorkflow, } from '@angular-devkit/schematics/tools'; import { Listr } from 'listr2'; import { SpawnSyncReturns, execSync, spawnSync } from 'node:child_process'; import { existsSync, promises as fs } from 'node:fs'; import { createRequire } from 'node:module'; import npa from 'npm-package-arg'; import pickManifest from 'npm-pick-manifest'; import * as path from 'path'; import { join, resolve } from 'path'; import * as semver from 'semver'; import { Argv } from 'yargs'; import { PackageManager } from '../../../lib/config/workspace-schema'; import { CommandModule, CommandModuleError, CommandScope, Options, } from '../../command-builder/command-module'; import { SchematicEngineHost } from '../../command-builder/utilities/schematic-engine-host'; import { subscribeToWorkflow } from '../../command-builder/utilities/schematic-workflow'; import { colors, figures } from '../../utilities/color'; import { disableVersionCheck } from '../../utilities/environment-options'; import { assertIsError } from '../../utilities/error'; import { writeErrorToLogFile } from '../../utilities/log-file'; import { PackageIdentifier, PackageManifest, fetchPackageManifest, fetchPackageMetadata, } from '../../utilities/package-metadata'; import { PackageTreeNode, findPackageJson, getProjectDependencies, readPackageJson, } from '../../utilities/package-tree'; import { askChoices } from '../../utilities/prompt'; import { isTTY } from '../../utilities/tty'; import { VERSION } from '../../utilities/version'; interface UpdateCommandArgs { packages?: string[]; force: boolean; next: boolean; 'migrate-only'?: boolean; name?: string; from?: string; to?: string; 'allow-dirty': boolean; verbose: boolean; 'create-commits': boolean; } interface MigrationSchematicDescription extends SchematicDescription<FileSystemCollectionDescription, FileSystemSchematicDescription> { version?: string; optional?: boolean; documentation?: string; } interface MigrationSchematicDescriptionWithVersion extends MigrationSchematicDescription { version: string; } class CommandError extends Error {} const ANGULAR_PACKAGES_REGEXP = /^@(?:angular|nguniversal)\//; const UPDATE_SCHEMATIC_COLLECTION = path.join(__dirname, 'schematic/collection.json');
{ "end_byte": 2658, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular/cli/src/commands/update/cli.ts" }
angular-cli/packages/angular/cli/src/commands/update/cli.ts_2660_11854
export default class UpdateCommandModule extends CommandModule<UpdateCommandArgs> { override scope = CommandScope.In; protected override shouldReportAnalytics = false; private readonly resolvePaths = [__dirname, this.context.root]; command = 'update [packages..]'; describe = 'Updates your workspace and its dependencies. See https://update.angular.dev/.'; longDescriptionPath = join(__dirname, 'long-description.md'); builder(localYargs: Argv): Argv<UpdateCommandArgs> { return localYargs .positional('packages', { description: 'The names of package(s) to update.', type: 'string', array: true, }) .option('force', { description: 'Ignore peer dependency version mismatches.', type: 'boolean', default: false, }) .option('next', { description: 'Use the prerelease version, including beta and RCs.', type: 'boolean', default: false, }) .option('migrate-only', { description: 'Only perform a migration, do not update the installed version.', type: 'boolean', }) .option('name', { description: 'The name of the migration to run. Only available when a single package is updated.', type: 'string', conflicts: ['to', 'from'], }) .option('from', { description: 'Version from which to migrate from. ' + `Only available when a single package is updated, and only with 'migrate-only'.`, type: 'string', implies: ['migrate-only'], conflicts: ['name'], }) .option('to', { describe: 'Version up to which to apply migrations. Only available when a single package is updated, ' + `and only with 'migrate-only' option. Requires 'from' to be specified. Default to the installed version detected.`, type: 'string', implies: ['from', 'migrate-only'], conflicts: ['name'], }) .option('allow-dirty', { describe: 'Whether to allow updating when the repository contains modified or untracked files.', type: 'boolean', default: false, }) .option('verbose', { describe: 'Display additional details about internal operations during execution.', type: 'boolean', default: false, }) .option('create-commits', { describe: 'Create source control commits for updates and migrations.', type: 'boolean', alias: ['C'], default: false, }) .middleware((argv) => { if (argv.name) { argv['migrate-only'] = true; } // eslint-disable-next-line @typescript-eslint/no-explicit-any return argv as any; }) .check(({ packages, 'allow-dirty': allowDirty, 'migrate-only': migrateOnly }) => { const { logger } = this.context; // This allows the user to easily reset any changes from the update. if (packages?.length && !this.checkCleanGit()) { if (allowDirty) { logger.warn( 'Repository is not clean. Update changes will be mixed with pre-existing changes.', ); } else { throw new CommandModuleError( 'Repository is not clean. Please commit or stash any changes before updating.', ); } } if (migrateOnly) { if (packages?.length !== 1) { throw new CommandModuleError( `A single package must be specified when using the 'migrate-only' option.`, ); } } return true; }) .strict(); } async run(options: Options<UpdateCommandArgs>): Promise<number | void> { const { logger, packageManager } = this.context; // Check if the current installed CLI version is older than the latest compatible version. // Skip when running `ng update` without a package name as this will not trigger an actual update. if (!disableVersionCheck && options.packages?.length) { const cliVersionToInstall = await this.checkCLIVersion( options.packages, options.verbose, options.next, ); if (cliVersionToInstall) { logger.warn( 'The installed Angular CLI version is outdated.\n' + `Installing a temporary Angular CLI versioned ${cliVersionToInstall} to perform the update.`, ); return this.runTempBinary(`@angular/cli@${cliVersionToInstall}`, process.argv.slice(2)); } } const packages: PackageIdentifier[] = []; for (const request of options.packages ?? []) { try { const packageIdentifier = npa(request); // only registry identifiers are supported if (!packageIdentifier.registry) { logger.error(`Package '${request}' is not a registry package identifer.`); return 1; } if (packages.some((v) => v.name === packageIdentifier.name)) { logger.error(`Duplicate package '${packageIdentifier.name}' specified.`); return 1; } if (options.migrateOnly && packageIdentifier.rawSpec !== '*') { logger.warn('Package specifier has no effect when using "migrate-only" option.'); } // If next option is used and no specifier supplied, use next tag if (options.next && packageIdentifier.rawSpec === '*') { packageIdentifier.fetchSpec = 'next'; } packages.push(packageIdentifier as PackageIdentifier); } catch (e) { assertIsError(e); logger.error(e.message); return 1; } } logger.info(`Using package manager: ${colors.gray(packageManager.name)}`); logger.info('Collecting installed dependencies...'); const rootDependencies = await getProjectDependencies(this.context.root); logger.info(`Found ${rootDependencies.size} dependencies.`); const workflow = new NodeWorkflow(this.context.root, { packageManager: packageManager.name, packageManagerForce: this.packageManagerForce(options.verbose), // __dirname -> favor @schematics/update from this package // Otherwise, use packages from the active workspace (migrations) resolvePaths: this.resolvePaths, schemaValidation: true, engineHostCreator: (options) => new SchematicEngineHost(options.resolvePaths), }); if (packages.length === 0) { // Show status const { success } = await this.executeSchematic( workflow, UPDATE_SCHEMATIC_COLLECTION, 'update', { force: options.force, next: options.next, verbose: options.verbose, packageManager: packageManager.name, packages: [], }, ); return success ? 0 : 1; } return options.migrateOnly ? this.migrateOnly(workflow, (options.packages ?? [])[0], rootDependencies, options) : this.updatePackagesAndMigrate(workflow, rootDependencies, options, packages); } private async executeSchematic( workflow: NodeWorkflow, collection: string, schematic: string, options: Record<string, unknown> = {}, ): Promise<{ success: boolean; files: Set<string> }> { const { logger } = this.context; const workflowSubscription = subscribeToWorkflow(workflow, logger); // TODO: Allow passing a schematic instance directly try { await workflow .execute({ collection, schematic, options, logger, }) .toPromise(); return { success: !workflowSubscription.error, files: workflowSubscription.files }; } catch (e) { if (e instanceof UnsuccessfulWorkflowExecution) { logger.error(`${figures.cross} Migration failed. See above for further details.\n`); } else { assertIsError(e); const logPath = writeErrorToLogFile(e); logger.fatal( `${figures.cross} Migration failed: ${e.message}\n` + ` See "${logPath}" for further details.\n`, ); } return { success: false, files: workflowSubscription.files }; } finally { workflowSubscription.unsubscribe(); } } /** * @return Whether or not the migration was performed successfully. */ private async executeMigration( workflow: NodeWorkflow, packageName: string, collectionPath: string, migrationName: string, commit?: boolean, ): Promise<number> { const { logger } = this.context; const collection = workflow.engine.createCollection(collectionPath); const name = collection.listSchematicNames().find((name) => name === migrationName); if (!name) { logger.error(`Cannot find migration '${migrationName}' in '${packageName}'.`); return 1; } logger.info(colors.cyan(`** Executing '${migrationName}' of package '${packageName}' **\n`)); const schematic = workflow.engine.createSchematic(name, collection); return this.executePackageMigrations(workflow, [schematic.description], packageName, commit); } /** * @return Whether or not the migrations were performed successfully. */
{ "end_byte": 11854, "start_byte": 2660, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular/cli/src/commands/update/cli.ts" }
angular-cli/packages/angular/cli/src/commands/update/cli.ts_11857_19257
private async executeMigrations( workflow: NodeWorkflow, packageName: string, collectionPath: string, from: string, to: string, commit?: boolean, ): Promise<number> { const collection = workflow.engine.createCollection(collectionPath); const migrationRange = new semver.Range( '>' + (semver.prerelease(from) ? from.split('-')[0] + '-0' : from) + ' <=' + to.split('-')[0], ); const requiredMigrations: MigrationSchematicDescriptionWithVersion[] = []; const optionalMigrations: MigrationSchematicDescriptionWithVersion[] = []; for (const name of collection.listSchematicNames()) { const schematic = workflow.engine.createSchematic(name, collection); const description = schematic.description as MigrationSchematicDescription; description.version = coerceVersionNumber(description.version); if (!description.version) { continue; } if (semver.satisfies(description.version, migrationRange, { includePrerelease: true })) { (description.optional ? optionalMigrations : requiredMigrations).push( description as MigrationSchematicDescriptionWithVersion, ); } } if (requiredMigrations.length === 0 && optionalMigrations.length === 0) { return 0; } // Required migrations if (requiredMigrations.length) { this.context.logger.info( colors.cyan(`** Executing migrations of package '${packageName}' **\n`), ); requiredMigrations.sort( (a, b) => semver.compare(a.version, b.version) || a.name.localeCompare(b.name), ); const result = await this.executePackageMigrations( workflow, requiredMigrations, packageName, commit, ); if (result === 1) { return 1; } } // Optional migrations if (optionalMigrations.length) { this.context.logger.info( colors.magenta(`** Optional migrations of package '${packageName}' **\n`), ); optionalMigrations.sort( (a, b) => semver.compare(a.version, b.version) || a.name.localeCompare(b.name), ); const migrationsToRun = await this.getOptionalMigrationsToRun( optionalMigrations, packageName, ); if (migrationsToRun?.length) { return this.executePackageMigrations(workflow, migrationsToRun, packageName, commit); } } return 0; } private async executePackageMigrations( workflow: NodeWorkflow, migrations: MigrationSchematicDescription[], packageName: string, commit = false, ): Promise<1 | 0> { const { logger } = this.context; for (const migration of migrations) { const { title, description } = getMigrationTitleAndDescription(migration); logger.info(colors.cyan(figures.pointer) + ' ' + colors.bold(title)); if (description) { logger.info(' ' + description); } const { success, files } = await this.executeSchematic( workflow, migration.collection.name, migration.name, ); if (!success) { return 1; } let modifiedFilesText: string; switch (files.size) { case 0: modifiedFilesText = 'No changes made'; break; case 1: modifiedFilesText = '1 file modified'; break; default: modifiedFilesText = `${files.size} files modified`; break; } logger.info(` Migration completed (${modifiedFilesText}).`); // Commit migration if (commit) { const commitPrefix = `${packageName} migration - ${migration.name}`; const commitMessage = migration.description ? `${commitPrefix}\n\n${migration.description}` : commitPrefix; const committed = this.commit(commitMessage); if (!committed) { // Failed to commit, something went wrong. Abort the update. return 1; } } logger.info(''); // Extra trailing newline. } return 0; } private async migrateOnly( workflow: NodeWorkflow, packageName: string, rootDependencies: Map<string, PackageTreeNode>, options: Options<UpdateCommandArgs>, ): Promise<number | void> { const { logger } = this.context; const packageDependency = rootDependencies.get(packageName); let packagePath = packageDependency?.path; let packageNode = packageDependency?.package; if (packageDependency && !packageNode) { logger.error('Package found in package.json but is not installed.'); return 1; } else if (!packageDependency) { // Allow running migrations on transitively installed dependencies // There can technically be nested multiple versions // TODO: If multiple, this should find all versions and ask which one to use const packageJson = findPackageJson(this.context.root, packageName); if (packageJson) { packagePath = path.dirname(packageJson); packageNode = await readPackageJson(packageJson); } } if (!packageNode || !packagePath) { logger.error('Package is not installed.'); return 1; } const updateMetadata = packageNode['ng-update']; let migrations = updateMetadata?.migrations; if (migrations === undefined) { logger.error('Package does not provide migrations.'); return 1; } else if (typeof migrations !== 'string') { logger.error('Package contains a malformed migrations field.'); return 1; } else if (path.posix.isAbsolute(migrations) || path.win32.isAbsolute(migrations)) { logger.error( 'Package contains an invalid migrations field. Absolute paths are not permitted.', ); return 1; } // Normalize slashes migrations = migrations.replace(/\\/g, '/'); if (migrations.startsWith('../')) { logger.error( 'Package contains an invalid migrations field. Paths outside the package root are not permitted.', ); return 1; } // Check if it is a package-local location const localMigrations = path.join(packagePath, migrations); if (existsSync(localMigrations)) { migrations = localMigrations; } else { // Try to resolve from package location. // This avoids issues with package hoisting. try { const packageRequire = createRequire(packagePath + '/'); migrations = packageRequire.resolve(migrations, { paths: this.resolvePaths }); } catch (e) { assertIsError(e); if (e.code === 'MODULE_NOT_FOUND') { logger.error('Migrations for package were not found.'); } else { logger.error(`Unable to resolve migrations for package. [${e.message}]`); } return 1; } } if (options.name) { return this.executeMigration( workflow, packageName, migrations, options.name, options.createCommits, ); } const from = coerceVersionNumber(options.from); if (!from) { logger.error(`"from" value [${options.from}] is not a valid version.`); return 1; } return this.executeMigrations( workflow, packageName, migrations, from, options.to || packageNode.version, options.createCommits, ); } // eslint-disable-next-line max-lines-per-function
{ "end_byte": 19257, "start_byte": 11857, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular/cli/src/commands/update/cli.ts" }
angular-cli/packages/angular/cli/src/commands/update/cli.ts_19260_29276
private async updatePackagesAndMigrate( workflow: NodeWorkflow, rootDependencies: Map<string, PackageTreeNode>, options: Options<UpdateCommandArgs>, packages: PackageIdentifier[], ): Promise<number> { const { logger } = this.context; const logVerbose = (message: string) => { if (options.verbose) { logger.info(message); } }; const requests: { identifier: PackageIdentifier; node: PackageTreeNode; }[] = []; // Validate packages actually are part of the workspace for (const pkg of packages) { const node = rootDependencies.get(pkg.name); if (!node?.package) { logger.error(`Package '${pkg.name}' is not a dependency.`); return 1; } // If a specific version is requested and matches the installed version, skip. if (pkg.type === 'version' && node.package.version === pkg.fetchSpec) { logger.info(`Package '${pkg.name}' is already at '${pkg.fetchSpec}'.`); continue; } requests.push({ identifier: pkg, node }); } if (requests.length === 0) { return 0; } logger.info('Fetching dependency metadata from registry...'); const packagesToUpdate: string[] = []; for (const { identifier: requestIdentifier, node } of requests) { const packageName = requestIdentifier.name; let metadata; try { // Metadata requests are internally cached; multiple requests for same name // does not result in additional network traffic metadata = await fetchPackageMetadata(packageName, logger, { verbose: options.verbose, }); } catch (e) { assertIsError(e); logger.error(`Error fetching metadata for '${packageName}': ` + e.message); return 1; } // Try to find a package version based on the user requested package specifier // registry specifier types are either version, range, or tag let manifest: PackageManifest | undefined; if ( requestIdentifier.type === 'version' || requestIdentifier.type === 'range' || requestIdentifier.type === 'tag' ) { try { manifest = pickManifest(metadata, requestIdentifier.fetchSpec); } catch (e) { assertIsError(e); if (e.code === 'ETARGET') { // If not found and next was used and user did not provide a specifier, try latest. // Package may not have a next tag. if ( requestIdentifier.type === 'tag' && requestIdentifier.fetchSpec === 'next' && !requestIdentifier.rawSpec ) { try { manifest = pickManifest(metadata, 'latest'); } catch (e) { assertIsError(e); if (e.code !== 'ETARGET' && e.code !== 'ENOVERSIONS') { throw e; } } } } else if (e.code !== 'ENOVERSIONS') { throw e; } } } if (!manifest) { logger.error( `Package specified by '${requestIdentifier.raw}' does not exist within the registry.`, ); return 1; } if (manifest.version === node.package?.version) { logger.info(`Package '${packageName}' is already up to date.`); continue; } if (node.package && ANGULAR_PACKAGES_REGEXP.test(node.package.name)) { const { name, version } = node.package; const toBeInstalledMajorVersion = +manifest.version.split('.')[0]; const currentMajorVersion = +version.split('.')[0]; if (toBeInstalledMajorVersion - currentMajorVersion > 1) { // Only allow updating a single version at a time. if (currentMajorVersion < 6) { // Before version 6, the major versions were not always sequential. // Example @angular/core skipped version 3, @angular/cli skipped versions 2-5. logger.error( `Updating multiple major versions of '${name}' at once is not supported. Please migrate each major version individually.\n` + `For more information about the update process, see https://update.angular.dev/.`, ); } else { const nextMajorVersionFromCurrent = currentMajorVersion + 1; logger.error( `Updating multiple major versions of '${name}' at once is not supported. Please migrate each major version individually.\n` + `Run 'ng update ${name}@${nextMajorVersionFromCurrent}' in your workspace directory ` + `to update to latest '${nextMajorVersionFromCurrent}.x' version of '${name}'.\n\n` + `For more information about the update process, see https://update.angular.dev/?v=${currentMajorVersion}.0-${nextMajorVersionFromCurrent}.0`, ); } return 1; } } packagesToUpdate.push(requestIdentifier.toString()); } if (packagesToUpdate.length === 0) { return 0; } const { success } = await this.executeSchematic( workflow, UPDATE_SCHEMATIC_COLLECTION, 'update', { verbose: options.verbose, force: options.force, next: options.next, packageManager: this.context.packageManager.name, packages: packagesToUpdate, }, ); if (success) { const { root: commandRoot, packageManager } = this.context; const installArgs = this.packageManagerForce(options.verbose) ? ['--force'] : []; const tasks = new Listr([ { title: 'Cleaning node modules directory', async task(_, task) { try { await fs.rm(path.join(commandRoot, 'node_modules'), { force: true, recursive: true, maxRetries: 3, }); } catch (e) { assertIsError(e); if (e.code === 'ENOENT') { task.skip('Cleaning not required. Node modules directory not found.'); } } }, }, { title: 'Installing packages', async task() { const installationSuccess = await packageManager.installAll(installArgs, commandRoot); if (!installationSuccess) { throw new CommandError('Unable to install packages'); } }, }, ]); try { await tasks.run(); } catch (e) { if (e instanceof CommandError) { return 1; } throw e; } } if (success && options.createCommits) { if (!this.commit(`Angular CLI update for packages - ${packagesToUpdate.join(', ')}`)) { return 1; } } // This is a temporary workaround to allow data to be passed back from the update schematic // eslint-disable-next-line @typescript-eslint/no-explicit-any const migrations = (global as any).externalMigrations as { package: string; collection: string; from: string; to: string; }[]; if (success && migrations) { const rootRequire = createRequire(this.context.root + '/'); for (const migration of migrations) { // Resolve the package from the workspace root, as otherwise it will be resolved from the temp // installed CLI version. let packagePath; logVerbose( `Resolving migration package '${migration.package}' from '${this.context.root}'...`, ); try { try { packagePath = path.dirname( // This may fail if the `package.json` is not exported as an entry point rootRequire.resolve(path.join(migration.package, 'package.json')), ); } catch (e) { assertIsError(e); if (e.code === 'MODULE_NOT_FOUND') { // Fallback to trying to resolve the package's main entry point packagePath = rootRequire.resolve(migration.package); } else { throw e; } } } catch (e) { assertIsError(e); if (e.code === 'MODULE_NOT_FOUND') { logVerbose(e.toString()); logger.error( `Migrations for package (${migration.package}) were not found.` + ' The package could not be found in the workspace.', ); } else { logger.error( `Unable to resolve migrations for package (${migration.package}). [${e.message}]`, ); } return 1; } let migrations; // Check if it is a package-local location const localMigrations = path.join(packagePath, migration.collection); if (existsSync(localMigrations)) { migrations = localMigrations; } else { // Try to resolve from package location. // This avoids issues with package hoisting. try { const packageRequire = createRequire(packagePath + '/'); migrations = packageRequire.resolve(migration.collection); } catch (e) { assertIsError(e); if (e.code === 'MODULE_NOT_FOUND') { logger.error(`Migrations for package (${migration.package}) were not found.`); } else { logger.error( `Unable to resolve migrations for package (${migration.package}). [${e.message}]`, ); } return 1; } } const result = await this.executeMigrations( workflow, migration.package, migrations, migration.from, migration.to, options.createCommits, ); // A non-zero value is a failure for the package's migrations if (result !== 0) { return result; } } } return success ? 0 : 1; }
{ "end_byte": 29276, "start_byte": 19260, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular/cli/src/commands/update/cli.ts" }
angular-cli/packages/angular/cli/src/commands/update/cli.ts_29280_37851
/** * @return Whether or not the commit was successful. */ private commit(message: string): boolean { const { logger } = this.context; // Check if a commit is needed. let commitNeeded: boolean; try { commitNeeded = hasChangesToCommit(); } catch (err) { logger.error(` Failed to read Git tree:\n${(err as SpawnSyncReturns<string>).stderr}`); return false; } if (!commitNeeded) { logger.info(' No changes to commit after migration.'); return true; } // Commit changes and abort on error. try { createCommit(message); } catch (err) { logger.error( `Failed to commit update (${message}):\n${(err as SpawnSyncReturns<string>).stderr}`, ); return false; } // Notify user of the commit. const hash = findCurrentGitSha(); const shortMessage = message.split('\n')[0]; if (hash) { logger.info(` Committed migration step (${getShortHash(hash)}): ${shortMessage}.`); } else { // Commit was successful, but reading the hash was not. Something weird happened, // but nothing that would stop the update. Just log the weirdness and continue. logger.info(` Committed migration step: ${shortMessage}.`); logger.warn(' Failed to look up hash of most recent commit, continuing anyways.'); } return true; } private checkCleanGit(): boolean { try { const topLevel = execSync('git rev-parse --show-toplevel', { encoding: 'utf8', stdio: 'pipe', }); const result = execSync('git status --porcelain', { encoding: 'utf8', stdio: 'pipe' }); if (result.trim().length === 0) { return true; } // Only files inside the workspace root are relevant for (const entry of result.split('\n')) { const relativeEntry = path.relative( path.resolve(this.context.root), path.resolve(topLevel.trim(), entry.slice(3).trim()), ); if (!relativeEntry.startsWith('..') && !path.isAbsolute(relativeEntry)) { return false; } } } catch {} return true; } /** * Checks if the current installed CLI version is older or newer than a compatible version. * @returns the version to install or null when there is no update to install. */ private async checkCLIVersion( packagesToUpdate: string[], verbose = false, next = false, ): Promise<string | null> { const { version } = await fetchPackageManifest( `@angular/cli@${this.getCLIUpdateRunnerVersion(packagesToUpdate, next)}`, this.context.logger, { verbose, usingYarn: this.context.packageManager.name === PackageManager.Yarn, }, ); return VERSION.full === version ? null : version; } private getCLIUpdateRunnerVersion( packagesToUpdate: string[] | undefined, next: boolean, ): string | number { if (next) { return 'next'; } const updatingAngularPackage = packagesToUpdate?.find((r) => ANGULAR_PACKAGES_REGEXP.test(r)); if (updatingAngularPackage) { // If we are updating any Angular package we can update the CLI to the target version because // migrations for @angular/core@13 can be executed using Angular/cli@13. // This is same behaviour as `npx @angular/cli@13 update @angular/core@13`. // `@angular/cli@13` -> ['', 'angular/cli', '13'] // `@angular/cli` -> ['', 'angular/cli'] const tempVersion = coerceVersionNumber(updatingAngularPackage.split('@')[2]); return semver.parse(tempVersion)?.major ?? 'latest'; } // When not updating an Angular package we cannot determine which schematic runtime the migration should to be executed in. // Typically, we can assume that the `@angular/cli` was updated previously. // Example: Angular official packages are typically updated prior to NGRX etc... // Therefore, we only update to the latest patch version of the installed major version of the Angular CLI. // This is important because we might end up in a scenario where locally Angular v12 is installed, updating NGRX from 11 to 12. // We end up using Angular ClI v13 to run the migrations if we run the migrations using the CLI installed major version + 1 logic. return VERSION.major; } private async runTempBinary(packageName: string, args: string[] = []): Promise<number> { const { success, tempNodeModules } = await this.context.packageManager.installTemp(packageName); if (!success) { return 1; } // Remove version/tag etc... from package name // Ex: @angular/cli@latest -> @angular/cli const packageNameNoVersion = packageName.substring(0, packageName.lastIndexOf('@')); const pkgLocation = join(tempNodeModules, packageNameNoVersion); const packageJsonPath = join(pkgLocation, 'package.json'); // Get a binary location for this package let binPath: string | undefined; if (existsSync(packageJsonPath)) { const content = await fs.readFile(packageJsonPath, 'utf-8'); if (content) { const { bin = {} } = JSON.parse(content) as { bin: Record<string, string> }; const binKeys = Object.keys(bin); if (binKeys.length) { binPath = resolve(pkgLocation, bin[binKeys[0]]); } } } if (!binPath) { throw new Error(`Cannot locate bin for temporary package: ${packageNameNoVersion}.`); } const { status, error } = spawnSync(process.execPath, [binPath, ...args], { stdio: 'inherit', env: { ...process.env, NG_DISABLE_VERSION_CHECK: 'true', NG_CLI_ANALYTICS: 'false', }, }); if (status === null && error) { throw error; } return status ?? 0; } private packageManagerForce(verbose: boolean): boolean { // npm 7+ can fail due to it incorrectly resolving peer dependencies that have valid SemVer // ranges during an update. Update will set correct versions of dependencies within the // package.json file. The force option is set to workaround these errors. // Example error: // npm ERR! Conflicting peer dependency: @angular/[email protected] // npm ERR! node_modules/@angular/compiler-cli // npm ERR! peer @angular/compiler-cli@"^14.0.0 || ^14.0.0-rc" from @angular-devkit/[email protected] // npm ERR! node_modules/@angular-devkit/build-angular // npm ERR! dev @angular-devkit/build-angular@"~14.0.0-rc.0" from the root project if ( this.context.packageManager.name === PackageManager.Npm && this.context.packageManager.version && semver.gte(this.context.packageManager.version, '7.0.0') ) { if (verbose) { this.context.logger.info( 'NPM 7+ detected -- enabling force option for package installation', ); } return true; } return false; } private async getOptionalMigrationsToRun( optionalMigrations: MigrationSchematicDescription[], packageName: string, ): Promise<MigrationSchematicDescription[] | undefined> { const { logger } = this.context; const numberOfMigrations = optionalMigrations.length; logger.info( `This package has ${numberOfMigrations} optional migration${ numberOfMigrations > 1 ? 's' : '' } that can be executed.`, ); if (!isTTY()) { for (const migration of optionalMigrations) { const { title } = getMigrationTitleAndDescription(migration); logger.info(colors.cyan(figures.pointer) + ' ' + colors.bold(title)); logger.info(colors.gray(` ng update ${packageName} --name ${migration.name}`)); logger.info(''); // Extra trailing newline. } return undefined; } logger.info( 'Optional migrations may be skipped and executed after the update process, if preferred.', ); logger.info(''); // Extra trailing newline. const answer = await askChoices( `Select the migrations that you'd like to run`, optionalMigrations.map((migration) => { const { title, documentation } = getMigrationTitleAndDescription(migration); return { name: `[${colors.white(migration.name)}] ${title}${documentation ? ` (${documentation})` : ''}`, value: migration.name, }; }), null, ); logger.info(''); // Extra trailing newline. return optionalMigrations.filter(({ name }) => answer?.includes(name)); } } /** * @return Whether or not the working directory has Git changes to commit. */
{ "end_byte": 37851, "start_byte": 29280, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular/cli/src/commands/update/cli.ts" }
angular-cli/packages/angular/cli/src/commands/update/cli.ts_37852_40116
function hasChangesToCommit(): boolean { // List all modified files not covered by .gitignore. // If any files are returned, then there must be something to commit. return execSync('git ls-files -m -d -o --exclude-standard').toString() !== ''; } /** * Precondition: Must have pending changes to commit, they do not need to be staged. * Postcondition: The Git working tree is committed and the repo is clean. * @param message The commit message to use. */ function createCommit(message: string) { // Stage entire working tree for commit. execSync('git add -A', { encoding: 'utf8', stdio: 'pipe' }); // Commit with the message passed via stdin to avoid bash escaping issues. execSync('git commit --no-verify -F -', { encoding: 'utf8', stdio: 'pipe', input: message }); } /** * @return The Git SHA hash of the HEAD commit. Returns null if unable to retrieve the hash. */ function findCurrentGitSha(): string | null { try { return execSync('git rev-parse HEAD', { encoding: 'utf8', stdio: 'pipe' }).trim(); } catch { return null; } } function getShortHash(commitHash: string): string { return commitHash.slice(0, 9); } function coerceVersionNumber(version: string | undefined): string | undefined { if (!version) { return undefined; } if (!/^\d{1,30}\.\d{1,30}\.\d{1,30}/.test(version)) { const match = version.match(/^\d{1,30}(\.\d{1,30})*/); if (!match) { return undefined; } if (!match[1]) { version = version.substring(0, match[0].length) + '.0.0' + version.substring(match[0].length); } else if (!match[2]) { version = version.substring(0, match[0].length) + '.0' + version.substring(match[0].length); } else { return undefined; } } return semver.valid(version) ?? undefined; } function getMigrationTitleAndDescription(migration: MigrationSchematicDescription): { title: string; description: string; documentation?: string; } { const [title, ...description] = migration.description.split('. '); return { title: title.endsWith('.') ? title : title + '.', description: description.join('.\n '), documentation: migration.documentation ? new URL(migration.documentation, 'https://angular.dev').href : undefined, }; }
{ "end_byte": 40116, "start_byte": 37852, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular/cli/src/commands/update/cli.ts" }
angular-cli/packages/angular/cli/src/commands/update/long-description.md_0_806
Perform a basic update to the current stable release of the core framework and CLI by running the following command. ``` ng update @angular/cli @angular/core ``` To update to the next beta or pre-release version, use the `--next` option. To update from one major version to another, use the format ``` ng update @angular/cli@^<major_version> @angular/core@^<major_version> ``` We recommend that you always update to the latest patch version, as it contains fixes we released since the initial major release. For example, use the following command to take the latest 10.x.x version and use that to update. ``` ng update @angular/cli@^10 @angular/core@^10 ``` For detailed information and guidance on updating your application, see the interactive [Angular Update Guide](https://update.angular.dev/).
{ "end_byte": 806, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular/cli/src/commands/update/long-description.md" }
angular-cli/packages/angular/cli/src/commands/update/schematic/index.ts_0_8199
/** * @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 { logging } from '@angular-devkit/core'; import { Rule, SchematicContext, SchematicsException, Tree } from '@angular-devkit/schematics'; import * as npa from 'npm-package-arg'; import type { Manifest } from 'pacote'; import * as semver from 'semver'; import { NgPackageManifestProperties, NpmRepositoryPackageJson, getNpmPackageJson, } from '../../../utilities/package-metadata'; import { Schema as UpdateSchema } from './schema'; interface JsonSchemaForNpmPackageJsonFiles extends Manifest, NgPackageManifestProperties { peerDependenciesMeta?: Record<string, { optional?: boolean }>; } type VersionRange = string & { __VERSION_RANGE: void }; type PeerVersionTransform = string | ((range: string) => string); // Angular guarantees that a major is compatible with its following major (so packages that depend // on Angular 5 are also compatible with Angular 6). This is, in code, represented by verifying // that all other packages that have a peer dependency of `"@angular/core": "^5.0.0"` actually // supports 6.0, by adding that compatibility to the range, so it is `^5.0.0 || ^6.0.0`. // We export it to allow for testing. export function angularMajorCompatGuarantee(range: string) { let newRange = semver.validRange(range); if (!newRange) { return range; } let major = 1; while (!semver.gtr(major + '.0.0', newRange)) { major++; if (major >= 99) { // Use original range if it supports a major this high // Range is most likely unbounded (e.g., >=5.0.0) return newRange; } } // Add the major version as compatible with the angular compatible, with all minors. This is // already one major above the greatest supported, because we increment `major` before checking. // We add minors like this because a minor beta is still compatible with a minor non-beta. newRange = range; for (let minor = 0; minor < 20; minor++) { newRange += ` || ^${major}.${minor}.0-alpha.0 `; } return semver.validRange(newRange) || range; } // This is a map of packageGroupName to range extending function. If it isn't found, the range is // kept the same. const knownPeerCompatibleList: { [name: string]: PeerVersionTransform } = { '@angular/core': angularMajorCompatGuarantee, }; interface PackageVersionInfo { version: VersionRange; packageJson: JsonSchemaForNpmPackageJsonFiles; updateMetadata: UpdateMetadata; } interface PackageInfo { name: string; npmPackageJson: NpmRepositoryPackageJson; installed: PackageVersionInfo; target?: PackageVersionInfo; packageJsonRange: string; } interface UpdateMetadata { packageGroupName?: string; packageGroup: { [packageName: string]: string }; requirements: { [packageName: string]: string }; migrations?: string; } function _updatePeerVersion(infoMap: Map<string, PackageInfo>, name: string, range: string) { // Resolve packageGroupName. const maybePackageInfo = infoMap.get(name); if (!maybePackageInfo) { return range; } if (maybePackageInfo.target) { name = maybePackageInfo.target.updateMetadata.packageGroupName || name; } else { name = maybePackageInfo.installed.updateMetadata.packageGroupName || name; } const maybeTransform = knownPeerCompatibleList[name]; if (maybeTransform) { if (typeof maybeTransform == 'function') { return maybeTransform(range); } else { return maybeTransform; } } return range; } function _validateForwardPeerDependencies( name: string, infoMap: Map<string, PackageInfo>, peers: { [name: string]: string }, peersMeta: { [name: string]: { optional?: boolean } }, logger: logging.LoggerApi, next: boolean, ): boolean { let validationFailed = false; for (const [peer, range] of Object.entries(peers)) { logger.debug(`Checking forward peer ${peer}...`); const maybePeerInfo = infoMap.get(peer); const isOptional = peersMeta[peer] && !!peersMeta[peer].optional; if (!maybePeerInfo) { if (!isOptional) { logger.warn( [ `Package ${JSON.stringify(name)} has a missing peer dependency of`, `${JSON.stringify(peer)} @ ${JSON.stringify(range)}.`, ].join(' '), ); } continue; } const peerVersion = maybePeerInfo.target && maybePeerInfo.target.packageJson.version ? maybePeerInfo.target.packageJson.version : maybePeerInfo.installed.version; logger.debug(` Range intersects(${range}, ${peerVersion})...`); if (!semver.satisfies(peerVersion, range, { includePrerelease: next || undefined })) { logger.error( [ `Package ${JSON.stringify(name)} has an incompatible peer dependency to`, `${JSON.stringify(peer)} (requires ${JSON.stringify(range)},`, `would install ${JSON.stringify(peerVersion)})`, ].join(' '), ); validationFailed = true; continue; } } return validationFailed; } function _validateReversePeerDependencies( name: string, version: string, infoMap: Map<string, PackageInfo>, logger: logging.LoggerApi, next: boolean, ) { for (const [installed, installedInfo] of infoMap.entries()) { const installedLogger = logger.createChild(installed); installedLogger.debug(`${installed}...`); const peers = (installedInfo.target || installedInfo.installed).packageJson.peerDependencies; for (const [peer, range] of Object.entries(peers || {})) { if (peer != name) { // Only check peers to the packages we're updating. We don't care about peers // that are unmet but we have no effect on. continue; } // Ignore peerDependency mismatches for these packages. // They are deprecated and removed via a migration. const ignoredPackages = [ 'codelyzer', '@schematics/update', '@angular-devkit/build-ng-packagr', 'tsickle', '@nguniversal/builders', ]; if (ignoredPackages.includes(installed)) { continue; } // Override the peer version range if it's known as a compatible. const extendedRange = _updatePeerVersion(infoMap, peer, range); if (!semver.satisfies(version, extendedRange, { includePrerelease: next || undefined })) { logger.error( [ `Package ${JSON.stringify(installed)} has an incompatible peer dependency to`, `${JSON.stringify(name)} (requires`, `${JSON.stringify(range)}${extendedRange == range ? '' : ' (extended)'},`, `would install ${JSON.stringify(version)}).`, ].join(' '), ); return true; } } } return false; } function _validateUpdatePackages( infoMap: Map<string, PackageInfo>, force: boolean, next: boolean, logger: logging.LoggerApi, ): void { logger.debug('Updating the following packages:'); infoMap.forEach((info) => { if (info.target) { logger.debug(` ${info.name} => ${info.target.version}`); } }); let peerErrors = false; infoMap.forEach((info) => { const { name, target } = info; if (!target) { return; } const pkgLogger = logger.createChild(name); logger.debug(`${name}...`); const { peerDependencies = {}, peerDependenciesMeta = {} } = target.packageJson; peerErrors = _validateForwardPeerDependencies( name, infoMap, peerDependencies, peerDependenciesMeta, pkgLogger, next, ) || peerErrors; peerErrors = _validateReversePeerDependencies(name, target.version, infoMap, pkgLogger, next) || peerErrors; }); if (!force && peerErrors) { throw new SchematicsException( 'Incompatible peer dependencies found.\n' + 'Peer dependency warnings when installing dependencies means that those dependencies might not work correctly together.\n' + `You can use the '--force' option to ignore incompatible peer dependencies and instead address these warnings later.`, ); } }
{ "end_byte": 8199, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular/cli/src/commands/update/schematic/index.ts" }
angular-cli/packages/angular/cli/src/commands/update/schematic/index.ts_8201_13745
function _performUpdate( tree: Tree, context: SchematicContext, infoMap: Map<string, PackageInfo>, logger: logging.LoggerApi, migrateOnly: boolean, ): void { const packageJsonContent = tree.read('/package.json')?.toString(); if (!packageJsonContent) { throw new SchematicsException('Could not find a package.json. Are you in a Node project?'); } const packageJson = tree.readJson('/package.json') as JsonSchemaForNpmPackageJsonFiles; const updateDependency = (deps: Record<string, string>, name: string, newVersion: string) => { const oldVersion = deps[name]; // We only respect caret and tilde ranges on update. const execResult = /^[\^~]/.exec(oldVersion); deps[name] = `${execResult ? execResult[0] : ''}${newVersion}`; }; const toInstall = [...infoMap.values()] .map((x) => [x.name, x.target, x.installed]) .filter(([name, target, installed]) => { return !!name && !!target && !!installed; }) as [string, PackageVersionInfo, PackageVersionInfo][]; toInstall.forEach(([name, target, installed]) => { logger.info( `Updating package.json with dependency ${name} ` + `@ ${JSON.stringify(target.version)} (was ${JSON.stringify(installed.version)})...`, ); if (packageJson.dependencies && packageJson.dependencies[name]) { updateDependency(packageJson.dependencies, name, target.version); if (packageJson.devDependencies && packageJson.devDependencies[name]) { delete packageJson.devDependencies[name]; } if (packageJson.peerDependencies && packageJson.peerDependencies[name]) { delete packageJson.peerDependencies[name]; } } else if (packageJson.devDependencies && packageJson.devDependencies[name]) { updateDependency(packageJson.devDependencies, name, target.version); if (packageJson.peerDependencies && packageJson.peerDependencies[name]) { delete packageJson.peerDependencies[name]; } } else if (packageJson.peerDependencies && packageJson.peerDependencies[name]) { updateDependency(packageJson.peerDependencies, name, target.version); } else { logger.warn(`Package ${name} was not found in dependencies.`); } }); const eofMatches = packageJsonContent.match(/\r?\n$/); const eof = eofMatches?.[0] ?? ''; const newContent = JSON.stringify(packageJson, null, 2) + eof; if (packageJsonContent != newContent || migrateOnly) { if (!migrateOnly) { tree.overwrite('/package.json', newContent); } const externalMigrations: {}[] = []; // Run the migrate schematics with the list of packages to use. The collection contains // version information and we need to do this post installation. Please note that the // migration COULD fail and leave side effects on disk. // Run the schematics task of those packages. toInstall.forEach(([name, target, installed]) => { if (!target.updateMetadata.migrations) { return; } externalMigrations.push({ package: name, collection: target.updateMetadata.migrations, from: installed.version, to: target.version, }); return; }); if (externalMigrations.length > 0) { // eslint-disable-next-line @typescript-eslint/no-explicit-any (global as any).externalMigrations = externalMigrations; } } } function _getUpdateMetadata( packageJson: JsonSchemaForNpmPackageJsonFiles, logger: logging.LoggerApi, ): UpdateMetadata { const metadata = packageJson['ng-update']; const result: UpdateMetadata = { packageGroup: {}, requirements: {}, }; if (!metadata || typeof metadata != 'object' || Array.isArray(metadata)) { return result; } if (metadata['packageGroup']) { const packageGroup = metadata['packageGroup']; // Verify that packageGroup is an array of strings or an map of versions. This is not an error // but we still warn the user and ignore the packageGroup keys. if (Array.isArray(packageGroup) && packageGroup.every((x) => typeof x == 'string')) { result.packageGroup = packageGroup.reduce((group, name) => { group[name] = packageJson.version; return group; }, result.packageGroup); } else if ( typeof packageGroup == 'object' && packageGroup && !Array.isArray(packageGroup) && Object.values(packageGroup).every((x) => typeof x == 'string') ) { result.packageGroup = packageGroup; } else { logger.warn(`packageGroup metadata of package ${packageJson.name} is malformed. Ignoring.`); } result.packageGroupName = Object.keys(result.packageGroup)[0]; } if (typeof metadata['packageGroupName'] == 'string') { result.packageGroupName = metadata['packageGroupName']; } if (metadata['requirements']) { const requirements = metadata['requirements']; // Verify that requirements are if ( typeof requirements != 'object' || Array.isArray(requirements) || Object.keys(requirements).some((name) => typeof requirements[name] != 'string') ) { logger.warn(`requirements metadata of package ${packageJson.name} is malformed. Ignoring.`); } else { result.requirements = requirements; } } if (metadata['migrations']) { const migrations = metadata['migrations']; if (typeof migrations != 'string') { logger.warn(`migrations metadata of package ${packageJson.name} is malformed. Ignoring.`); } else { result.migrations = migrations; } } return result; }
{ "end_byte": 13745, "start_byte": 8201, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular/cli/src/commands/update/schematic/index.ts" }
angular-cli/packages/angular/cli/src/commands/update/schematic/index.ts_13747_21000
function _usageMessage( options: UpdateSchema, infoMap: Map<string, PackageInfo>, logger: logging.LoggerApi, ) { const packageGroups = new Map<string, string>(); const packagesToUpdate = [...infoMap.entries()] .map(([name, info]) => { let tag = options.next ? info.npmPackageJson['dist-tags']['next'] ? 'next' : 'latest' : 'latest'; let version = info.npmPackageJson['dist-tags'][tag]; let target = info.npmPackageJson.versions[version]; const versionDiff = semver.diff(info.installed.version, version); if ( versionDiff !== 'patch' && versionDiff !== 'minor' && /^@(?:angular|nguniversal)\//.test(name) ) { const installedMajorVersion = semver.parse(info.installed.version)?.major; const toInstallMajorVersion = semver.parse(version)?.major; if ( installedMajorVersion !== undefined && toInstallMajorVersion !== undefined && installedMajorVersion < toInstallMajorVersion - 1 ) { const nextMajorVersion = `${installedMajorVersion + 1}.`; const nextMajorVersions = Object.keys(info.npmPackageJson.versions) .filter((v) => v.startsWith(nextMajorVersion)) .sort((a, b) => (a > b ? -1 : 1)); if (nextMajorVersions.length) { version = nextMajorVersions[0]; target = info.npmPackageJson.versions[version]; tag = ''; } } } return { name, info, version, tag, target, }; }) .filter( ({ info, version, target }) => target?.['ng-update'] && semver.compare(info.installed.version, version) < 0, ) .map(({ name, info, version, tag, target }) => { // Look for packageGroup. const packageGroup = target['ng-update']?.['packageGroup']; if (packageGroup) { const packageGroupNames = Array.isArray(packageGroup) ? packageGroup : Object.keys(packageGroup); const packageGroupName = target['ng-update']?.['packageGroupName'] || packageGroupNames[0]; if (packageGroupName) { if (packageGroups.has(name)) { return null; } packageGroupNames.forEach((x: string) => packageGroups.set(x, packageGroupName)); packageGroups.set(packageGroupName, packageGroupName); name = packageGroupName; } } let command = `ng update ${name}`; if (!tag) { command += `@${semver.parse(version)?.major || version}`; } else if (tag == 'next') { command += ' --next'; } return [name, `${info.installed.version} -> ${version} `, command]; }) .filter((x) => x !== null) .sort((a, b) => (a && b ? a[0].localeCompare(b[0]) : 0)); if (packagesToUpdate.length == 0) { logger.info('We analyzed your package.json and everything seems to be in order. Good work!'); return; } logger.info('We analyzed your package.json, there are some packages to update:\n'); // Find the largest name to know the padding needed. let namePad = Math.max(...[...infoMap.keys()].map((x) => x.length)) + 2; if (!Number.isFinite(namePad)) { namePad = 30; } const pads = [namePad, 25, 0]; logger.info( ' ' + ['Name', 'Version', 'Command to update'].map((x, i) => x.padEnd(pads[i])).join(''), ); logger.info(' ' + '-'.repeat(pads.reduce((s, x) => (s += x), 0) + 20)); packagesToUpdate.forEach((fields) => { if (!fields) { return; } logger.info(' ' + fields.map((x, i) => x.padEnd(pads[i])).join('')); }); logger.info( `\nThere might be additional packages which don't provide 'ng update' capabilities that are outdated.\n` + `You can update the additional packages by running the update command of your package manager.`, ); return; } function _buildPackageInfo( tree: Tree, packages: Map<string, VersionRange>, allDependencies: ReadonlyMap<string, VersionRange>, npmPackageJson: NpmRepositoryPackageJson, logger: logging.LoggerApi, ): PackageInfo { const name = npmPackageJson.name; const packageJsonRange = allDependencies.get(name); if (!packageJsonRange) { throw new SchematicsException(`Package ${JSON.stringify(name)} was not found in package.json.`); } // Find out the currently installed version. Either from the package.json or the node_modules/ // TODO: figure out a way to read package-lock.json and/or yarn.lock. const pkgJsonPath = `/node_modules/${name}/package.json`; const pkgJsonExists = tree.exists(pkgJsonPath); let installedVersion: string | undefined | null; if (pkgJsonExists) { const { version } = tree.readJson(pkgJsonPath) as JsonSchemaForNpmPackageJsonFiles; installedVersion = version; } const packageVersionsNonDeprecated: string[] = []; const packageVersionsDeprecated: string[] = []; for (const [version, { deprecated }] of Object.entries(npmPackageJson.versions)) { if (deprecated) { packageVersionsDeprecated.push(version); } else { packageVersionsNonDeprecated.push(version); } } const findSatisfyingVersion = (targetVersion: VersionRange): VersionRange | undefined => ((semver.maxSatisfying(packageVersionsNonDeprecated, targetVersion) ?? semver.maxSatisfying(packageVersionsDeprecated, targetVersion)) as VersionRange | null) ?? undefined; if (!installedVersion) { // Find the version from NPM that fits the range to max. installedVersion = findSatisfyingVersion(packageJsonRange); } if (!installedVersion) { throw new SchematicsException( `An unexpected error happened; could not determine version for package ${name}.`, ); } const installedPackageJson = npmPackageJson.versions[installedVersion] || pkgJsonExists; if (!installedPackageJson) { throw new SchematicsException( `An unexpected error happened; package ${name} has no version ${installedVersion}.`, ); } let targetVersion: VersionRange | undefined = packages.get(name); if (targetVersion) { if (npmPackageJson['dist-tags'][targetVersion]) { targetVersion = npmPackageJson['dist-tags'][targetVersion] as VersionRange; } else if (targetVersion == 'next') { targetVersion = npmPackageJson['dist-tags']['latest'] as VersionRange; } else { targetVersion = findSatisfyingVersion(targetVersion); } } if (targetVersion && semver.lte(targetVersion, installedVersion)) { logger.debug(`Package ${name} already satisfied by package.json (${packageJsonRange}).`); targetVersion = undefined; } const target: PackageVersionInfo | undefined = targetVersion ? { version: targetVersion, packageJson: npmPackageJson.versions[targetVersion], updateMetadata: _getUpdateMetadata(npmPackageJson.versions[targetVersion], logger), } : undefined; // Check if there's an installed version. return { name, npmPackageJson, installed: { version: installedVersion as VersionRange, packageJson: installedPackageJson, updateMetadata: _getUpdateMetadata(installedPackageJson, logger), }, target, packageJsonRange, }; }
{ "end_byte": 21000, "start_byte": 13747, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular/cli/src/commands/update/schematic/index.ts" }
angular-cli/packages/angular/cli/src/commands/update/schematic/index.ts_21002_26585
function _buildPackageList( options: UpdateSchema, projectDeps: Map<string, VersionRange>, logger: logging.LoggerApi, ): Map<string, VersionRange> { // Parse the packages options to set the targeted version. const packages = new Map<string, VersionRange>(); const commandLinePackages = options.packages && options.packages.length > 0 ? options.packages : []; for (const pkg of commandLinePackages) { // Split the version asked on command line. const m = pkg.match(/^((?:@[^/]{1,100}\/)?[^@]{1,100})(?:@(.{1,100}))?$/); if (!m) { logger.warn(`Invalid package argument: ${JSON.stringify(pkg)}. Skipping.`); continue; } const [, npmName, maybeVersion] = m; const version = projectDeps.get(npmName); if (!version) { logger.warn(`Package not installed: ${JSON.stringify(npmName)}. Skipping.`); continue; } packages.set(npmName, (maybeVersion || (options.next ? 'next' : 'latest')) as VersionRange); } return packages; } function _addPackageGroup( tree: Tree, packages: Map<string, VersionRange>, allDependencies: ReadonlyMap<string, VersionRange>, npmPackageJson: NpmRepositoryPackageJson, logger: logging.LoggerApi, ): void { const maybePackage = packages.get(npmPackageJson.name); if (!maybePackage) { return; } const info = _buildPackageInfo(tree, packages, allDependencies, npmPackageJson, logger); const version = (info.target && info.target.version) || npmPackageJson['dist-tags'][maybePackage] || maybePackage; if (!npmPackageJson.versions[version]) { return; } const ngUpdateMetadata = npmPackageJson.versions[version]['ng-update']; if (!ngUpdateMetadata) { return; } const packageGroup = ngUpdateMetadata['packageGroup']; if (!packageGroup) { return; } let packageGroupNormalized: Record<string, string> = {}; if (Array.isArray(packageGroup) && !packageGroup.some((x) => typeof x != 'string')) { packageGroupNormalized = packageGroup.reduce( (acc, curr) => { acc[curr] = maybePackage; return acc; }, {} as { [name: string]: string }, ); } else if ( typeof packageGroup == 'object' && packageGroup && !Array.isArray(packageGroup) && Object.values(packageGroup).every((x) => typeof x == 'string') ) { packageGroupNormalized = packageGroup; } else { logger.warn(`packageGroup metadata of package ${npmPackageJson.name} is malformed. Ignoring.`); return; } for (const [name, value] of Object.entries(packageGroupNormalized)) { // Don't override names from the command line. // Remove packages that aren't installed. if (!packages.has(name) && allDependencies.has(name)) { packages.set(name, value as VersionRange); } } } /** * Add peer dependencies of packages on the command line to the list of packages to update. * We don't do verification of the versions here as this will be done by a later step (and can * be ignored by the --force flag). * @private */ function _addPeerDependencies( tree: Tree, packages: Map<string, VersionRange>, allDependencies: ReadonlyMap<string, VersionRange>, npmPackageJson: NpmRepositoryPackageJson, npmPackageJsonMap: Map<string, NpmRepositoryPackageJson>, logger: logging.LoggerApi, ): void { const maybePackage = packages.get(npmPackageJson.name); if (!maybePackage) { return; } const info = _buildPackageInfo(tree, packages, allDependencies, npmPackageJson, logger); const version = (info.target && info.target.version) || npmPackageJson['dist-tags'][maybePackage] || maybePackage; if (!npmPackageJson.versions[version]) { return; } const packageJson = npmPackageJson.versions[version]; const error = false; for (const [peer, range] of Object.entries(packageJson.peerDependencies || {})) { if (packages.has(peer)) { continue; } const peerPackageJson = npmPackageJsonMap.get(peer); if (peerPackageJson) { const peerInfo = _buildPackageInfo(tree, packages, allDependencies, peerPackageJson, logger); if (semver.satisfies(peerInfo.installed.version, range)) { continue; } } packages.set(peer, range as VersionRange); } if (error) { throw new SchematicsException('An error occured, see above.'); } } function _getAllDependencies(tree: Tree): Array<readonly [string, VersionRange]> { const { dependencies, devDependencies, peerDependencies } = tree.readJson( '/package.json', ) as JsonSchemaForNpmPackageJsonFiles; return [ ...(Object.entries(peerDependencies || {}) as Array<[string, VersionRange]>), ...(Object.entries(devDependencies || {}) as Array<[string, VersionRange]>), ...(Object.entries(dependencies || {}) as Array<[string, VersionRange]>), ]; } function _formatVersion(version: string | undefined) { if (version === undefined) { return undefined; } if (!version.match(/^\d{1,30}\.\d{1,30}\.\d{1,30}/)) { version += '.0'; } if (!version.match(/^\d{1,30}\.\d{1,30}\.\d{1,30}/)) { version += '.0'; } if (!semver.valid(version)) { throw new SchematicsException(`Invalid migration version: ${JSON.stringify(version)}`); } return version; } /** * Returns whether or not the given package specifier (the value string in a * `package.json` dependency) is hosted in the NPM registry. * @throws When the specifier cannot be parsed. */ function isPkgFromRegistry(name: string, specifier: string): boolean { const result = npa.resolve(name, specifier); return !!result.registry; }
{ "end_byte": 26585, "start_byte": 21002, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular/cli/src/commands/update/schematic/index.ts" }
angular-cli/packages/angular/cli/src/commands/update/schematic/index.ts_26587_30743
export default function (options: UpdateSchema): Rule { if (!options.packages) { // We cannot just return this because we need to fetch the packages from NPM still for the // help/guide to show. options.packages = []; } else { // We split every packages by commas to allow people to pass in multiple and make it an array. options.packages = options.packages.reduce((acc, curr) => { return acc.concat(curr.split(',')); }, [] as string[]); } if (options.migrateOnly && options.from) { if (options.packages.length !== 1) { throw new SchematicsException('--from requires that only a single package be passed.'); } } options.from = _formatVersion(options.from); options.to = _formatVersion(options.to); const usingYarn = options.packageManager === 'yarn'; return async (tree: Tree, context: SchematicContext) => { const logger = context.logger; const npmDeps = new Map( _getAllDependencies(tree).filter(([name, specifier]) => { try { return isPkgFromRegistry(name, specifier); } catch { logger.warn(`Package ${name} was not found on the registry. Skipping.`); return false; } }), ); const packages = _buildPackageList(options, npmDeps, logger); // Grab all package.json from the npm repository. This requires a lot of HTTP calls so we // try to parallelize as many as possible. const allPackageMetadata = await Promise.all( Array.from(npmDeps.keys()).map((depName) => getNpmPackageJson(depName, logger, { registry: options.registry, usingYarn, verbose: options.verbose, }), ), ); // Build a map of all dependencies and their packageJson. const npmPackageJsonMap = allPackageMetadata.reduce((acc, npmPackageJson) => { // If the package was not found on the registry. It could be private, so we will just // ignore. If the package was part of the list, we will error out, but will simply ignore // if it's either not requested (so just part of package.json. silently). if (!npmPackageJson.name) { if (npmPackageJson.requestedName && packages.has(npmPackageJson.requestedName)) { throw new SchematicsException( `Package ${JSON.stringify(npmPackageJson.requestedName)} was not found on the ` + 'registry. Cannot continue as this may be an error.', ); } } else { // If a name is present, it is assumed to be fully populated acc.set(npmPackageJson.name, npmPackageJson as NpmRepositoryPackageJson); } return acc; }, new Map<string, NpmRepositoryPackageJson>()); // Augment the command line package list with packageGroups and forward peer dependencies. // Each added package may uncover new package groups and peer dependencies, so we must // repeat this process until the package list stabilizes. let lastPackagesSize; do { lastPackagesSize = packages.size; npmPackageJsonMap.forEach((npmPackageJson) => { _addPackageGroup(tree, packages, npmDeps, npmPackageJson, logger); _addPeerDependencies(tree, packages, npmDeps, npmPackageJson, npmPackageJsonMap, logger); }); } while (packages.size > lastPackagesSize); // Build the PackageInfo for each module. const packageInfoMap = new Map<string, PackageInfo>(); npmPackageJsonMap.forEach((npmPackageJson) => { packageInfoMap.set( npmPackageJson.name, _buildPackageInfo(tree, packages, npmDeps, npmPackageJson, logger), ); }); // Now that we have all the information, check the flags. if (packages.size > 0) { if (options.migrateOnly && options.from && options.packages) { return; } const sublog = new logging.LevelCapLogger('validation', logger.createChild(''), 'warn'); _validateUpdatePackages(packageInfoMap, !!options.force, !!options.next, sublog); _performUpdate(tree, context, packageInfoMap, logger, !!options.migrateOnly); } else { _usageMessage(options, packageInfoMap, logger); } }; }
{ "end_byte": 30743, "start_byte": 26587, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular/cli/src/commands/update/schematic/index.ts" }
angular-cli/packages/angular/cli/src/commands/update/schematic/index_spec.ts_0_884
/** * @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 { normalize, virtualFs } from '@angular-devkit/core'; import { HostTree } from '@angular-devkit/schematics'; import { SchematicTestRunner, UnitTestTree } from '@angular-devkit/schematics/testing'; import * as semver from 'semver'; import { angularMajorCompatGuarantee } from './index'; describe('angularMajorCompatGuarantee', () => { [ '5.0.0', '5.1.0', '5.20.0', '6.0.0', '6.0.0-rc.0', '6.0.0-beta.0', '6.1.0-beta.0', '6.1.0-rc.0', '6.10.11', ].forEach((golden) => { it('works with ' + JSON.stringify(golden), () => { expect(semver.satisfies(golden, angularMajorCompatGuarantee('^5.0.0'))).toBeTruthy(); }); }); });
{ "end_byte": 884, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular/cli/src/commands/update/schematic/index_spec.ts" }
angular-cli/packages/angular/cli/src/commands/update/schematic/index_spec.ts_886_8868
describe('@schematics/update', () => { const schematicRunner = new SchematicTestRunner( '@schematics/update', require.resolve('./collection.json'), ); let host: virtualFs.test.TestHost; let appTree: UnitTestTree = new UnitTestTree(new HostTree()); beforeEach(() => { host = new virtualFs.test.TestHost({ '/package.json': `{ "name": "blah", "dependencies": { "@angular-devkit-tests/update-base": "1.0.0" } }`, }); appTree = new UnitTestTree(new HostTree(host)); }); it('ignores dependencies not hosted on the NPM registry', async () => { let newTree = new UnitTestTree( new HostTree( new virtualFs.test.TestHost({ '/package.json': `{ "name": "blah", "dependencies": { "@angular-devkit-tests/update-base": "file:update-base-1.0.0.tgz" } }`, }), ), ); newTree = await schematicRunner.runSchematic('update', undefined, newTree); const packageJson = JSON.parse(newTree.readContent('/package.json')); expect(packageJson['dependencies']['@angular-devkit-tests/update-base']).toBe( 'file:update-base-1.0.0.tgz', ); }, 45000); it('should not error with yarn 2.0 protocols', async () => { let newTree = new UnitTestTree( new HostTree( new virtualFs.test.TestHost({ '/package.json': `{ "name": "blah", "dependencies": { "src": "src@link:./src", "@angular-devkit-tests/update-base": "1.0.0" } }`, }), ), ); newTree = await schematicRunner.runSchematic( 'update', { packages: ['@angular-devkit-tests/update-base'], }, newTree, ); const { dependencies } = JSON.parse(newTree.readContent('/package.json')); expect(dependencies['@angular-devkit-tests/update-base']).toBe('1.1.0'); }); it('updates Angular as compatible with Angular N-1', async () => { // Add the basic migration package. const content = virtualFs.fileBufferToString(host.sync.read(normalize('/package.json'))); const packageJson = JSON.parse(content); const dependencies = packageJson['dependencies']; dependencies['@angular-devkit-tests/update-peer-dependencies-angular-5'] = '1.0.0'; dependencies['@angular/core'] = '5.1.0'; dependencies['rxjs'] = '5.5.0'; dependencies['zone.js'] = '0.8.26'; host.sync.write( normalize('/package.json'), virtualFs.stringToFileBuffer(JSON.stringify(packageJson)), ); const newTree = await schematicRunner.runSchematic( 'update', { packages: ['@angular/core@^6.0.0'], }, appTree, ); const newPpackageJson = JSON.parse(newTree.readContent('/package.json')); expect(newPpackageJson['dependencies']['@angular/core'][0]).toBe('6'); }, 45000); it('updates Angular as compatible with Angular N-1 (2)', async () => { // Add the basic migration package. const content = virtualFs.fileBufferToString(host.sync.read(normalize('/package.json'))); const packageJson = JSON.parse(content); const dependencies = packageJson['dependencies']; dependencies['@angular-devkit-tests/update-peer-dependencies-angular-5-2'] = '1.0.0'; dependencies['@angular/core'] = '5.1.0'; dependencies['@angular/animations'] = '5.1.0'; dependencies['@angular/common'] = '5.1.0'; dependencies['@angular/compiler'] = '5.1.0'; dependencies['@angular/compiler-cli'] = '5.1.0'; dependencies['@angular/platform-browser'] = '5.1.0'; dependencies['rxjs'] = '5.5.0'; dependencies['zone.js'] = '0.8.26'; dependencies['typescript'] = '2.4.2'; host.sync.write( normalize('/package.json'), virtualFs.stringToFileBuffer(JSON.stringify(packageJson)), ); const newTree = await schematicRunner.runSchematic( 'update', { packages: ['@angular/core@^6.0.0'], }, appTree, ); const newPackageJson = JSON.parse(newTree.readContent('/package.json')); expect(newPackageJson['dependencies']['@angular/core'][0]).toBe('6'); expect(newPackageJson['dependencies']['rxjs'][0]).toBe('6'); expect(newPackageJson['dependencies']['typescript'][0]).toBe('2'); expect(newPackageJson['dependencies']['typescript'][2]).not.toBe('4'); }, 45000); it('uses packageGroup for versioning', async () => { // Add the basic migration package. const content = virtualFs.fileBufferToString(host.sync.read(normalize('/package.json'))); const packageJson = JSON.parse(content); const dependencies = packageJson['dependencies']; dependencies['@angular-devkit-tests/update-package-group-1'] = '1.0.0'; dependencies['@angular-devkit-tests/update-package-group-2'] = '1.0.0'; host.sync.write( normalize('/package.json'), virtualFs.stringToFileBuffer(JSON.stringify(packageJson)), ); const newTree = await schematicRunner.runSchematic( 'update', { packages: ['@angular-devkit-tests/update-package-group-1'], }, appTree, ); const { dependencies: deps } = JSON.parse(newTree.readContent('/package.json')); expect(deps['@angular-devkit-tests/update-package-group-1']).toBe('1.2.0'); expect(deps['@angular-devkit-tests/update-package-group-2']).toBe('2.0.0'); }, 45000); it('can migrate only', async () => { // Add the basic migration package. const content = virtualFs.fileBufferToString(host.sync.read(normalize('/package.json'))); const packageJson = JSON.parse(content); packageJson['dependencies']['@angular-devkit-tests/update-migrations'] = '1.0.0'; host.sync.write( normalize('/package.json'), virtualFs.stringToFileBuffer(JSON.stringify(packageJson)), ); const newTree = await schematicRunner.runSchematic( 'update', { packages: ['@angular-devkit-tests/update-migrations'], migrateOnly: true, }, appTree, ); const newPackageJson = JSON.parse(newTree.readContent('/package.json')); expect(newPackageJson['dependencies']['@angular-devkit-tests/update-base']).toBe('1.0.0'); expect(newPackageJson['dependencies']['@angular-devkit-tests/update-migrations']).toBe('1.0.0'); }, 45000); it('can migrate from only', async () => { // Add the basic migration package. const content = virtualFs.fileBufferToString(host.sync.read(normalize('/package.json'))); const packageJson = JSON.parse(content); packageJson['dependencies']['@angular-devkit-tests/update-migrations'] = '1.6.0'; host.sync.write( normalize('/package.json'), virtualFs.stringToFileBuffer(JSON.stringify(packageJson)), ); const newTree = await schematicRunner.runSchematic( 'update', { packages: ['@angular-devkit-tests/update-migrations'], migrateOnly: true, from: '0.1.2', }, appTree, ); const { dependencies } = JSON.parse(newTree.readContent('/package.json')); expect(dependencies['@angular-devkit-tests/update-migrations']).toBe('1.6.0'); }, 45000); it('can install and migrate with --from (short version number)', async () => { // Add the basic migration package. const content = virtualFs.fileBufferToString(host.sync.read(normalize('/package.json'))); const packageJson = JSON.parse(content); packageJson['dependencies']['@angular-devkit-tests/update-migrations'] = '1.6.0'; host.sync.write( normalize('/package.json'), virtualFs.stringToFileBuffer(JSON.stringify(packageJson)), ); const newTree = await schematicRunner.runSchematic( 'update', { packages: ['@angular-devkit-tests/update-migrations'], migrateOnly: true, from: '0', }, appTree, ); const { dependencies } = JSON.parse(newTree.readContent('/package.json')); expect(dependencies['@angular-devkit-tests/update-migrations']).toBe('1.6.0'); }, 45000);
{ "end_byte": 8868, "start_byte": 886, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular/cli/src/commands/update/schematic/index_spec.ts" }
angular-cli/packages/angular/cli/src/commands/update/schematic/index_spec.ts_8872_11768
it('validates peer dependencies', async () => { const content = virtualFs.fileBufferToString(host.sync.read(normalize('/package.json'))); const packageJson = JSON.parse(content); const dependencies = packageJson['dependencies']; // TODO: when we start using a local npm registry for test packages, add a package that includes // a optional peer dependency and a non-optional one for this test. Use it instead of // @angular-devkit/build-angular, whose optional peerdep is @angular/localize and non-optional // are typescript and @angular/compiler-cli. dependencies['@angular-devkit/build-angular'] = '0.900.0-next.1'; host.sync.write( normalize('/package.json'), virtualFs.stringToFileBuffer(JSON.stringify(packageJson)), ); const messages: string[] = []; schematicRunner.logger.subscribe((x) => messages.push(x.message)); const hasPeerdepMsg = (dep: string) => messages.some((str) => str.includes(`missing peer dependency of "${dep}"`)); await schematicRunner.runSchematic( 'update', { packages: ['@angular-devkit/build-angular'], next: true, }, appTree, ); expect(hasPeerdepMsg('@angular/compiler-cli')).toBeTruthy(); expect(hasPeerdepMsg('typescript')).toBeTruthy(); expect(hasPeerdepMsg('@angular/localize')).toBeFalsy(); }, 45000); it('does not remove newline at the end of package.json', async () => { const newlineStyles = ['\n', '\r\n']; for (const newline of newlineStyles) { const packageJsonContent = `{ "name": "blah", "dependencies": { "@angular-devkit-tests/update-base": "1.0.0" } }${newline}`; const inputTree = new UnitTestTree( new HostTree( new virtualFs.test.TestHost({ '/package.json': packageJsonContent, }), ), ); const resultTree = await schematicRunner.runSchematic( 'update', { packages: ['@angular-devkit-tests/update-base'] }, inputTree, ); const resultTreeContent = resultTree.readContent('/package.json'); expect(resultTreeContent.endsWith(newline)).toBeTrue(); } }); it('does not add a newline at the end of package.json', async () => { const packageJsonContent = `{ "name": "blah", "dependencies": { "@angular-devkit-tests/update-base": "1.0.0" } }`; const inputTree = new UnitTestTree( new HostTree( new virtualFs.test.TestHost({ '/package.json': packageJsonContent, }), ), ); const resultTree = await schematicRunner.runSchematic( 'update', { packages: ['@angular-devkit-tests/update-base'] }, inputTree, ); const resultTreeContent = resultTree.readContent('/package.json'); expect(resultTreeContent.endsWith('}')).toBeTrue(); }); });
{ "end_byte": 11768, "start_byte": 8872, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular/cli/src/commands/update/schematic/index_spec.ts" }
angular-cli/packages/angular/cli/src/commands/config/cli.ts_0_5488
/** * @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 { JsonValue } from '@angular-devkit/core'; import { randomUUID } from 'crypto'; import { join } from 'path'; import { Argv } from 'yargs'; import { CommandModule, CommandModuleError, CommandModuleImplementation, Options, } from '../../command-builder/command-module'; import { getWorkspaceRaw, validateWorkspace } from '../../utilities/config'; import { JSONFile, parseJson } from '../../utilities/json-file'; interface ConfigCommandArgs { 'json-path'?: string; value?: string; global?: boolean; } export default class ConfigCommandModule extends CommandModule<ConfigCommandArgs> implements CommandModuleImplementation<ConfigCommandArgs> { command = 'config [json-path] [value]'; describe = 'Retrieves or sets Angular configuration values in the angular.json file for the workspace.'; longDescriptionPath = join(__dirname, 'long-description.md'); builder(localYargs: Argv): Argv<ConfigCommandArgs> { return localYargs .positional('json-path', { description: `The configuration key to set or query, in JSON path format. ` + `For example: "a[3].foo.bar[2]". If no new value is provided, returns the current value of this key.`, type: 'string', }) .positional('value', { description: 'If provided, a new value for the given configuration key.', type: 'string', }) .option('global', { description: `Access the global configuration in the caller's home directory.`, alias: ['g'], type: 'boolean', default: false, }) .strict(); } async run(options: Options<ConfigCommandArgs>): Promise<number | void> { const level = options.global ? 'global' : 'local'; const [config] = await getWorkspaceRaw(level); if (options.value == undefined) { if (!config) { this.context.logger.error('No config found.'); return 1; } return this.get(config, options); } else { return this.set(options); } } private get(jsonFile: JSONFile, options: Options<ConfigCommandArgs>): number { const { logger } = this.context; const value = options.jsonPath ? jsonFile.get(parseJsonPath(options.jsonPath)) : jsonFile.content; if (value === undefined) { logger.error('Value cannot be found.'); return 1; } else if (typeof value === 'string') { logger.info(value); } else { logger.info(JSON.stringify(value, null, 2)); } return 0; } private async set(options: Options<ConfigCommandArgs>): Promise<number | void> { if (!options.jsonPath?.trim()) { throw new CommandModuleError('Invalid Path.'); } const [config, configPath] = await getWorkspaceRaw(options.global ? 'global' : 'local'); const { logger } = this.context; if (!config || !configPath) { throw new CommandModuleError('Confguration file cannot be found.'); } const normalizeUUIDValue = (v: string | undefined) => (v === '' ? randomUUID() : `${v}`); const value = options.jsonPath === 'cli.analyticsSharing.uuid' ? normalizeUUIDValue(options.value) : options.value; const modified = config.modify(parseJsonPath(options.jsonPath), normalizeValue(value)); if (!modified) { logger.error('Value cannot be found.'); return 1; } await validateWorkspace(parseJson(config.content), options.global ?? false); config.save(); return 0; } } /** * Splits a JSON path string into fragments. Fragments can be used to get the value referenced * by the path. For example, a path of "a[3].foo.bar[2]" would give you a fragment array of * ["a", 3, "foo", "bar", 2]. * @param path The JSON string to parse. * @returns {(string|number)[]} The fragments for the string. * @private */ function parseJsonPath(path: string): (string | number)[] { const fragments = (path || '').split(/\./g); const result: (string | number)[] = []; while (fragments.length > 0) { const fragment = fragments.shift(); if (fragment == undefined) { break; } const match = fragment.match(/([^[]+)((\[.*\])*)/); if (!match) { throw new CommandModuleError('Invalid JSON path.'); } result.push(match[1]); if (match[2]) { const indices = match[2] .slice(1, -1) .split('][') .map((x) => (/^\d$/.test(x) ? +x : x.replace(/"|'/g, ''))); result.push(...indices); } } return result.filter((fragment) => fragment != null); } function normalizeValue(value: string | undefined | boolean | number): JsonValue | undefined { const valueString = `${value}`.trim(); switch (valueString) { case 'true': return true; case 'false': return false; case 'null': return null; case 'undefined': return undefined; } if (isFinite(+valueString)) { return +valueString; } try { // We use `JSON.parse` instead of `parseJson` because the latter will parse UUIDs // and convert them into a numberic entities. // Example: 73b61974-182c-48e4-b4c6-30ddf08c5c98 -> 73. // These values should never contain comments, therefore using `JSON.parse` is safe. return JSON.parse(valueString) as JsonValue; } catch { return value; } }
{ "end_byte": 5488, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular/cli/src/commands/config/cli.ts" }
angular-cli/packages/angular/cli/src/commands/config/long-description.md_0_640
A workspace has a single CLI configuration file, `angular.json`, at the top level. The `projects` object contains a configuration object for each project in the workspace. You can edit the configuration directly in a code editor, or indirectly on the command line using this command. The configurable property names match command option names, except that in the configuration file, all names must use camelCase, while on the command line options can be given dash-case. For further details, see [Workspace Configuration](reference/configs/workspace-config). For configuration of CLI usage analytics, see [ng analytics](cli/analytics).
{ "end_byte": 640, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular/cli/src/commands/config/long-description.md" }
angular-cli/packages/angular/cli/src/commands/deploy/cli.ts_0_1325
/** * @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 { join } from 'node:path'; import { MissingTargetChoice } from '../../command-builder/architect-base-command-module'; import { ArchitectCommandModule } from '../../command-builder/architect-command-module'; import { CommandModuleImplementation } from '../../command-builder/command-module'; export default class DeployCommandModule extends ArchitectCommandModule implements CommandModuleImplementation { // The below choices should be kept in sync with the list in https://angular.dev/tools/cli/deployment override missingTargetChoices: MissingTargetChoice[] = [ { name: 'Amazon S3', value: '@jefiozie/ngx-aws-deploy', }, { name: 'Firebase', value: '@angular/fire', }, { name: 'Netlify', value: '@netlify-builder/deploy', }, { name: 'GitHub Pages', value: 'angular-cli-ghpages', }, ]; multiTarget = false; command = 'deploy [project]'; longDescriptionPath = join(__dirname, 'long-description.md'); describe = 'Invokes the deploy builder for a specified project or for the default project in the workspace.'; }
{ "end_byte": 1325, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular/cli/src/commands/deploy/cli.ts" }
angular-cli/packages/angular/cli/src/commands/deploy/long-description.md_0_684
The command takes an optional project name, as specified in the `projects` section of the `angular.json` workspace configuration file. When a project name is not supplied, executes the `deploy` builder for the default project. To use the `ng deploy` command, use `ng add` to add a package that implements deployment capabilities to your favorite platform. Adding the package automatically updates your workspace configuration, adding a deployment [CLI builder](tools/cli/cli-builder). For example: ```json "projects": { "my-project": { ... "architect": { ... "deploy": { "builder": "@angular/fire:deploy", "options": {} } } } } ```
{ "end_byte": 684, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular/cli/src/commands/deploy/long-description.md" }
angular-cli/packages/angular/cli/src/commands/completion/cli.ts_0_2412
/** * @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 { join } from 'path'; import yargs, { Argv } from 'yargs'; import { CommandModule, CommandModuleImplementation } from '../../command-builder/command-module'; import { addCommandModuleToYargs } from '../../command-builder/utilities/command'; import { colors } from '../../utilities/color'; import { hasGlobalCliInstall, initializeAutocomplete } from '../../utilities/completion'; import { assertIsError } from '../../utilities/error'; export default class CompletionCommandModule extends CommandModule implements CommandModuleImplementation { command = 'completion'; describe = 'Set up Angular CLI autocompletion for your terminal.'; longDescriptionPath = join(__dirname, 'long-description.md'); builder(localYargs: Argv): Argv { return addCommandModuleToYargs(localYargs, CompletionScriptCommandModule, this.context); } async run(): Promise<number> { let rcFile: string; try { rcFile = await initializeAutocomplete(); } catch (err) { assertIsError(err); this.context.logger.error(err.message); return 1; } this.context.logger.info( ` Appended \`source <(ng completion script)\` to \`${rcFile}\`. Restart your terminal or run the following to autocomplete \`ng\` commands: ${colors.yellow('source <(ng completion script)')} `.trim(), ); if ((await hasGlobalCliInstall()) === false) { this.context.logger.warn( 'Setup completed successfully, but there does not seem to be a global install of the' + ' Angular CLI. For autocompletion to work, the CLI will need to be on your `$PATH`, which' + ' is typically done with the `-g` flag in `npm install -g @angular/cli`.' + '\n\n' + 'For more information, see https://angular.dev/cli/completion#global-install', ); } return 0; } } class CompletionScriptCommandModule extends CommandModule implements CommandModuleImplementation { command = 'script'; describe = 'Generate a bash and zsh real-time type-ahead autocompletion script.'; longDescriptionPath = undefined; builder(localYargs: Argv): Argv { return localYargs; } run(): void { yargs.showCompletionScript(); } }
{ "end_byte": 2412, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular/cli/src/commands/completion/cli.ts" }
angular-cli/packages/angular/cli/src/commands/completion/long-description.md_0_3008
Setting up autocompletion configures your terminal, so pressing the `<TAB>` key while in the middle of typing will display various commands and options available to you. This makes it very easy to discover and use CLI commands without lots of memorization. ![A demo of Angular CLI autocompletion in a terminal. The user types several partial `ng` commands, using autocompletion to finish several arguments and list contextual options. ](assets/images/guide/cli/completion.gif) ## Automated setup The CLI should prompt and ask to set up autocompletion for you the first time you use it (v14+). Simply answer "Yes" and the CLI will take care of the rest. ``` $ ng serve ? Would you like to enable autocompletion? This will set up your terminal so pressing TAB while typing Angular CLI commands will show possible options and autocomplete arguments. (Enabling autocompletion will modify configuration files in your home directory.) Yes Appended `source <(ng completion script)` to `/home/my-username/.bashrc`. Restart your terminal or run: source <(ng completion script) to autocomplete `ng` commands. # Serve output... ``` If you already refused the prompt, it won't ask again. But you can run `ng completion` to do the same thing automatically. This modifies your terminal environment to load Angular CLI autocompletion, but can't update your current terminal session. Either restart it or run `source <(ng completion script)` directly to enable autocompletion in your current session. Test it out by typing `ng ser<TAB>` and it should autocomplete to `ng serve`. Ambiguous arguments will show all possible options and their documentation, such as `ng generate <TAB>`. ## Manual setup Some users may have highly customized terminal setups, possibly with configuration files checked into source control with an opinionated structure. `ng completion` only ever appends Angular's setup to an existing configuration file for your current shell, or creates one if none exists. If you want more control over exactly where this configuration lives, you can manually set it up by having your shell run at startup: ```bash source <(ng completion script) ``` This is equivalent to what `ng completion` will automatically set up, and gives power users more flexibility in their environments when desired. ## Platform support Angular CLI supports autocompletion for the Bash and Zsh shells on MacOS and Linux operating systems. On Windows, Git Bash and [Windows Subsystem for Linux](https://docs.microsoft.com/en-us/windows/wsl/) using Bash or Zsh are supported. ## Global install Autocompletion works by configuring your terminal to invoke the Angular CLI on startup to load the setup script. This means the terminal must be able to find and execute the Angular CLI, typically through a global install that places the binary on the user's `$PATH`. If you get `command not found: ng`, make sure the CLI is installed globally which you can do with the `-g` flag: ```bash npm install -g @angular/cli ```
{ "end_byte": 3008, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular/cli/src/commands/completion/long-description.md" }
angular-cli/packages/angular/cli/src/commands/extract-i18n/cli.ts_0_2070
/** * @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 { workspaces } from '@angular-devkit/core'; import { createRequire } from 'node:module'; import { join } from 'node:path'; import { ArchitectCommandModule } from '../../command-builder/architect-command-module'; import { CommandModuleImplementation } from '../../command-builder/command-module'; export default class ExtractI18nCommandModule extends ArchitectCommandModule implements CommandModuleImplementation { multiTarget = false; command = 'extract-i18n [project]'; describe = 'Extracts i18n messages from source code.'; longDescriptionPath?: string | undefined; override async findDefaultBuilderName( project: workspaces.ProjectDefinition, ): Promise<string | undefined> { // Only application type projects have a default i18n extraction target if (project.extensions['projectType'] !== 'application') { return; } const buildTarget = project.targets.get('build'); if (!buildTarget) { // No default if there is no build target return; } // Provide a default based on the defined builder for the 'build' target switch (buildTarget.builder) { case '@angular-devkit/build-angular:application': case '@angular-devkit/build-angular:browser-esbuild': case '@angular-devkit/build-angular:browser': return '@angular-devkit/build-angular:extract-i18n'; case '@angular/build:application': return '@angular/build:extract-i18n'; } // For other builders, check for `@angular-devkit/build-angular` and use if found. // This package is safer to use since it supports both application builder types. try { const projectRequire = createRequire(join(this.context.root, project.root) + '/'); projectRequire.resolve('@angular-devkit/build-angular'); return '@angular-devkit/build-angular:extract-i18n'; } catch {} } }
{ "end_byte": 2070, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular/cli/src/commands/extract-i18n/cli.ts" }
angular-cli/packages/angular/cli/src/commands/add/cli.ts_0_4479
/** * @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 { NodePackageDoesNotSupportSchematics } from '@angular-devkit/schematics/tools'; import { Listr, color, figures } from 'listr2'; import { createRequire } from 'module'; import assert from 'node:assert'; import npa from 'npm-package-arg'; import { dirname, join } from 'path'; import { Range, compare, intersects, prerelease, satisfies, valid } from 'semver'; import { Argv } from 'yargs'; import { PackageManager } from '../../../lib/config/workspace-schema'; import { CommandModuleImplementation, Options, OtherOptions, } from '../../command-builder/command-module'; import { SchematicsCommandArgs, SchematicsCommandModule, } from '../../command-builder/schematics-command-module'; import { assertIsError } from '../../utilities/error'; import { NgAddSaveDependency, PackageManifest, fetchPackageManifest, fetchPackageMetadata, } from '../../utilities/package-metadata'; import { isTTY } from '../../utilities/tty'; import { VERSION } from '../../utilities/version'; class CommandError extends Error {} interface AddCommandArgs extends SchematicsCommandArgs { collection: string; verbose?: boolean; registry?: string; 'skip-confirmation'?: boolean; } interface AddCommandTaskContext { packageIdentifier: npa.Result; usingYarn?: boolean; savePackage?: NgAddSaveDependency; collectionName?: string; executeSchematic: AddCommandModule['executeSchematic']; hasMismatchedPeer: AddCommandModule['hasMismatchedPeer']; } /** * The set of packages that should have certain versions excluded from consideration * when attempting to find a compatible version for a package. * The key is a package name and the value is a SemVer range of versions to exclude. */ const packageVersionExclusions: Record<string, string | Range> = { // @angular/[email protected] and earlier versions as well as @angular/[email protected] prereleases do not have peer dependencies setup. '@angular/localize': '<10.0.0', // @angular/[email protected] versions have unbounded peer dependency ranges (>=7.0.0). '@angular/material': '7.x', }; export default class AddCommandModule extends SchematicsCommandModule implements CommandModuleImplementation<AddCommandArgs> { command = 'add <collection>'; describe = 'Adds support for an external library to your project.'; longDescriptionPath = join(__dirname, 'long-description.md'); protected override allowPrivateSchematics = true; private readonly schematicName = 'ng-add'; private rootRequire = createRequire(this.context.root + '/'); override async builder(argv: Argv): Promise<Argv<AddCommandArgs>> { const localYargs = (await super.builder(argv)) .positional('collection', { description: 'The package to be added.', type: 'string', demandOption: true, }) .option('registry', { description: 'The NPM registry to use.', type: 'string' }) .option('verbose', { description: 'Display additional details about internal operations during execution.', type: 'boolean', default: false, }) .option('skip-confirmation', { description: 'Skip asking a confirmation prompt before installing and executing the package. ' + 'Ensure package name is correct prior to using this option.', type: 'boolean', default: false, }) // Prior to downloading we don't know the full schema and therefore we cannot be strict on the options. // Possibly in the future update the logic to use the following syntax: // `ng add @angular/localize -- --package-options`. .strict(false); const collectionName = await this.getCollectionName(); const workflow = this.getOrCreateWorkflowForBuilder(collectionName); try { const collection = workflow.engine.createCollection(collectionName); const options = await this.getSchematicOptions(collection, this.schematicName, workflow); return this.addSchemaOptionsToCommand(localYargs, options); } catch (error) { // During `ng add` prior to the downloading of the package // we are not able to resolve and create a collection. // Or when the collection value is a path to a tarball. } return localYargs; } // eslint-disable-next-line max-lines-per-function
{ "end_byte": 4479, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular/cli/src/commands/add/cli.ts" }
angular-cli/packages/angular/cli/src/commands/add/cli.ts_4482_14673
async run(options: Options<AddCommandArgs> & OtherOptions): Promise<number | void> { const { logger, packageManager } = this.context; const { verbose, registry, collection, skipConfirmation } = options; let packageIdentifier; try { packageIdentifier = npa(collection); } catch (e) { assertIsError(e); logger.error(e.message); return 1; } if ( packageIdentifier.name && packageIdentifier.registry && this.isPackageInstalled(packageIdentifier.name) ) { const validVersion = await this.isProjectVersionValid(packageIdentifier); if (validVersion) { // Already installed so just run schematic logger.info('Skipping installation: Package already installed'); return this.executeSchematic({ ...options, collection: packageIdentifier.name }); } } const taskContext: AddCommandTaskContext = { packageIdentifier, executeSchematic: this.executeSchematic.bind(this), hasMismatchedPeer: this.hasMismatchedPeer.bind(this), }; const tasks = new Listr<AddCommandTaskContext>([ { title: 'Determining Package Manager', task(context, task) { context.usingYarn = packageManager.name === PackageManager.Yarn; task.output = `Using package manager: ${color.dim(packageManager.name)}`; }, rendererOptions: { persistentOutput: true }, }, { title: 'Searching for compatible package version', enabled: packageIdentifier.type === 'range' && packageIdentifier.rawSpec === '*', async task(context, task) { assert( context.packageIdentifier.name, 'Registry package identifiers should always have a name.', ); // only package name provided; search for viable version // plus special cases for packages that did not have peer deps setup let packageMetadata; try { packageMetadata = await fetchPackageMetadata(context.packageIdentifier.name, logger, { registry, usingYarn: context.usingYarn, verbose, }); } catch (e) { assertIsError(e); throw new CommandError( `Unable to load package information from registry: ${e.message}`, ); } // Start with the version tagged as `latest` if it exists const latestManifest = packageMetadata.tags['latest']; if (latestManifest) { context.packageIdentifier = npa.resolve(latestManifest.name, latestManifest.version); } // Adjust the version based on name and peer dependencies if ( latestManifest?.peerDependencies && Object.keys(latestManifest.peerDependencies).length === 0 ) { task.output = `Found compatible package version: ${color.blue(latestManifest.version)}.`; } else if (!latestManifest || (await context.hasMismatchedPeer(latestManifest))) { // 'latest' is invalid so search for most recent matching package // Allow prelease versions if the CLI itself is a prerelease const allowPrereleases = prerelease(VERSION.full); const versionExclusions = packageVersionExclusions[packageMetadata.name]; const versionManifests = Object.values(packageMetadata.versions).filter( (value: PackageManifest) => { // Prerelease versions are not stable and should not be considered by default if (!allowPrereleases && prerelease(value.version)) { return false; } // Deprecated versions should not be used or considered if (value.deprecated) { return false; } // Excluded package versions should not be considered if ( versionExclusions && satisfies(value.version, versionExclusions, { includePrerelease: true }) ) { return false; } return true; }, ); // Sort in reverse SemVer order so that the newest compatible version is chosen versionManifests.sort((a, b) => compare(b.version, a.version, true)); let found = false; for (const versionManifest of versionManifests) { const mismatch = await context.hasMismatchedPeer(versionManifest); if (mismatch) { continue; } context.packageIdentifier = npa.resolve( versionManifest.name, versionManifest.version, ); found = true; } if (!found) { task.output = "Unable to find compatible package. Using 'latest' tag."; } else { task.output = `Found compatible package version: ${color.blue(context.packageIdentifier.toString())}.`; } } else { task.output = `Found compatible package version: ${color.blue(context.packageIdentifier.toString())}.`; } }, rendererOptions: { persistentOutput: true }, }, { title: 'Loading package information from registry', async task(context, task) { let manifest; try { manifest = await fetchPackageManifest(context.packageIdentifier.toString(), logger, { registry, verbose, usingYarn: context.usingYarn, }); } catch (e) { assertIsError(e); throw new CommandError( `Unable to fetch package information for '${context.packageIdentifier}': ${e.message}`, ); } context.savePackage = manifest['ng-add']?.save; context.collectionName = manifest.name; if (await context.hasMismatchedPeer(manifest)) { task.output = color.yellow( figures.warning + ' Package has unmet peer dependencies. Adding the package may not succeed.', ); } }, rendererOptions: { persistentOutput: true }, }, { title: 'Confirming installation', enabled: !skipConfirmation, async task(context, task) { if (!isTTY()) { task.output = `'--skip-confirmation' can be used to bypass installation confirmation. ` + `Ensure package name is correct prior to '--skip-confirmation' option usage.`; throw new CommandError('No terminal detected'); } const { ListrInquirerPromptAdapter } = await import('@listr2/prompt-adapter-inquirer'); const { confirm } = await import('@inquirer/prompts'); const shouldProceed = await task.prompt(ListrInquirerPromptAdapter).run(confirm, { message: `The package ${color.blue(context.packageIdentifier.toString())} will be installed and executed.\n` + 'Would you like to proceed?', default: true, theme: { prefix: '' }, }); if (!shouldProceed) { throw new CommandError('Command aborted'); } }, rendererOptions: { persistentOutput: true }, }, { async task(context, task) { // Only show if installation will actually occur task.title = 'Installing package'; if (context.savePackage === false) { task.title += ' in temporary location'; // Temporary packages are located in a different directory // Hence we need to resolve them using the temp path const { success, tempNodeModules } = await packageManager.installTemp( context.packageIdentifier.toString(), registry ? [`--registry="${registry}"`] : undefined, ); const tempRequire = createRequire(tempNodeModules + '/'); assert(context.collectionName, 'Collection name should always be available'); const resolvedCollectionPath = tempRequire.resolve( join(context.collectionName, 'package.json'), ); if (!success) { throw new CommandError('Unable to install package'); } context.collectionName = dirname(resolvedCollectionPath); } else { const success = await packageManager.install( context.packageIdentifier.toString(), context.savePackage, registry ? [`--registry="${registry}"`] : undefined, undefined, ); if (!success) { throw new CommandError('Unable to install package'); } } }, rendererOptions: { bottomBar: Infinity }, }, // TODO: Rework schematic execution as a task and insert here ]); try { const result = await tasks.run(taskContext); assert(result.collectionName, 'Collection name should always be available'); return this.executeSchematic({ ...options, collection: result.collectionName }); } catch (e) { if (e instanceof CommandError) { return 1; } throw e; } } private async isProjectVersionValid(packageIdentifier: npa.Result): Promise<boolean> { if (!packageIdentifier.name) { return false; } const installedVersion = await this.findProjectVersion(packageIdentifier.name); if (!installedVersion) { return false; } if (packageIdentifier.rawSpec === '*') { return true; } if ( packageIdentifier.type === 'range' && packageIdentifier.fetchSpec && packageIdentifier.fetchSpec !== '*' ) { return satisfies(installedVersion, packageIdentifier.fetchSpec); } if (packageIdentifier.type === 'version') { const v1 = valid(packageIdentifier.fetchSpec); const v2 = valid(installedVersion); return v1 !== null && v1 === v2; } return false; }
{ "end_byte": 14673, "start_byte": 4482, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular/cli/src/commands/add/cli.ts" }
angular-cli/packages/angular/cli/src/commands/add/cli.ts_14677_18448
private async getCollectionName(): Promise<string> { let [, collectionName] = this.context.args.positional; // The CLI argument may specify also a version, like `ng add @my/[email protected]`, // but here we need only the name of the package, like `@my/lib` try { const packageIdentifier = npa(collectionName); collectionName = packageIdentifier.name ?? collectionName; } catch (e) { assertIsError(e); this.context.logger.error(e.message); } return collectionName; } private isPackageInstalled(name: string): boolean { try { this.rootRequire.resolve(join(name, 'package.json')); return true; } catch (e) { assertIsError(e); if (e.code !== 'MODULE_NOT_FOUND') { throw e; } } return false; } private async executeSchematic( options: Options<AddCommandArgs> & OtherOptions, ): Promise<number | void> { try { const { verbose, skipConfirmation, interactive, force, dryRun, registry, defaults, collection: collectionName, ...schematicOptions } = options; return await this.runSchematic({ schematicOptions, schematicName: this.schematicName, collectionName, executionOptions: { interactive, force, dryRun, defaults, packageRegistry: registry, }, }); } catch (e) { if (e instanceof NodePackageDoesNotSupportSchematics) { this.context.logger.error( 'The package that you are trying to add does not support schematics.' + 'You can try using a different version of the package or contact the package author to add ng-add support.', ); return 1; } throw e; } } private async findProjectVersion(name: string): Promise<string | null> { const { logger, root } = this.context; let installedPackage; try { installedPackage = this.rootRequire.resolve(join(name, 'package.json')); } catch {} if (installedPackage) { try { const installed = await fetchPackageManifest(dirname(installedPackage), logger); return installed.version; } catch {} } let projectManifest; try { projectManifest = await fetchPackageManifest(root, logger); } catch {} if (projectManifest) { const version = projectManifest.dependencies?.[name] || projectManifest.devDependencies?.[name]; if (version) { return version; } } return null; } private async hasMismatchedPeer(manifest: PackageManifest): Promise<boolean> { for (const peer in manifest.peerDependencies) { let peerIdentifier; try { peerIdentifier = npa.resolve(peer, manifest.peerDependencies[peer]); } catch { this.context.logger.warn(`Invalid peer dependency ${peer} found in package.`); continue; } if (peerIdentifier.type === 'version' || peerIdentifier.type === 'range') { try { const version = await this.findProjectVersion(peer); if (!version) { continue; } const options = { includePrerelease: true }; if ( !intersects(version, peerIdentifier.rawSpec, options) && !satisfies(version, peerIdentifier.rawSpec, options) ) { return true; } } catch { // Not found or invalid so ignore continue; } } else { // type === 'tag' | 'file' | 'directory' | 'remote' | 'git' // Cannot accurately compare these as the tag/location may have changed since install } } return false; } }
{ "end_byte": 18448, "start_byte": 14677, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular/cli/src/commands/add/cli.ts" }
angular-cli/packages/angular/cli/src/commands/add/long-description.md_0_295
Adds the npm package for a published library to your workspace, and configures the project in the current working directory to use that library, as specified by the library's schematic. For example, adding `@angular/pwa` configures your project for PWA support: ```bash ng add @angular/pwa ```
{ "end_byte": 295, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular/cli/src/commands/add/long-description.md" }
angular-cli/packages/angular/cli/src/commands/version/cli.ts_0_5744
/** * @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 nodeModule from 'node:module'; import { resolve } from 'node:path'; import { Argv } from 'yargs'; import { CommandModule, CommandModuleImplementation } from '../../command-builder/command-module'; import { colors } from '../../utilities/color'; import { RootCommands } from '../command-config'; interface PartialPackageInfo { name: string; version: string; dependencies?: Record<string, string>; devDependencies?: Record<string, string>; } /** * Major versions of Node.js that are officially supported by Angular. */ const SUPPORTED_NODE_MAJORS = [18, 20, 22]; const PACKAGE_PATTERNS = [ /^@angular\/.*/, /^@angular-devkit\/.*/, /^@ngtools\/.*/, /^@schematics\/.*/, /^rxjs$/, /^typescript$/, /^ng-packagr$/, /^webpack$/, /^zone\.js$/, ]; export default class VersionCommandModule extends CommandModule implements CommandModuleImplementation { command = 'version'; aliases = RootCommands['version'].aliases; describe = 'Outputs Angular CLI version.'; longDescriptionPath?: string | undefined; builder(localYargs: Argv): Argv { return localYargs; } async run(): Promise<void> { const { packageManager, logger, root } = this.context; const localRequire = nodeModule.createRequire(resolve(__filename, '../../../')); // Trailing slash is used to allow the path to be treated as a directory const workspaceRequire = nodeModule.createRequire(root + '/'); const cliPackage: PartialPackageInfo = localRequire('./package.json'); let workspacePackage: PartialPackageInfo | undefined; try { workspacePackage = workspaceRequire('./package.json'); } catch {} const [nodeMajor] = process.versions.node.split('.').map((part) => Number(part)); const unsupportedNodeVersion = !SUPPORTED_NODE_MAJORS.includes(nodeMajor); const packageNames = new Set( Object.keys({ ...cliPackage.dependencies, ...cliPackage.devDependencies, ...workspacePackage?.dependencies, ...workspacePackage?.devDependencies, }), ); const versions: Record<string, string> = {}; for (const name of packageNames) { if (PACKAGE_PATTERNS.some((p) => p.test(name))) { versions[name] = this.getVersion(name, workspaceRequire, localRequire); } } const ngCliVersion = cliPackage.version; let angularCoreVersion = ''; const angularSameAsCore: string[] = []; if (workspacePackage) { // Filter all angular versions that are the same as core. angularCoreVersion = versions['@angular/core']; if (angularCoreVersion) { for (const [name, version] of Object.entries(versions)) { if (version === angularCoreVersion && name.startsWith('@angular/')) { angularSameAsCore.push(name.replace(/^@angular\//, '')); delete versions[name]; } } // Make sure we list them in alphabetical order. angularSameAsCore.sort(); } } const namePad = ' '.repeat( Object.keys(versions).sort((a, b) => b.length - a.length)[0].length + 3, ); const asciiArt = ` _ _ ____ _ ___ / \\ _ __ __ _ _ _| | __ _ _ __ / ___| | |_ _| / △ \\ | '_ \\ / _\` | | | | |/ _\` | '__| | | | | | | / ___ \\| | | | (_| | |_| | | (_| | | | |___| |___ | | /_/ \\_\\_| |_|\\__, |\\__,_|_|\\__,_|_| \\____|_____|___| |___/ ` .split('\n') .map((x) => colors.red(x)) .join('\n'); logger.info(asciiArt); logger.info( ` Angular CLI: ${ngCliVersion} Node: ${process.versions.node}${unsupportedNodeVersion ? ' (Unsupported)' : ''} Package Manager: ${packageManager.name} ${packageManager.version ?? '<error>'} OS: ${process.platform} ${process.arch} Angular: ${angularCoreVersion} ... ${angularSameAsCore .reduce<string[]>((acc, name) => { // Perform a simple word wrap around 60. if (acc.length == 0) { return [name]; } const line = acc[acc.length - 1] + ', ' + name; if (line.length > 60) { acc.push(name); } else { acc[acc.length - 1] = line; } return acc; }, []) .join('\n... ')} Package${namePad.slice(7)}Version -------${namePad.replace(/ /g, '-')}------------------ ${Object.keys(versions) .map((module) => `${module}${namePad.slice(module.length)}${versions[module]}`) .sort() .join('\n')} `.replace(/^ {6}/gm, ''), ); if (unsupportedNodeVersion) { logger.warn( `Warning: The current version of Node (${process.versions.node}) is not supported by Angular.`, ); } } private getVersion( moduleName: string, workspaceRequire: NodeRequire, localRequire: NodeRequire, ): string { let packageInfo: PartialPackageInfo | undefined; let cliOnly = false; // Try to find the package in the workspace try { packageInfo = workspaceRequire(`${moduleName}/package.json`); } catch {} // If not found, try to find within the CLI if (!packageInfo) { try { packageInfo = localRequire(`${moduleName}/package.json`); cliOnly = true; } catch {} } // If found, attempt to get the version if (packageInfo) { try { return packageInfo.version + (cliOnly ? ' (cli-only)' : ''); } catch {} } return '<error>'; } }
{ "end_byte": 5744, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular/cli/src/commands/version/cli.ts" }
angular-cli/packages/angular/cli/src/commands/new/cli.ts_0_3431
/** * @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 { join } from 'node:path'; import { Argv } from 'yargs'; import { CommandModuleImplementation, CommandScope, Options, OtherOptions, } from '../../command-builder/command-module'; import { DEFAULT_SCHEMATICS_COLLECTION, SchematicsCommandArgs, SchematicsCommandModule, } from '../../command-builder/schematics-command-module'; import { VERSION } from '../../utilities/version'; import { RootCommands } from '../command-config'; interface NewCommandArgs extends SchematicsCommandArgs { collection?: string; } export default class NewCommandModule extends SchematicsCommandModule implements CommandModuleImplementation<NewCommandArgs> { private readonly schematicName = 'ng-new'; override scope = CommandScope.Out; protected override allowPrivateSchematics = true; command = 'new [name]'; aliases = RootCommands['new'].aliases; describe = 'Creates a new Angular workspace.'; longDescriptionPath = join(__dirname, 'long-description.md'); override async builder(argv: Argv): Promise<Argv<NewCommandArgs>> { const localYargs = (await super.builder(argv)).option('collection', { alias: 'c', describe: 'A collection of schematics to use in generating the initial application.', type: 'string', }); const { options: { collection: collectionNameFromArgs }, } = this.context.args; const collectionName = typeof collectionNameFromArgs === 'string' ? collectionNameFromArgs : await this.getCollectionFromConfig(); const workflow = this.getOrCreateWorkflowForBuilder(collectionName); const collection = workflow.engine.createCollection(collectionName); const options = await this.getSchematicOptions(collection, this.schematicName, workflow); return this.addSchemaOptionsToCommand(localYargs, options); } async run(options: Options<NewCommandArgs> & OtherOptions): Promise<number | void> { // Register the version of the CLI in the registry. const collectionName = options.collection ?? (await this.getCollectionFromConfig()); const { dryRun, force, interactive, defaults, collection, ...schematicOptions } = options; const workflow = await this.getOrCreateWorkflowForExecution(collectionName, { dryRun, force, interactive, defaults, }); workflow.registry.addSmartDefaultProvider('ng-cli-version', () => VERSION.full); return this.runSchematic({ collectionName, schematicName: this.schematicName, schematicOptions, executionOptions: { dryRun, force, interactive, defaults, }, }); } /** Find a collection from config that has an `ng-new` schematic. */ private async getCollectionFromConfig(): Promise<string> { for (const collectionName of await this.getSchematicCollections()) { const workflow = this.getOrCreateWorkflowForBuilder(collectionName); const collection = workflow.engine.createCollection(collectionName); const schematicsInCollection = collection.description.schematics; if (Object.keys(schematicsInCollection).includes(this.schematicName)) { return collectionName; } } return DEFAULT_SCHEMATICS_COLLECTION; } }
{ "end_byte": 3431, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular/cli/src/commands/new/cli.ts" }
angular-cli/packages/angular/cli/src/commands/new/long-description.md_0_1133
Creates and initializes a new Angular application that is the default project for a new workspace. Provides interactive prompts for optional configuration, such as adding routing support. All prompts can safely be allowed to default. - The new workspace folder is given the specified project name, and contains configuration files at the top level. - By default, the files for a new initial application (with the same name as the workspace) are placed in the `src/` subfolder. - The new application's configuration appears in the `projects` section of the `angular.json` workspace configuration file, under its project name. - Subsequent applications that you generate in the workspace reside in the `projects/` subfolder. If you plan to have multiple applications in the workspace, you can create an empty workspace by using the `--no-create-application` option. You can then use `ng generate application` to create an initial application. This allows a workspace name different from the initial app name, and ensures that all applications reside in the `/projects` subfolder, matching the structure of the configuration file.
{ "end_byte": 1133, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular/cli/src/commands/new/long-description.md" }
angular-cli/packages/angular/cli/src/commands/make-this-awesome/cli.ts_0_1227
/** * @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 { Argv } from 'yargs'; import { CommandModule, CommandModuleImplementation } from '../../command-builder/command-module'; import { colors } from '../../utilities/color'; export default class AwesomeCommandModule extends CommandModule implements CommandModuleImplementation { command = 'make-this-awesome'; describe = false as const; deprecated = false; longDescriptionPath?: string | undefined; builder(localYargs: Argv): Argv { return localYargs; } run(): void { const pickOne = (of: string[]) => of[Math.floor(Math.random() * of.length)]; const phrase = pickOne([ `You're on it, there's nothing for me to do!`, `Let's take a look... nope, it's all good!`, `You're doing fine.`, `You're already doing great.`, `Nothing to do; already awesome. Exiting.`, `Error 418: As Awesome As Can Get.`, `I spy with my little eye a great developer!`, `Noop... already awesome.`, ]); this.context.logger.info(colors.green(phrase)); } }
{ "end_byte": 1227, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular/cli/src/commands/make-this-awesome/cli.ts" }
angular-cli/packages/angular/cli/src/commands/generate/cli.ts_0_1028
/** * @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 { strings } from '@angular-devkit/core'; import { Collection } from '@angular-devkit/schematics'; import { FileSystemCollectionDescription, FileSystemSchematicDescription, } from '@angular-devkit/schematics/tools'; import { ArgumentsCamelCase, Argv } from 'yargs'; import { CommandModuleError, CommandModuleImplementation, Options, OtherOptions, } from '../../command-builder/command-module'; import { SchematicsCommandArgs, SchematicsCommandModule, } from '../../command-builder/schematics-command-module'; import { demandCommandFailureMessage } from '../../command-builder/utilities/command'; import { Option } from '../../command-builder/utilities/json-schema'; import { RootCommands } from '../command-config'; interface GenerateCommandArgs extends SchematicsCommandArgs { schematic?: string; }
{ "end_byte": 1028, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular/cli/src/commands/generate/cli.ts" }
angular-cli/packages/angular/cli/src/commands/generate/cli.ts_1030_9914
export default class GenerateCommandModule extends SchematicsCommandModule implements CommandModuleImplementation<GenerateCommandArgs> { command = 'generate'; aliases = RootCommands['generate'].aliases; describe = 'Generates and/or modifies files based on a schematic.'; longDescriptionPath?: string | undefined; override async builder(argv: Argv): Promise<Argv<GenerateCommandArgs>> { let localYargs = (await super.builder(argv)).command({ command: '$0 <schematic>', describe: 'Run the provided schematic.', builder: (localYargs) => localYargs .positional('schematic', { describe: 'The [collection:schematic] to run.', type: 'string', demandOption: true, }) .strict(), handler: (options) => this.handler(options as ArgumentsCamelCase<GenerateCommandArgs>), }); for (const [schematicName, collectionName] of await this.getSchematicsToRegister()) { const workflow = this.getOrCreateWorkflowForBuilder(collectionName); const collection = workflow.engine.createCollection(collectionName); const { description: { schemaJson, aliases: schematicAliases, hidden: schematicHidden, description: schematicDescription, }, } = collection.createSchematic(schematicName, true); if (!schemaJson) { continue; } const { 'x-deprecated': xDeprecated, description = schematicDescription, hidden = schematicHidden, } = schemaJson; const options = await this.getSchematicOptions(collection, schematicName, workflow); localYargs = localYargs.command({ command: await this.generateCommandString(collectionName, schematicName, options), // When 'describe' is set to false, it results in a hidden command. describe: hidden === true ? false : typeof description === 'string' ? description : '', deprecated: xDeprecated === true || typeof xDeprecated === 'string' ? xDeprecated : false, aliases: Array.isArray(schematicAliases) ? await this.generateCommandAliasesStrings(collectionName, schematicAliases) : undefined, builder: (localYargs) => this.addSchemaOptionsToCommand(localYargs, options).strict(), handler: (options) => this.handler({ ...options, schematic: `${collectionName}:${schematicName}`, } as ArgumentsCamelCase< SchematicsCommandArgs & { schematic: string; } >), }); } return localYargs.demandCommand(1, demandCommandFailureMessage); } async run(options: Options<GenerateCommandArgs> & OtherOptions): Promise<number | void> { const { dryRun, schematic, defaults, force, interactive, ...schematicOptions } = options; const [collectionName, schematicName] = this.parseSchematicInfo(schematic); if (!collectionName || !schematicName) { throw new CommandModuleError('A collection and schematic is required during execution.'); } return this.runSchematic({ collectionName, schematicName, schematicOptions, executionOptions: { dryRun, defaults, force, interactive, }, }); } private async getCollectionNames(): Promise<string[]> { const [collectionName] = this.parseSchematicInfo( // positional = [generate, component] or [generate] this.context.args.positional[1], ); return collectionName ? [collectionName] : [...(await this.getSchematicCollections())]; } private async shouldAddCollectionNameAsPartOfCommand(): Promise<boolean> { const [collectionNameFromArgs] = this.parseSchematicInfo( // positional = [generate, component] or [generate] this.context.args.positional[1], ); const schematicCollectionsFromConfig = await this.getSchematicCollections(); const collectionNames = await this.getCollectionNames(); // Only add the collection name as part of the command when it's not a known // schematics collection or when it has been provided via the CLI. // Ex:`ng generate @schematics/angular:c` return ( !!collectionNameFromArgs || !collectionNames.some((c) => schematicCollectionsFromConfig.has(c)) ); } /** * Generate an aliases string array to be passed to the command builder. * * @example `[component]` or `[@schematics/angular:component]`. */ private async generateCommandAliasesStrings( collectionName: string, schematicAliases: string[], ): Promise<string[]> { // Only add the collection name as part of the command when it's not a known // schematics collection or when it has been provided via the CLI. // Ex:`ng generate @schematics/angular:c` return (await this.shouldAddCollectionNameAsPartOfCommand()) ? schematicAliases.map((alias) => `${collectionName}:${alias}`) : schematicAliases; } /** * Generate a command string to be passed to the command builder. * * @example `component [name]` or `@schematics/angular:component [name]`. */ private async generateCommandString( collectionName: string, schematicName: string, options: Option[], ): Promise<string> { const dasherizedSchematicName = strings.dasherize(schematicName); // Only add the collection name as part of the command when it's not a known // schematics collection or when it has been provided via the CLI. // Ex:`ng generate @schematics/angular:component` const commandName = (await this.shouldAddCollectionNameAsPartOfCommand()) ? collectionName + ':' + dasherizedSchematicName : dasherizedSchematicName; const positionalArgs = options .filter((o) => o.positional !== undefined) .map((o) => { const label = `${strings.dasherize(o.name)}${o.type === 'array' ? ' ..' : ''}`; return o.required ? `<${label}>` : `[${label}]`; }) .join(' '); return `${commandName}${positionalArgs ? ' ' + positionalArgs : ''}`; } /** * Get schematics that can to be registered as subcommands. */ private async *getSchematics(): AsyncGenerator<{ schematicName: string; schematicAliases?: Set<string>; collectionName: string; }> { const seenNames = new Set<string>(); for (const collectionName of await this.getCollectionNames()) { const workflow = this.getOrCreateWorkflowForBuilder(collectionName); const collection = workflow.engine.createCollection(collectionName); for (const schematicName of collection.listSchematicNames(true /** includeHidden */)) { // If a schematic with this same name is already registered skip. if (!seenNames.has(schematicName)) { seenNames.add(schematicName); yield { schematicName, collectionName, schematicAliases: this.listSchematicAliases(collection, schematicName), }; } } } } private listSchematicAliases( collection: Collection<FileSystemCollectionDescription, FileSystemSchematicDescription>, schematicName: string, ): Set<string> | undefined { const description = collection.description.schematics[schematicName]; if (description) { return description.aliases && new Set(description.aliases); } // Extended collections if (collection.baseDescriptions) { for (const base of collection.baseDescriptions) { const description = base.schematics[schematicName]; if (description) { return description.aliases && new Set(description.aliases); } } } return undefined; } /** * Get schematics that should to be registered as subcommands. * * @returns a sorted list of schematic that needs to be registered as subcommands. */ private async getSchematicsToRegister(): Promise< [schematicName: string, collectionName: string][] > { const schematicsToRegister: [schematicName: string, collectionName: string][] = []; const [, schematicNameFromArgs] = this.parseSchematicInfo( // positional = [generate, component] or [generate] this.context.args.positional[1], ); for await (const { schematicName, collectionName, schematicAliases } of this.getSchematics()) { if ( schematicNameFromArgs && (schematicName === schematicNameFromArgs || schematicAliases?.has(schematicNameFromArgs)) ) { return [[schematicName, collectionName]]; } schematicsToRegister.push([schematicName, collectionName]); } // Didn't find the schematic or no schematic name was provided Ex: `ng generate --help`. return schematicsToRegister.sort(([nameA], [nameB]) => nameA.localeCompare(nameB, undefined, { sensitivity: 'accent' }), ); } }
{ "end_byte": 9914, "start_byte": 1030, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular/cli/src/commands/generate/cli.ts" }
angular-cli/packages/angular/cli/src/commands/build/cli.ts_0_862
/** * @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 { join } from 'path'; import { ArchitectCommandModule } from '../../command-builder/architect-command-module'; import { CommandModuleImplementation } from '../../command-builder/command-module'; import { RootCommands } from '../command-config'; export default class BuildCommandModule extends ArchitectCommandModule implements CommandModuleImplementation { multiTarget = false; command = 'build [project]'; aliases = RootCommands['build'].aliases; describe = 'Compiles an Angular application or library into an output directory named dist/ at the given output path.'; longDescriptionPath = join(__dirname, 'long-description.md'); }
{ "end_byte": 862, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular/cli/src/commands/build/cli.ts" }
angular-cli/packages/angular/cli/src/commands/build/long-description.md_0_1461
The command can be used to build a project of type "application" or "library". When used to build a library, a different builder is invoked, and only the `ts-config`, `configuration`, `poll` and `watch` options are applied. All other options apply only to building applications. The application builder uses the [esbuild](https://esbuild.github.io/) build tool, with default configuration options specified in the workspace configuration file (`angular.json`) or with a named alternative configuration. A "development" configuration is created by default when you use the CLI to create the project, and you can use that configuration by specifying the `--configuration development`. The configuration options generally correspond to the command options. You can override individual configuration defaults by specifying the corresponding options on the command line. The command can accept option names given in dash-case. Note that in the configuration file, you must specify names in camelCase. Some additional options can only be set through the configuration file, either by direct editing or with the `ng config` command. These include `assets`, `styles`, and `scripts` objects that provide runtime-global resources to include in the project. Resources in CSS, such as images and fonts, are automatically written and fingerprinted at the root of the output folder. For further details, see [Workspace Configuration](reference/configs/workspace-config).
{ "end_byte": 1461, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular/cli/src/commands/build/long-description.md" }
angular-cli/packages/angular/cli/src/commands/run/cli.ts_0_4005
/** * @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 { Target } from '@angular-devkit/architect'; import { join } from 'path'; import { Argv } from 'yargs'; import { ArchitectBaseCommandModule } from '../../command-builder/architect-base-command-module'; import { CommandModuleError, CommandModuleImplementation, CommandScope, Options, OtherOptions, } from '../../command-builder/command-module'; export interface RunCommandArgs { target: string; } export default class RunCommandModule extends ArchitectBaseCommandModule<RunCommandArgs> implements CommandModuleImplementation<RunCommandArgs> { override scope = CommandScope.In; command = 'run <target>'; describe = 'Runs an Architect target with an optional custom builder configuration defined in your project.'; longDescriptionPath = join(__dirname, 'long-description.md'); async builder(argv: Argv): Promise<Argv<RunCommandArgs>> { const { jsonHelp, getYargsCompletions, help } = this.context.args.options; const localYargs: Argv<RunCommandArgs> = argv .positional('target', { describe: 'The Architect target to run provided in the following format `project:target[:configuration]`.', type: 'string', demandOption: true, // Show only in when using --help and auto completion because otherwise comma seperated configuration values will be invalid. // Also, hide choices from JSON help so that we don't display them in AIO. choices: (getYargsCompletions || help) && !jsonHelp ? this.getTargetChoices() : undefined, }) .middleware((args) => { // TODO: remove in version 15. const { configuration, target } = args; if (typeof configuration === 'string' && target) { const targetWithConfig = target.split(':', 2); targetWithConfig.push(configuration); throw new CommandModuleError( 'Unknown argument: configuration.\n' + `Provide the configuration as part of the target 'ng run ${targetWithConfig.join( ':', )}'.`, ); } }, true) .strict(); const target = this.makeTargetSpecifier(); if (!target) { return localYargs; } const schemaOptions = await this.getArchitectTargetOptions(target); return this.addSchemaOptionsToCommand(localYargs, schemaOptions); } async run(options: Options<RunCommandArgs> & OtherOptions): Promise<number> { const target = this.makeTargetSpecifier(options); const { target: _target, ...extraOptions } = options; if (!target) { throw new CommandModuleError('Cannot determine project or target.'); } return this.runSingleTarget(target, extraOptions); } protected makeTargetSpecifier(options?: Options<RunCommandArgs>): Target | undefined { const architectTarget = options?.target ?? this.context.args.positional[1]; if (!architectTarget) { return undefined; } const [project = '', target = '', configuration] = architectTarget.split(':'); return { project, target, configuration, }; } /** @returns a sorted list of target specifiers to be used for auto completion. */ private getTargetChoices(): string[] | undefined { if (!this.context.workspace) { return; } const targets = []; for (const [projectName, project] of this.context.workspace.projects) { for (const [targetName, target] of project.targets) { const currentTarget = `${projectName}:${targetName}`; targets.push(currentTarget); if (!target.configurations) { continue; } for (const configName of Object.keys(target.configurations)) { targets.push(`${currentTarget}:${configName}`); } } } return targets.sort(); } }
{ "end_byte": 4005, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular/cli/src/commands/run/cli.ts" }
angular-cli/packages/angular/cli/src/commands/run/long-description.md_0_683
Architect is the tool that the CLI uses to perform complex tasks such as compilation, according to provided configurations. The CLI commands run Architect targets such as `build`, `serve`, `test`, and `lint`. Each named target has a default configuration, specified by an `options` object, and an optional set of named alternate configurations in the `configurations` object. For example, the `serve` target for a newly generated app has a predefined alternate configuration named `production`. You can define new targets and their configuration options in the `architect` section of the `angular.json` file which you can run them from the command line using the `ng run` command.
{ "end_byte": 683, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular/cli/src/commands/run/long-description.md" }
angular-cli/packages/angular/cli/src/commands/serve/cli.ts_0_767
/** * @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 { ArchitectCommandModule } from '../../command-builder/architect-command-module'; import { CommandModuleImplementation } from '../../command-builder/command-module'; import { RootCommands } from '../command-config'; export default class ServeCommandModule extends ArchitectCommandModule implements CommandModuleImplementation { multiTarget = false; command = 'serve [project]'; aliases = RootCommands['serve'].aliases; describe = 'Builds and serves your application, rebuilding on file changes.'; longDescriptionPath?: string | undefined; }
{ "end_byte": 767, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular/cli/src/commands/serve/cli.ts" }