complete-cli 1.0.5 → 1.0.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (50) hide show
  1. package/dist/commands/CheckCommand.js +141 -0
  2. package/dist/commands/InitCommand.js +64 -0
  3. package/dist/commands/NukeCommand.js +12 -0
  4. package/dist/commands/PublishCommand.js +162 -0
  5. package/dist/commands/UpdateCommand.js +15 -0
  6. package/dist/commands/check/check.test.js +86 -0
  7. package/dist/commands/check/getTruncatedText.js +139 -0
  8. package/dist/commands/init/checkIfProjectPathExists.js +21 -0
  9. package/dist/commands/init/createProject.js +130 -0
  10. package/dist/commands/init/getAuthorName.js +17 -0
  11. package/dist/commands/init/getProjectPath.js +80 -0
  12. package/dist/commands/init/packageManager.js +35 -0
  13. package/dist/commands/init/vsCodeInit.js +82 -0
  14. package/dist/constants.js +17 -0
  15. package/dist/git.js +132 -0
  16. package/dist/interfaces/GitHubCLIHostsYAML.js +1 -0
  17. package/dist/main.js +24 -0
  18. package/dist/prompt.js +53 -0
  19. package/package.json +9 -9
  20. package/src/main.ts +0 -3
  21. package/dist/main.cjs +0 -65140
  22. package/dist/main.cjs.map +0 -1
  23. package/dist/vendors-node_modules_prettier_plugins_acorn_mjs.main.cjs +0 -38
  24. package/dist/vendors-node_modules_prettier_plugins_acorn_mjs.main.cjs.map +0 -1
  25. package/dist/vendors-node_modules_prettier_plugins_angular_mjs.main.cjs +0 -25
  26. package/dist/vendors-node_modules_prettier_plugins_angular_mjs.main.cjs.map +0 -1
  27. package/dist/vendors-node_modules_prettier_plugins_babel_mjs.main.cjs +0 -38
  28. package/dist/vendors-node_modules_prettier_plugins_babel_mjs.main.cjs.map +0 -1
  29. package/dist/vendors-node_modules_prettier_plugins_estree_mjs.main.cjs +0 -61
  30. package/dist/vendors-node_modules_prettier_plugins_estree_mjs.main.cjs.map +0 -1
  31. package/dist/vendors-node_modules_prettier_plugins_flow_mjs.main.cjs +0 -42
  32. package/dist/vendors-node_modules_prettier_plugins_flow_mjs.main.cjs.map +0 -1
  33. package/dist/vendors-node_modules_prettier_plugins_glimmer_mjs.main.cjs +0 -55
  34. package/dist/vendors-node_modules_prettier_plugins_glimmer_mjs.main.cjs.map +0 -1
  35. package/dist/vendors-node_modules_prettier_plugins_graphql_mjs.main.cjs +0 -55
  36. package/dist/vendors-node_modules_prettier_plugins_graphql_mjs.main.cjs.map +0 -1
  37. package/dist/vendors-node_modules_prettier_plugins_html_mjs.main.cjs +0 -48
  38. package/dist/vendors-node_modules_prettier_plugins_html_mjs.main.cjs.map +0 -1
  39. package/dist/vendors-node_modules_prettier_plugins_markdown_mjs.main.cjs +0 -89
  40. package/dist/vendors-node_modules_prettier_plugins_markdown_mjs.main.cjs.map +0 -1
  41. package/dist/vendors-node_modules_prettier_plugins_meriyah_mjs.main.cjs +0 -27
  42. package/dist/vendors-node_modules_prettier_plugins_meriyah_mjs.main.cjs.map +0 -1
  43. package/dist/vendors-node_modules_prettier_plugins_postcss_mjs.main.cjs +0 -80
  44. package/dist/vendors-node_modules_prettier_plugins_postcss_mjs.main.cjs.map +0 -1
  45. package/dist/vendors-node_modules_prettier_plugins_typescript_mjs.main.cjs +0 -43
  46. package/dist/vendors-node_modules_prettier_plugins_typescript_mjs.main.cjs.map +0 -1
  47. package/dist/vendors-node_modules_prettier_plugins_yaml_mjs.main.cjs +0 -187
  48. package/dist/vendors-node_modules_prettier_plugins_yaml_mjs.main.cjs.map +0 -1
  49. package/dist/vendors-node_modules_typanion_lib_index_js.main.cjs +0 -1323
  50. package/dist/vendors-node_modules_typanion_lib_index_js.main.cjs.map +0 -1
@@ -0,0 +1,141 @@
1
+ import chalk from "chalk";
2
+ import { Command, Option } from "clipanion";
3
+ import { ReadonlySet } from "complete-common";
4
+ import { $, deleteFileOrDirectory, fatalError, isDirectory, isFile, readFile, writeFile, } from "complete-node";
5
+ import klawSync from "klaw-sync";
6
+ import path from "node:path";
7
+ import { ACTION_YML, ACTION_YML_TEMPLATE_PATH, CWD, TEMPLATES_DYNAMIC_DIR, TEMPLATES_STATIC_DIR, } from "../constants.js";
8
+ import { getTruncatedText } from "./check/getTruncatedText.js";
9
+ const URL_PREFIX = "https://raw.githubusercontent.com/complete-ts/complete/main/packages/complete-cli/file-templates";
10
+ export class CheckCommand extends Command {
11
+ static paths = [["check"], ["c"]];
12
+ ignore = Option.String("-i,--ignore", {
13
+ description: "Comma separated list of file names to ignore.",
14
+ });
15
+ verbose = Option.Boolean("-v,--verbose", false, {
16
+ description: "Enable verbose output.",
17
+ });
18
+ static usage = Command.Usage({
19
+ description: "Check the template files of the current TypeScript project to see if they are up to date.",
20
+ });
21
+ // eslint-disable-next-line @typescript-eslint/require-await
22
+ async execute() {
23
+ let oneOrMoreErrors = false;
24
+ const ignore = this.ignore ?? "";
25
+ const ignoreFileNames = ignore.split(",");
26
+ const ignoreFileNamesSet = new ReadonlySet(ignoreFileNames);
27
+ // First, check the static files.
28
+ if (checkTemplateDirectory(TEMPLATES_STATIC_DIR, ignoreFileNamesSet, this.verbose)) {
29
+ oneOrMoreErrors = true;
30
+ }
31
+ // Second, check dynamic files that require specific logic.
32
+ if (checkIndividualFiles(ignoreFileNamesSet, this.verbose)) {
33
+ oneOrMoreErrors = true;
34
+ }
35
+ if (oneOrMoreErrors) {
36
+ fatalError("The check command failed.");
37
+ }
38
+ }
39
+ }
40
+ function checkTemplateDirectory(templateDirectory, ignoreFileNamesSet, verbose) {
41
+ let oneOrMoreErrors = false;
42
+ for (const klawItem of klawSync(templateDirectory)) {
43
+ const templateFilePath = klawItem.path;
44
+ if (isDirectory(templateFilePath)) {
45
+ continue;
46
+ }
47
+ const originalFileName = path.basename(templateFilePath);
48
+ if (originalFileName === "main.ts") {
49
+ continue;
50
+ }
51
+ const relativeTemplateFilePath = path.relative(templateDirectory, templateFilePath);
52
+ const templateFileName = path.basename(relativeTemplateFilePath);
53
+ let projectFilePath = path.join(CWD, relativeTemplateFilePath);
54
+ switch (templateFileName) {
55
+ case "_cspell.config.jsonc": {
56
+ projectFilePath = path.join(projectFilePath, "..", "cspell.config.jsonc");
57
+ break;
58
+ }
59
+ case "_gitattributes": {
60
+ projectFilePath = path.join(projectFilePath, "..", ".gitattributes");
61
+ break;
62
+ }
63
+ default: {
64
+ break;
65
+ }
66
+ }
67
+ const projectFileName = path.basename(projectFilePath);
68
+ if (ignoreFileNamesSet.has(projectFileName)) {
69
+ continue;
70
+ }
71
+ if (!compareTextFiles(projectFilePath, templateFilePath, verbose)) {
72
+ oneOrMoreErrors = true;
73
+ }
74
+ }
75
+ return oneOrMoreErrors;
76
+ }
77
+ function checkIndividualFiles(ignoreFileNamesSet, verbose) {
78
+ let oneOrMoreErrors = false;
79
+ if (!ignoreFileNamesSet.has(ACTION_YML)) {
80
+ const templateFilePath = ACTION_YML_TEMPLATE_PATH;
81
+ const relativeTemplateFilePath = path.relative(TEMPLATES_DYNAMIC_DIR, templateFilePath);
82
+ const projectFilePath = path.join(CWD, relativeTemplateFilePath);
83
+ if (!compareTextFiles(projectFilePath, templateFilePath, verbose)) {
84
+ oneOrMoreErrors = true;
85
+ }
86
+ }
87
+ return oneOrMoreErrors;
88
+ }
89
+ /** @returns Whether the project file is valid in reference to the template file. */
90
+ function compareTextFiles(projectFilePath, templateFilePath, verbose) {
91
+ if (!isFile(projectFilePath)) {
92
+ console.log(`Failed to find the following file: ${projectFilePath}`);
93
+ printTemplateLocation(templateFilePath);
94
+ return false;
95
+ }
96
+ const projectFileObject = getTruncatedFileText(projectFilePath, new Set(), new Set());
97
+ const templateFileObject = getTruncatedFileText(templateFilePath, projectFileObject.ignoreLines, projectFileObject.linesBeforeIgnore);
98
+ if (projectFileObject.text === templateFileObject.text) {
99
+ return true;
100
+ }
101
+ console.log(`The contents of the following file do not match: ${chalk.red(projectFilePath)}`);
102
+ printTemplateLocation(templateFilePath);
103
+ if (verbose) {
104
+ const originalTemplateFile = readFile(templateFilePath);
105
+ const originalProjectFile = readFile(projectFilePath);
106
+ console.log("--- Original template file: ---\n");
107
+ console.log(originalTemplateFile);
108
+ console.log();
109
+ console.log("--- Original project file: ---\n");
110
+ console.log(originalProjectFile);
111
+ console.log();
112
+ console.log("--- Parsed template file: ---\n");
113
+ console.log(templateFileObject.text);
114
+ console.log();
115
+ console.log("--- Parsed project file: ---\n");
116
+ console.log(projectFileObject.text);
117
+ console.log();
118
+ }
119
+ const tempProjectFilePath = path.join(CWD, "tempProjectFile.txt");
120
+ const tempTemplateFilePath = path.join(CWD, "tempTemplateFile.txt");
121
+ writeFile(tempProjectFilePath, projectFileObject.text);
122
+ writeFile(tempTemplateFilePath, templateFileObject.text);
123
+ $.sync `diff ${tempProjectFilePath} ${tempTemplateFilePath} --ignore-blank-lines`;
124
+ deleteFileOrDirectory(tempProjectFilePath);
125
+ deleteFileOrDirectory(tempTemplateFilePath);
126
+ return false;
127
+ }
128
+ function getTruncatedFileText(filePath, ignoreLines, linesBeforeIgnore) {
129
+ const fileName = path.basename(filePath);
130
+ const fileContents = readFile(filePath);
131
+ return getTruncatedText(fileName, fileContents, ignoreLines, linesBeforeIgnore);
132
+ }
133
+ function printTemplateLocation(templateFilePath) {
134
+ const unixPath = templateFilePath.split(path.sep).join(path.posix.sep);
135
+ const match = unixPath.match(/.+\/file-templates\/(?<urlSuffix>.+)/);
136
+ if (match === null || match.groups === undefined) {
137
+ fatalError(`Failed to parse the template file path: ${templateFilePath}`);
138
+ }
139
+ const { urlSuffix } = match.groups;
140
+ console.log(`You can find the template at: ${chalk.green(`${URL_PREFIX}/${urlSuffix}`)}\n`);
141
+ }
@@ -0,0 +1,64 @@
1
+ import { Command, Option } from "clipanion";
2
+ import path from "node:path";
3
+ import { promptGitHubRepoOrGitRemoteURL } from "../git.js";
4
+ import { promptEnd, promptStart } from "../prompt.js";
5
+ import { checkIfProjectPathExists } from "./init/checkIfProjectPathExists.js";
6
+ import { createProject } from "./init/createProject.js";
7
+ import { getAuthorName } from "./init/getAuthorName.js";
8
+ import { getProjectPath } from "./init/getProjectPath.js";
9
+ import { getPackageManagerUsedForNewProject } from "./init/packageManager.js";
10
+ import { vsCodeInit } from "./init/vsCodeInit.js";
11
+ export class InitCommand extends Command {
12
+ static paths = [["init"], ["i"]];
13
+ // The first positional argument.
14
+ name = Option.String({
15
+ required: false,
16
+ });
17
+ yes = Option.Boolean("-y,--yes", false, {
18
+ description: 'Answer yes to every dialog option, similar to how "npm init --yes" works.',
19
+ });
20
+ useCurrentDirectory = Option.Boolean("--use-current-directory", false, {
21
+ description: "Use the current directory as the root for the project.",
22
+ });
23
+ customDirectory = Option.String("--custom-directory", {
24
+ description: "Initialize the project into the specified directory (instead of creating a new one based on the name or using the current working directory).",
25
+ });
26
+ vsCode = Option.Boolean("--vscode", false, {
27
+ description: "Open the project in VSCode after initialization.",
28
+ });
29
+ npm = Option.Boolean("--npm", false, {
30
+ description: "Use npm as the package manager.",
31
+ });
32
+ yarn = Option.Boolean("--yarn", false, {
33
+ description: "Use yarn as the package manager.",
34
+ });
35
+ pnpm = Option.Boolean("--pnpm", false, {
36
+ description: "Use pnpm as the package manager.",
37
+ });
38
+ skipGit = Option.Boolean("--skip-git", false, {
39
+ description: "Do not initialize Git.",
40
+ });
41
+ skipInstall = Option.Boolean("--skip-install", false, {
42
+ description: "Do not automatically install the dependencies after initializing the project.",
43
+ });
44
+ forceName = Option.Boolean("-f,--force-name", false, {
45
+ description: "Allow project names that are normally illegal.",
46
+ });
47
+ static usage = Command.Usage({
48
+ description: "Initialize a new TypeScript project.",
49
+ });
50
+ async execute() {
51
+ promptStart();
52
+ const packageManager = await getPackageManagerUsedForNewProject(this);
53
+ // Prompt the end-user for some information (and validate it as we go).
54
+ const { projectPath, createNewDir } = await getProjectPath(this.name, this.useCurrentDirectory, this.customDirectory, this.yes, this.forceName);
55
+ await checkIfProjectPathExists(projectPath, this.yes);
56
+ const projectName = path.basename(projectPath);
57
+ const authorName = await getAuthorName();
58
+ const gitRemoteURL = await promptGitHubRepoOrGitRemoteURL(projectName, this.yes, this.skipGit);
59
+ // Now that we have asked the user all of the questions we need, we can create the project.
60
+ await createProject(projectName, authorName, projectPath, createNewDir, gitRemoteURL, this.skipInstall, packageManager);
61
+ await vsCodeInit(projectPath, this.vsCode, this.yes);
62
+ promptEnd("Initialization completed.");
63
+ }
64
+ }
@@ -0,0 +1,12 @@
1
+ import { Command } from "clipanion";
2
+ import { nukeDependencies } from "complete-node";
3
+ export class NukeCommand extends Command {
4
+ static paths = [["nuke"], ["n"]];
5
+ static usage = Command.Usage({
6
+ description: 'Delete the "node_modules" directory and the package lock file, then reinstall the dependencies for the project.',
7
+ });
8
+ async execute() {
9
+ await nukeDependencies();
10
+ console.log("Successfully reinstalled dependencies from npm.");
11
+ }
12
+ }
@@ -0,0 +1,162 @@
1
+ import { Command, Option } from "clipanion";
2
+ import { isSemanticVersion } from "complete-common";
3
+ import { $, fatalError, getPackageJSONField, getPackageJSONVersion, getPackageManagerInstallCommand, getPackageManagerLockFileName, getPackageManagersForProject, isFileAsync, isGitRepository, isGitRepositoryClean, isLoggedInToNPM, readFile, updatePackageJSONDependencies, writeFileAsync, } from "complete-node";
4
+ import path from "node:path";
5
+ import { CWD, DEFAULT_PACKAGE_MANAGER } from "../constants.js";
6
+ export class PublishCommand extends Command {
7
+ static paths = [["publish"], ["p"]];
8
+ // The first positional argument.
9
+ versionBumpType = Option.String({
10
+ required: true,
11
+ });
12
+ dryRun = Option.Boolean("--dry-run", false, {
13
+ description: "Skip committing/uploading & perform a Git reset afterward.",
14
+ });
15
+ skipLint = Option.Boolean("--skip-lint", false, {
16
+ description: "Skip linting before publishing.",
17
+ });
18
+ skipUpdate = Option.Boolean("--skip-update", false, {
19
+ description: "Skip updating the npm dependencies.",
20
+ });
21
+ static usage = Command.Usage({
22
+ description: "Bump the version & publish a new release.",
23
+ });
24
+ async execute() {
25
+ await validate();
26
+ await prePublish(this.versionBumpType, this.dryRun, this.skipLint, this.skipUpdate);
27
+ await publish(this.dryRun);
28
+ }
29
+ }
30
+ async function validate() {
31
+ const isRepository = await isGitRepository(CWD);
32
+ if (!isRepository) {
33
+ fatalError("Failed to publish since the current working directory is not inside of a git repository.");
34
+ }
35
+ const isRepositoryClean = await isGitRepositoryClean(CWD);
36
+ if (!isRepositoryClean) {
37
+ fatalError("Failed to publish since the Git repository was dirty. Before publishing, you must push any current changes to git. (Version commits should not contain any code changes.)");
38
+ }
39
+ const packageJSONExists = await isFileAsync("package.json");
40
+ if (!packageJSONExists) {
41
+ fatalError('Failed to find the "package.json" file in the current working directory.');
42
+ }
43
+ const isLoggedIn = await isLoggedInToNPM();
44
+ if (!isLoggedIn) {
45
+ fatalError('Failed to publish since you are not logged in to npm. Try doing "npm login".');
46
+ }
47
+ }
48
+ /**
49
+ * Before uploading the project, we want to update dependencies, increment the version, and perform
50
+ * some other steps.
51
+ */
52
+ async function prePublish(versionBumpType, dryRun, skipLint, skipUpdate) {
53
+ const packageManager = await getPackageManagerUsedForExistingProject();
54
+ await $ `git pull --rebase`;
55
+ await $ `git push`;
56
+ await updateDependencies(skipUpdate, dryRun, packageManager);
57
+ await incrementVersion(versionBumpType);
58
+ await unsetDevelopmentConstants();
59
+ await tryRunNPMScript("build");
60
+ if (!skipLint) {
61
+ await tryRunNPMScript("lint");
62
+ }
63
+ }
64
+ async function getPackageManagerUsedForExistingProject() {
65
+ const packageManagers = await getPackageManagersForProject(CWD);
66
+ if (packageManagers.length > 1) {
67
+ const packageManagerLockFileNames = packageManagers
68
+ .map((packageManager) => getPackageManagerLockFileName(packageManager))
69
+ .map((packageManagerLockFileName) => `"${packageManagerLockFileName}"`)
70
+ .join(" & ");
71
+ fatalError(`Multiple different kinds of package manager lock files were found (${packageManagerLockFileNames}). You should delete the ones that you are not using so that this program can correctly detect your package manager.`);
72
+ }
73
+ const packageManager = packageManagers[0];
74
+ if (packageManager !== undefined) {
75
+ return packageManager;
76
+ }
77
+ return DEFAULT_PACKAGE_MANAGER;
78
+ }
79
+ async function updateDependencies(skipUpdate, dryRun, packageManager) {
80
+ if (skipUpdate) {
81
+ return;
82
+ }
83
+ console.log('Updating dependencies in the "package.json" file...');
84
+ const hasNewDependencies = await updatePackageJSONDependencies(undefined);
85
+ if (hasNewDependencies) {
86
+ const command = getPackageManagerInstallCommand(packageManager);
87
+ const commandParts = command.split(" ");
88
+ await $ `${commandParts}`;
89
+ if (!dryRun) {
90
+ await gitCommitAllAndPush("chore: update dependencies");
91
+ }
92
+ }
93
+ }
94
+ async function gitCommitAllAndPush(message) {
95
+ await $ `git add --all`;
96
+ await $ `git commit --message ${message}`;
97
+ await $ `git push`;
98
+ console.log(`Committed and pushed to the git repository with a message of: ${message}`);
99
+ }
100
+ async function incrementVersion(versionBumpType) {
101
+ if (versionBumpType === "none") {
102
+ return;
103
+ }
104
+ if (versionBumpType === "dev") {
105
+ throw new Error('The version bump type of "dev" is not currently supported.');
106
+ }
107
+ if (versionBumpType !== "major" &&
108
+ versionBumpType !== "minor" &&
109
+ versionBumpType !== "patch" &&
110
+ versionBumpType !== "dev" &&
111
+ !isSemanticVersion(versionBumpType)) {
112
+ fatalError('The version must be one of "major", "minor", "patch", "dev", "none", or a specific semantic version like "1.2.3".');
113
+ }
114
+ // We always use `npm` here to avoid differences with the version command between package
115
+ // managers. The "--no-git-tag-version" flag will prevent npm from both making a commit and adding
116
+ // a tag.
117
+ await $ `npm version ${versionBumpType} --no-git-tag-version`;
118
+ }
119
+ async function unsetDevelopmentConstants() {
120
+ const constantsTSPath = path.join(CWD, "src", "constants.ts");
121
+ const constantsTSExists = await isFileAsync(constantsTSPath);
122
+ if (!constantsTSExists) {
123
+ return;
124
+ }
125
+ const constantsTS = readFile(constantsTSPath);
126
+ const newConstantsTS = constantsTS
127
+ .replace("const IS_DEV = true", "const IS_DEV = false")
128
+ .replace("const DEBUG = true", "const DEBUG = false");
129
+ await writeFileAsync(constantsTSPath, newConstantsTS);
130
+ }
131
+ async function tryRunNPMScript(scriptName) {
132
+ console.log(`Running: ${scriptName}`);
133
+ const $$ = $({
134
+ reject: false,
135
+ });
136
+ const { exitCode } = await $$ `npm run ${scriptName}`;
137
+ if (exitCode !== 0) {
138
+ await $ `git reset --hard`; // Revert the version changes.
139
+ fatalError(`Failed to run "${scriptName}".`);
140
+ }
141
+ }
142
+ async function publish(dryRun) {
143
+ const projectName = getPackageJSONField(undefined, "name");
144
+ const version = getPackageJSONVersion(undefined);
145
+ if (dryRun) {
146
+ await $ `git reset --hard`; // Revert the version changes.
147
+ }
148
+ else {
149
+ const releaseGitCommitMessage = getReleaseGitCommitMessage(version);
150
+ await gitCommitAllAndPush(releaseGitCommitMessage);
151
+ // - The "--access=public" flag is only technically needed for the first publish (unless the
152
+ // package is a scoped package), but it is saved here for posterity.
153
+ // - The "--ignore-scripts" flag is needed since the "npm publish" command will run the
154
+ // "publish" script in the "package.json" file, causing an infinite loop.
155
+ await $ `npm publish --access=public --ignore-scripts`;
156
+ }
157
+ const dryRunSuffix = dryRun ? " (dry-run)" : "";
158
+ console.log(`Published ${projectName} version ${version} successfully${dryRunSuffix}.`);
159
+ }
160
+ function getReleaseGitCommitMessage(version) {
161
+ return `chore: release ${version}`;
162
+ }
@@ -0,0 +1,15 @@
1
+ import { Command } from "clipanion";
2
+ import { updatePackageJSONDependencies } from "complete-node";
3
+ export class UpdateCommand extends Command {
4
+ static paths = [["update"], ["u"]];
5
+ static usage = Command.Usage({
6
+ description: 'Invoke "npm-check-updates" to update the dependencies inside of the "package.json" file and then install them.',
7
+ });
8
+ async execute() {
9
+ const hasNewDependencies = await updatePackageJSONDependencies();
10
+ const msg = hasNewDependencies
11
+ ? "Successfully installed new Node.js dependencies."
12
+ : "There were no new dependency updates from npm.";
13
+ console.log(msg);
14
+ }
15
+ }
@@ -0,0 +1,86 @@
1
+ import { strictEqual } from "node:assert";
2
+ import test from "node:test";
3
+ import { getTruncatedText } from "./getTruncatedText.js";
4
+ test("no markers", () => {
5
+ const templateText = `
6
+ line 1
7
+ line 2
8
+ line 3
9
+ `.trim();
10
+ const { text } = getTruncatedText("test", templateText, new Set(), new Set());
11
+ strictEqual(text, templateText);
12
+ });
13
+ test("customization marker", () => {
14
+ const templateText = `
15
+ line 1
16
+ @template-customization-start
17
+ line 2
18
+ @template-customization-end
19
+ line 3
20
+ `.trim();
21
+ const expectedTemplateText = `
22
+ line 1
23
+ line 3
24
+ `.trim();
25
+ const { text } = getTruncatedText("test", templateText, new Set(), new Set());
26
+ strictEqual(text, expectedTemplateText);
27
+ });
28
+ test("ignore block marker part 1", () => {
29
+ const templateText = `
30
+ line 1
31
+ @template-ignore-block-start
32
+ // line 2
33
+ @template-ignore-block-end
34
+ line 3
35
+ `.trim();
36
+ const parsedTemplateText = `
37
+ line 1
38
+ line 3
39
+ `.trim();
40
+ const { text, ignoreLines } = getTruncatedText("test", templateText, new Set(), new Set());
41
+ strictEqual(text, parsedTemplateText);
42
+ strictEqual(ignoreLines.size, 1);
43
+ strictEqual([...ignoreLines][0], "line 2");
44
+ });
45
+ test("ignore block marker part 2", () => {
46
+ const templateText = `
47
+ line 1
48
+ line 2
49
+ line 3
50
+ `.trim();
51
+ const expectedTemplateText = `
52
+ line 1
53
+ line 3
54
+ `.trim();
55
+ const { text } = getTruncatedText("test", templateText, new Set(["line 2"]), new Set());
56
+ strictEqual(text, expectedTemplateText);
57
+ });
58
+ test("ignore next line part 1", () => {
59
+ const templateText = `
60
+ line 1
61
+ @template-ignore-next-line
62
+ line 2
63
+ line 3
64
+ `.trim();
65
+ const expectedTemplateText = `
66
+ line 1
67
+ line 3
68
+ `.trim();
69
+ const { text, linesBeforeIgnore } = getTruncatedText("test", templateText, new Set(), new Set());
70
+ strictEqual(linesBeforeIgnore.size, 1);
71
+ strictEqual([...linesBeforeIgnore][0], "line 1");
72
+ strictEqual(text, expectedTemplateText);
73
+ });
74
+ test("ignore next line part 2", () => {
75
+ const templateText = `
76
+ line 1
77
+ line 2
78
+ line 3
79
+ `.trim();
80
+ const expectedTemplateText = `
81
+ line 1
82
+ line 3
83
+ `.trim();
84
+ const { text } = getTruncatedText("test", templateText, new Set(), new Set(["line 1"]));
85
+ strictEqual(text, expectedTemplateText);
86
+ });
@@ -0,0 +1,139 @@
1
+ import { getEnumValues, trimPrefix } from "complete-common";
2
+ import { fatalError, getPackageManagerLockFileNames, PackageManager, } from "complete-node";
3
+ const MARKER_CUSTOMIZATION_START = "@template-customization-start";
4
+ const MARKER_CUSTOMIZATION_END = "@template-customization-end";
5
+ const MARKER_IGNORE_BLOCK_START = "@template-ignore-block-start";
6
+ const MARKER_IGNORE_BLOCK_END = "@template-ignore-block-end";
7
+ const MARKER_IGNORE_NEXT_LINE = "@template-ignore-next-line";
8
+ const PACKAGE_MANAGER_STRINGS = [
9
+ "PACKAGE_MANAGER_NAME",
10
+ "PACKAGE_MANAGER_INSTALL_COMMAND",
11
+ "PACKAGE_MANAGER_LOCK_FILE_NAME",
12
+ ...getEnumValues(PackageManager),
13
+ ...getPackageManagerLockFileNames(),
14
+ ];
15
+ /**
16
+ * @param fileName Used to perform some specific rules based on the template file name.
17
+ * @param text The text to parse.
18
+ * @param ignoreLines A set of lines to remove from the text.
19
+ * @param linesBeforeIgnore A set of lines that will trigger the subsequent line to be ignored.
20
+ * @returns The text of the file with all text removed between any flagged markers (and other
21
+ * specific hard-coded exclusions), as well as an array of lines that had a
22
+ * "ignore-next-line" marker below them.
23
+ */
24
+ export function getTruncatedText(fileName, text, ignoreLines, linesBeforeIgnore) {
25
+ const lines = text.split("\n");
26
+ const newLines = [];
27
+ const newIgnoreLines = new Set();
28
+ const newLinesBeforeIgnore = new Set();
29
+ let isSkipping = false;
30
+ let isIgnoring = false;
31
+ let shouldIgnoreNextLine = false;
32
+ let previousLine = "";
33
+ for (const line of lines) {
34
+ if (line.trim() === "") {
35
+ continue;
36
+ }
37
+ if (ignoreLines.has(line.trim())) {
38
+ continue;
39
+ }
40
+ if (shouldIgnoreNextLine) {
41
+ shouldIgnoreNextLine = false;
42
+ continue;
43
+ }
44
+ if (linesBeforeIgnore.has(line)) {
45
+ shouldIgnoreNextLine = true;
46
+ }
47
+ // -------------
48
+ // Marker checks
49
+ // -------------
50
+ if (line.includes(MARKER_CUSTOMIZATION_START)) {
51
+ isSkipping = true;
52
+ continue;
53
+ }
54
+ if (line.includes(MARKER_CUSTOMIZATION_END)) {
55
+ isSkipping = false;
56
+ continue;
57
+ }
58
+ if (line.includes(MARKER_IGNORE_BLOCK_START)) {
59
+ isIgnoring = true;
60
+ continue;
61
+ }
62
+ if (line.includes(MARKER_IGNORE_BLOCK_END)) {
63
+ isIgnoring = false;
64
+ continue;
65
+ }
66
+ if (line.includes(MARKER_IGNORE_NEXT_LINE)) {
67
+ shouldIgnoreNextLine = true;
68
+ // We mark the previous line so that we know the next line to skip in the template.
69
+ if (previousLine.trim() === "") {
70
+ fatalError(`You cannot have a "${MARKER_IGNORE_NEXT_LINE}" marker before a blank line in the "${fileName}" file.`);
71
+ }
72
+ newLinesBeforeIgnore.add(previousLine);
73
+ continue;
74
+ }
75
+ if (isIgnoring) {
76
+ const baseLine = trimPrefix(line.trim(), "// ");
77
+ newIgnoreLines.add(baseLine);
78
+ continue;
79
+ }
80
+ // --------------------
81
+ // Specific file checks
82
+ // --------------------
83
+ // We should ignore imports in JavaScript or TypeScript files.
84
+ if (fileName.endsWith(".js") || fileName.endsWith(".ts")) {
85
+ if (line === "import {") {
86
+ isSkipping = true;
87
+ continue;
88
+ }
89
+ if (line.startsWith("} from ")) {
90
+ isSkipping = false;
91
+ continue;
92
+ }
93
+ if (line.startsWith("import ")) {
94
+ continue;
95
+ }
96
+ }
97
+ // End-users can have different ignored words.
98
+ if (fileName === "cspell.config.jsonc" ||
99
+ fileName === "_cspell.config.jsonc") {
100
+ if (line.match(/"words": \[.*]/) !== null) {
101
+ continue;
102
+ }
103
+ if (line.includes('"words": [')) {
104
+ isSkipping = true;
105
+ continue;
106
+ }
107
+ if ((line.endsWith("]") || line.endsWith("],")) && isSkipping) {
108
+ isSkipping = false;
109
+ continue;
110
+ }
111
+ }
112
+ if (fileName === "ci.yml" || fileName === "action.yml") {
113
+ // End-users can have different package managers.
114
+ if (hasPackageManagerString(line)) {
115
+ continue;
116
+ }
117
+ // Ignore comments, since end-users are expected to delete the explanations.
118
+ if (line.match(/^\s*#/) !== null) {
119
+ continue;
120
+ }
121
+ }
122
+ // ------------
123
+ // Final checks
124
+ // ------------
125
+ if (!isSkipping) {
126
+ newLines.push(line);
127
+ previousLine = line;
128
+ }
129
+ }
130
+ const newText = newLines.join("\n");
131
+ return {
132
+ text: newText,
133
+ ignoreLines: newIgnoreLines,
134
+ linesBeforeIgnore: newLinesBeforeIgnore,
135
+ };
136
+ }
137
+ function hasPackageManagerString(line) {
138
+ return PACKAGE_MANAGER_STRINGS.some((string) => line.includes(string));
139
+ }
@@ -0,0 +1,21 @@
1
+ import chalk from "chalk";
2
+ import { deleteFileOrDirectory, fileOrDirectoryExists, isDirectory, } from "complete-node";
3
+ import { CWD } from "../../constants.js";
4
+ import { getInputYesNo, promptEnd, promptLog } from "../../prompt.js";
5
+ export async function checkIfProjectPathExists(projectPath, yes) {
6
+ if (projectPath === CWD || !fileOrDirectoryExists(projectPath)) {
7
+ return;
8
+ }
9
+ const fileType = isDirectory(projectPath) ? "directory" : "file";
10
+ if (yes) {
11
+ deleteFileOrDirectory(projectPath);
12
+ promptLog(`Deleted ${fileType}: ${chalk.green(projectPath)}`);
13
+ return;
14
+ }
15
+ promptLog(`A ${fileType} already exists with a name of: ${chalk.green(projectPath)}`);
16
+ const shouldDelete = await getInputYesNo("Do you want me to delete it?");
17
+ if (!shouldDelete) {
18
+ promptEnd("Ok then. Goodbye.");
19
+ }
20
+ deleteFileOrDirectory(projectPath);
21
+ }