@snap/valdi 1.0.6 → 1.0.8

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 (161) hide show
  1. package/README.md +22 -10
  2. package/bundled-skills/CONTRIBUTING_SKILLS.md +74 -0
  3. package/bundled-skills/registry.json +20 -0
  4. package/bundled-skills/skills/valdi-android/skill.md +89 -0
  5. package/bundled-skills/skills/valdi-async/skill.md +246 -0
  6. package/bundled-skills/skills/valdi-async/tests/BUILD.bazel +19 -0
  7. package/bundled-skills/skills/valdi-async/tests/README.md +25 -0
  8. package/bundled-skills/skills/valdi-async/tests/src/reference.tsx +210 -0
  9. package/bundled-skills/skills/valdi-async/tests/tsconfig.json +1 -0
  10. package/bundled-skills/skills/valdi-bazel/skill.md +122 -0
  11. package/bundled-skills/skills/valdi-compiler/skill.md +108 -0
  12. package/bundled-skills/skills/valdi-component-tests/skill.md +430 -0
  13. package/bundled-skills/skills/valdi-component-tests/tests/BUILD.bazel +24 -0
  14. package/bundled-skills/skills/valdi-component-tests/tests/README.md +35 -0
  15. package/bundled-skills/skills/valdi-component-tests/tests/src/ProfileCard.tsx +38 -0
  16. package/bundled-skills/skills/valdi-component-tests/tests/test/ProfileCardTest.spec.tsx +107 -0
  17. package/bundled-skills/skills/valdi-component-tests/tests/tsconfig.json +1 -0
  18. package/bundled-skills/skills/valdi-cpp-runtime/skill.md +103 -0
  19. package/bundled-skills/skills/valdi-custom-view/skill.md +62 -0
  20. package/bundled-skills/skills/valdi-ios/skill.md +93 -0
  21. package/bundled-skills/skills/valdi-migrate/skill.md +175 -0
  22. package/bundled-skills/skills/valdi-migrate/tests/BUILD.bazel +23 -0
  23. package/bundled-skills/skills/valdi-migrate/tests/README.md +70 -0
  24. package/bundled-skills/skills/valdi-migrate/tests/check_antipatterns.py +89 -0
  25. package/bundled-skills/skills/valdi-migrate/tests/compose_example.kt +94 -0
  26. package/bundled-skills/skills/valdi-migrate/tests/flutter_example.dart +129 -0
  27. package/bundled-skills/skills/valdi-migrate/tests/react_example.tsx +98 -0
  28. package/bundled-skills/skills/valdi-migrate/tests/src/expected_valdi.tsx +267 -0
  29. package/bundled-skills/skills/valdi-migrate/tests/tsconfig.json +3 -0
  30. package/{.metadata/.cursorrules.template → bundled-skills/skills/valdi-overview/skill.md} +23 -13
  31. package/bundled-skills/skills/valdi-perf/skill.md +197 -0
  32. package/bundled-skills/skills/valdi-perf/tests/BUILD.bazel +19 -0
  33. package/bundled-skills/skills/valdi-perf/tests/README.md +26 -0
  34. package/bundled-skills/skills/valdi-perf/tests/src/reference.tsx +202 -0
  35. package/bundled-skills/skills/valdi-perf/tests/tsconfig.json +1 -0
  36. package/bundled-skills/skills/valdi-polyglot-module/skill.md +85 -0
  37. package/bundled-skills/skills/valdi-setup/skill.md +129 -0
  38. package/bundled-skills/skills/valdi-testing/skill.md +65 -0
  39. package/bundled-skills/skills/valdi-tsx/skill.md +385 -0
  40. package/bundled-skills/skills/valdi-tsx/tests/BUILD.bazel +19 -0
  41. package/bundled-skills/skills/valdi-tsx/tests/README.md +29 -0
  42. package/bundled-skills/skills/valdi-tsx/tests/src/reference.tsx +173 -0
  43. package/bundled-skills/skills/valdi-tsx/tests/tsconfig.json +1 -0
  44. package/dist/commands/bootstrap.js +3 -9
  45. package/dist/commands/newModule.js +10 -14
  46. package/dist/commands/skills.js +16 -0
  47. package/dist/commands/skills_commands/create.js +125 -0
  48. package/dist/commands/skills_commands/install.js +96 -0
  49. package/dist/commands/skills_commands/list.js +83 -0
  50. package/dist/commands/skills_commands/remove.js +41 -0
  51. package/dist/commands/skills_commands/update.js +59 -0
  52. package/dist/core/constants.js +1 -1
  53. package/dist/index.js +5 -0
  54. package/dist/setup/versions.js +1 -1
  55. package/dist/utils/skillsAdapters.js +140 -0
  56. package/dist/utils/skillsRegistry.js +40 -0
  57. package/package.json +6 -1
  58. package/.bazelignore +0 -2
  59. package/.bootstrap/apps/cli_application/AGENTS.md.template +0 -291
  60. package/.bootstrap/apps/cli_application/BUILD.bazel.template +0 -7
  61. package/.bootstrap/apps/cli_application/modules/{{MODULE_NAME}}/BUILD.bazel.template +0 -11
  62. package/.bootstrap/apps/cli_application/modules/{{MODULE_NAME}}/src/index.ts +0 -1
  63. package/.bootstrap/apps/ui_application/.eslint.rc +0 -27
  64. package/.bootstrap/apps/ui_application/AGENTS.md.template +0 -278
  65. package/.bootstrap/apps/ui_application/BUILD.bazel.template +0 -19
  66. package/.bootstrap/apps/ui_application/modules/{{MODULE_NAME}}/BUILD.bazel.template +0 -21
  67. package/.bootstrap/apps/ui_application/modules/{{MODULE_NAME}}/res/valdi@3x.png +0 -0
  68. package/.bootstrap/apps/ui_application/modules/{{MODULE_NAME}}/src/App.tsx +0 -133
  69. package/.bootstrap/apps/ui_application/package.json +0 -24
  70. package/.bootstrap/modules/cpp_bridge_module/BUILD.bazel.template +0 -21
  71. package/.bootstrap/modules/cpp_bridge_module/cpp/CalculatorModuleFactory.cpp.template +0 -28
  72. package/.bootstrap/modules/cpp_bridge_module/src/Calculator.d.ts +0 -4
  73. package/.bootstrap/modules/ios_android_bridge_module/BUILD.bazel.template +0 -39
  74. package/.bootstrap/modules/ios_android_bridge_module/android/CalculatorModuleFactory.kt.template +0 -18
  75. package/.bootstrap/modules/ios_android_bridge_module/ios/SCCCalculatorModuleFactory.m.template +0 -31
  76. package/.bootstrap/modules/ios_android_bridge_module/src/Calculator.d.ts +0 -4
  77. package/.bootstrap/modules/ios_android_view_module/BUILD.bazel.template +0 -41
  78. package/.bootstrap/modules/ios_android_view_module/android/CircleView.kt.template +0 -42
  79. package/.bootstrap/modules/ios_android_view_module/android/CircleViewAttributesBinder.kt.template +0 -60
  80. package/.bootstrap/modules/ios_android_view_module/ios/SCCCircleView.h +0 -6
  81. package/.bootstrap/modules/ios_android_view_module/ios/SCCCircleView.m +0 -82
  82. package/.bootstrap/modules/ios_android_view_module/src/Circle.tsx.template +0 -15
  83. package/.bootstrap/modules/ui_component/BUILD.bazel.template +0 -34
  84. package/.bootstrap/modules/ui_component/src/NewModuleComponent.tsx +0 -45
  85. package/.config/copyconfig.json +0 -10
  86. package/.editorconfig +0 -21
  87. package/.eslintignore +0 -1
  88. package/.eslintrc.js +0 -72
  89. package/.github/README.md +0 -164
  90. package/.metadata/.bazelrc.template +0 -91
  91. package/.metadata/.bazelversion.template +0 -1
  92. package/.metadata/.editorconfig.template +0 -37
  93. package/.metadata/.eslintrc.js.template +0 -27
  94. package/.metadata/.gitignore.template +0 -4
  95. package/.metadata/.prettierrc.json.template +0 -7
  96. package/.metadata/.watchmanconfig.template +0 -8
  97. package/.metadata/README.md.template +0 -31
  98. package/.metadata/WORKSPACE.template +0 -57
  99. package/.metadata/config.yaml.template +0 -1
  100. package/.metadata/package.json.template +0 -23
  101. package/.prettierignore +0 -2
  102. package/.prettierrc.json +0 -7
  103. package/LINUX_COMPATIBILITY.md +0 -248
  104. package/prettier.config.js +0 -4
  105. package/scripts/sync-agents-md.sh +0 -44
  106. package/scripts/update-agents-templates.ts +0 -170
  107. package/spec/support/jasmine.json +0 -6
  108. package/src/commands/bootstrap.ts +0 -409
  109. package/src/commands/build.ts +0 -89
  110. package/src/commands/devSetup.ts +0 -17
  111. package/src/commands/doctor.ts +0 -1832
  112. package/src/commands/export.ts +0 -131
  113. package/src/commands/hotreload.ts +0 -108
  114. package/src/commands/install.ts +0 -93
  115. package/src/commands/lint.ts +0 -15
  116. package/src/commands/lint_commands/lintCheck.ts +0 -53
  117. package/src/commands/lint_commands/lintFormat.ts +0 -49
  118. package/src/commands/log.ts +0 -108
  119. package/src/commands/newModule.ts +0 -286
  120. package/src/commands/package.ts +0 -102
  121. package/src/commands/projectsync.ts +0 -488
  122. package/src/commands/test.ts +0 -68
  123. package/src/core/constants.ts +0 -97
  124. package/src/core/errors.ts +0 -10
  125. package/src/index.ts +0 -22
  126. package/src/setup/DevSetupHelper.ts +0 -290
  127. package/src/setup/linuxSetup.ts +0 -261
  128. package/src/setup/macOSSetup.ts +0 -156
  129. package/src/setup/setupEntryPoint.ts +0 -64
  130. package/src/setup/versions.ts +0 -8
  131. package/src/utils/ArgumentsResolver.ts +0 -23
  132. package/src/utils/BazelClient.ts +0 -285
  133. package/src/utils/Digraph.ts +0 -81
  134. package/src/utils/LoadingIndicator.ts +0 -43
  135. package/src/utils/applicationUtils.ts +0 -276
  136. package/src/utils/buildInfo.ts +0 -99
  137. package/src/utils/byString.ts +0 -3
  138. package/src/utils/cliUtils.ts +0 -112
  139. package/src/utils/copyBootstrapFiles.ts +0 -30
  140. package/src/utils/deviceUtils.ts +0 -76
  141. package/src/utils/errorUtils.ts +0 -63
  142. package/src/utils/fileUtils.ts +0 -257
  143. package/src/utils/githubUtils.ts +0 -102
  144. package/src/utils/jsonUtils.ts +0 -30
  145. package/src/utils/lintUtils.ts +0 -190
  146. package/src/utils/linuxDistro.spec.ts +0 -219
  147. package/src/utils/linuxDistro.ts +0 -326
  148. package/src/utils/logUtils.ts +0 -9
  149. package/src/utils/pathUtils.ts +0 -12
  150. package/src/utils/stringUtils.spec.ts +0 -95
  151. package/src/utils/stringUtils.ts +0 -103
  152. package/src/utils/tempDir.ts +0 -24
  153. package/src/utils/zipUtils.ts +0 -14
  154. package/test/ValdiSmokeTest.ts +0 -279
  155. package/test/helpers/AsyncHelpers.ts +0 -113
  156. package/test/helpers/CommandHelpers.ts +0 -37
  157. package/test/helpers/ProjectHelpers.ts +0 -153
  158. package/test/helpers/StreamHelpers.ts +0 -37
  159. package/test/helpers/TypeScriptClient.ts +0 -217
  160. package/tsconfig.dist.json +0 -8
  161. package/tsconfig.json +0 -42
@@ -1,257 +0,0 @@
1
- import fs from 'fs';
2
- import os from 'os';
3
- import path from 'path';
4
- import yaml from 'yaml';
5
- import * as Constants from '../core/constants';
6
- import { CliError } from '../core/errors';
7
-
8
- export type Replacements = { [key: string]: string };
9
-
10
- export class TemplateFile {
11
- readonly templatePath: string;
12
- readonly metaTemplatePath: string;
13
-
14
- // Defaults to cwd
15
- readonly outputPath: string;
16
- readonly replacements: Replacements;
17
-
18
- // Name/Path without .template suffix
19
- readonly baseName: string;
20
- readonly basePath: string;
21
-
22
- private constructor(templatePath: string, outputPath?: string, replacements: Replacements = {}) {
23
- this.templatePath = path.normalize(templatePath);
24
- this.metaTemplatePath = path.join(Constants.META_DIR_PATH, this.templatePath);
25
-
26
- if (!fileExists(this.metaTemplatePath)) {
27
- throw new CliError(`Template file not found: ${this.metaTemplatePath}`);
28
- }
29
-
30
- const parsedPath = path.parse(this.templatePath);
31
- this.baseName = parsedPath.name;
32
- this.basePath = path.join(parsedPath.dir, parsedPath.name);
33
-
34
- this.outputPath = outputPath ?? path.join(process.cwd(), this.basePath);
35
- this.outputPath = path.normalize(this.outputPath);
36
-
37
- this.replacements = replacements;
38
- }
39
-
40
- static init(templatePath: string): TemplateFile {
41
- return new TemplateFile(templatePath);
42
- }
43
-
44
- withReplacements(replacements: Replacements): TemplateFile {
45
- return new TemplateFile(this.templatePath, this.outputPath, replacements);
46
- }
47
-
48
- withOutputPath(outputPath: string): TemplateFile {
49
- const newOutputPath = isDirectory(outputPath) ? path.join(outputPath, this.baseName) : outputPath;
50
- return new TemplateFile(this.templatePath, newOutputPath, this.replacements);
51
- }
52
-
53
- expandTemplate(): string {
54
- const metaTemplatePath = path.join(Constants.META_DIR_PATH, this.templatePath);
55
- return copyFileWithReplacement(metaTemplatePath, this.outputPath, this.replacements);
56
- }
57
- }
58
-
59
- export function resolveFilePath(pathString: string): string {
60
- if (pathString.startsWith('~')) {
61
- const tildeResolvedPath = path.join(os.homedir(), pathString.slice(1));
62
- return path.resolve(tildeResolvedPath);
63
- }
64
- return path.resolve(pathString);
65
- }
66
-
67
- export function fileExists(filePath: string): boolean {
68
- return fs.existsSync(filePath);
69
- }
70
-
71
- export function getUserConfig(): Constants.UserConfig {
72
- let resolvedPath: string | undefined;
73
-
74
- for (const filePath of Constants.VALDI_CONFIG_PATHS) {
75
- const unrolledPath = resolveFilePath(filePath);
76
- if (fs.existsSync(unrolledPath)) {
77
- resolvedPath = unrolledPath;
78
- break;
79
- }
80
- }
81
-
82
- if (resolvedPath === undefined) {
83
- throw new CliError(
84
- `Please create a Valdi config file in ${Constants.VALDI_CONFIG_PATHS[0] ?? ''} (Running 'valdi bootstrap' takes care of that for you)`,
85
- );
86
- }
87
-
88
- const configContents = fs.readFileSync(resolvedPath, 'utf8');
89
- const parsedYaml = yaml.parse(configContents) as Constants.UserConfig;
90
-
91
- return parsedYaml;
92
- }
93
-
94
- export function getAllFilePaths(directoryPath: string): string[] {
95
- directoryPath = resolveFilePath(directoryPath);
96
-
97
- const files: string[] = [];
98
- function traverseDirectories(dir: string) {
99
- fs.readdirSync(dir, { withFileTypes: true }).forEach(file => {
100
- const fullPath = path.join(dir, file.name);
101
- if (file.isDirectory()) {
102
- traverseDirectories(fullPath);
103
- return;
104
- }
105
-
106
- files.push(fullPath);
107
- });
108
- }
109
-
110
- traverseDirectories(directoryPath);
111
-
112
- return files;
113
- }
114
-
115
- export function isDirectoryEmpty(directoryPath: string): boolean {
116
- const absPath = resolveFilePath(directoryPath);
117
- const dir = fs.opendirSync(absPath);
118
- const firstEntry = dir.readSync();
119
- dir.closeSync();
120
- return firstEntry === null;
121
- }
122
-
123
- export function getFilesSortedByUpdatedTime(directoryPath: string): string[] {
124
- directoryPath = resolveFilePath(directoryPath);
125
- const files = getAllFilePaths(directoryPath);
126
-
127
- const fileStats = files.map(file => {
128
- const stats = fs.statSync(file);
129
- return { file, mtime: stats.mtime };
130
- });
131
-
132
- const sortedFiles = fileStats.sort((a, b) => b.mtime.getTime() - a.mtime.getTime()).map(fileStat => fileStat.file);
133
-
134
- return sortedFiles;
135
- }
136
-
137
- export function isDirectory(filePath: string): boolean {
138
- return fs.existsSync(filePath) && fs.statSync(filePath).isDirectory();
139
- }
140
-
141
- export function hasExtension(filePath: string, extension: string): boolean {
142
- return fs.existsSync(filePath) && path.extname(filePath) === extension;
143
- }
144
-
145
- export function processReplacements(input: string, replacements: Replacements): string {
146
- let outputContent = input;
147
- for (const [key, value] of Object.entries(replacements)) {
148
- const placeholder = `{{${key}}}`;
149
- const regex = new RegExp(placeholder, 'g'); // Global replace for all occurrences
150
- outputContent = outputContent.replace(regex, value);
151
- }
152
-
153
- return outputContent;
154
- }
155
-
156
- // Returns outputFilePath
157
- export function copyFileWithReplacement(
158
- inputFilePath: string,
159
- outputFilePath: string,
160
- replacements: Replacements,
161
- ): string {
162
- // Read the input file content
163
- const inputContent = fs.readFileSync(inputFilePath, 'utf8');
164
-
165
- // Replace the keys in the input content with the corresponding values
166
- const outputContent = processReplacements(inputContent, replacements);
167
-
168
- // Ensure the output directory exists
169
- const outputDir = path.dirname(outputFilePath);
170
- if (!fs.existsSync(outputDir)) {
171
- fs.mkdirSync(outputDir, { recursive: true });
172
- }
173
-
174
- // Write the replaced content to the output file
175
- fs.writeFileSync(outputFilePath, outputContent);
176
-
177
- return outputFilePath;
178
- }
179
-
180
- export function deleteAll(destPath: string) {
181
- if (!isDirectory(destPath)) {
182
- return;
183
- }
184
-
185
- fs.readdirSync(destPath, { withFileTypes: true }).forEach(item => {
186
- const fullPath = path.join(destPath, item.name);
187
- fs.rmSync(fullPath, { recursive: true });
188
- });
189
- }
190
-
191
- // Util functions for copying files
192
- export interface CopyConfig {
193
- whitelist?: string[];
194
- blacklist?: string[];
195
- }
196
-
197
- export function loadConfig(configPath: string): CopyConfig {
198
- const ext = path.extname(configPath).toLowerCase();
199
- const rawConfig = fs.readFileSync(configPath, 'utf8');
200
-
201
- if (ext === '.json') {
202
- return JSON.parse(rawConfig) as CopyConfig;
203
- } else {
204
- throw new Error(`Unsupported config file format: ${ext}`);
205
- }
206
- }
207
-
208
- function precompilePatterns(patterns?: string[]): RegExp[] {
209
- return patterns?.map(pattern => new RegExp(pattern)) ?? [];
210
- }
211
-
212
- function matchesCompiledPatterns(compiledPatterns: RegExp[], filePath: string): boolean {
213
- return compiledPatterns.some(regex => regex.test(filePath));
214
- }
215
-
216
- function isPathAllowed(filePath: string, blacklist: RegExp[], whitelist: RegExp[]): boolean {
217
- const normalizedPath = resolveFilePath(filePath);
218
-
219
- if (blacklist.length > 0 && matchesCompiledPatterns(blacklist, normalizedPath)) {
220
- return false;
221
- }
222
-
223
- if (whitelist.length > 0) {
224
- return matchesCompiledPatterns(whitelist, normalizedPath);
225
- }
226
-
227
- return true;
228
- }
229
-
230
- export function copyFiles(sourceDir: string, destDir: string, config: CopyConfig = {}) {
231
- // Precompile patterns for efficiency.
232
- const blacklist = precompilePatterns(config.blacklist);
233
- const whitelist = precompilePatterns(config.whitelist);
234
-
235
- fs.cpSync(sourceDir, destDir, {
236
- recursive: true,
237
- filter: (src): boolean => {
238
- return isPathAllowed(src, blacklist, whitelist);
239
- },
240
- });
241
- }
242
-
243
- export function removeFileOrDirAtPath(path: string): boolean {
244
- if (!fs.existsSync(path)) {
245
- return false;
246
- }
247
-
248
- const outputStat = fs.lstatSync(path);
249
- if (outputStat.isFile()) {
250
- fs.rmSync(path);
251
- return true;
252
- } else if (outputStat.isDirectory()) {
253
- fs.rmSync(path, { recursive: true });
254
- return true;
255
- }
256
- return false;
257
- }
@@ -1,102 +0,0 @@
1
- import { runCliCommand } from './cliUtils';
2
-
3
- /**
4
- * Parses a GitHub repo URL (e.g. https://github.com/Snapchat/Valdi or .git variant)
5
- * into "owner/repo" for the GitHub API.
6
- */
7
- function parseGitHubRepoSlug(repoUrl: string): string {
8
- const normalized = repoUrl.replace(/\.git$/u, '').trim();
9
- const match = normalized.match(/github\.com[/:]([^/]+)\/([^/]+?)(?:[/]?$)/u);
10
- if (!match) {
11
- throw new Error(`Invalid GitHub URL: ${repoUrl}`);
12
- }
13
- return `${match[1]}/${match[2]}`;
14
- }
15
-
16
- const LATEST_RELEASE_HINT =
17
- 'Use --valdiVersion=latest to retry, or --valdiVersion=<tag> (e.g. main or v1.0.0) to pin a version.';
18
-
19
- /**
20
- * Returns the tag name of the release marked as "Latest" on GitHub (releases UI).
21
- * Uses only the GitHub Releases API so the result matches what GitHub shows.
22
- * Falls back to git ls-remote only when the repo has no releases (404).
23
- */
24
- export async function getLatestReleaseTag(repoUrl: string): Promise<string> {
25
- const slug = parseGitHubRepoSlug(repoUrl);
26
- let response: Response;
27
- try {
28
- response = await fetch(`https://api.github.com/repos/${slug}/releases/latest`, {
29
- headers: { 'User-Agent': 'Valdi-CLI' },
30
- });
31
- } catch (error) {
32
- const message = error instanceof Error ? error.message : String(error);
33
- throw new Error(
34
- `Could not fetch latest release from GitHub (${message}). ${LATEST_RELEASE_HINT}`,
35
- );
36
- }
37
- if (!response.ok) {
38
- if (response.status === 404) {
39
- // No releases or no "latest" release – fall back to git ls-remote
40
- return getLatestReleaseTagFromGit(repoUrl);
41
- }
42
- throw new Error(
43
- `GitHub API returned ${response.status} (rate limit or server error). ${LATEST_RELEASE_HINT}`,
44
- );
45
- }
46
- const data = (await response.json()) as { tag_name?: string };
47
- if (typeof data?.tag_name !== 'string') {
48
- throw new Error(`Invalid response: missing tag_name. ${LATEST_RELEASE_HINT}`);
49
- }
50
- return data.tag_name;
51
- }
52
-
53
- /** Matches semver-like tags (e.g. v1.0.0, 2.3.1, beta-0.0.1). Captures major, minor, patch. */
54
- const SEMVER_TAG_REGEX = /^(?:\w+-)?v?(\d+)\.(\d+)\.(\d+)(?:[-.]\S+)?$/u;
55
-
56
- function parseSemverTag(tag: string): [number, number, number] | null {
57
- const m = tag.match(SEMVER_TAG_REGEX);
58
- if (!m) return null;
59
- return [Number.parseInt(m[1]!, 10), Number.parseInt(m[2]!, 10), Number.parseInt(m[3]!, 10)];
60
- }
61
-
62
- function compareSemverTags(a: string, b: string): number {
63
- const va = parseSemverTag(a);
64
- const vb = parseSemverTag(b);
65
- if (va && vb) {
66
- return va[0] - vb[0] || va[1] - vb[1] || va[2] - vb[2];
67
- }
68
- if (va) return 1; // non-semver (b) sorts before semver (a)
69
- if (vb) return -1; // non-semver (a) sorts before semver (b)
70
- return a.localeCompare(b, undefined, { numeric: true });
71
- }
72
-
73
- /**
74
- * Fallback: resolve tag refs via git ls-remote and return the latest tag by semver.
75
- * git ls-remote returns refs sorted by refname (alphabetically), so we parse all tags
76
- * and pick the highest semantic version.
77
- */
78
- async function getLatestReleaseTagFromGit(repoUrl: string): Promise<string> {
79
- const gitUrl = repoUrl.includes('.git') ? repoUrl : `${repoUrl}.git`;
80
- const result = await runCliCommand(`git ls-remote --tags --refs ${gitUrl}`, undefined, true);
81
- const lines = result.stdout.trim().split('\n').filter(Boolean);
82
- const tags: string[] = [];
83
- for (const line of lines) {
84
- const ref = line.split(/\s+/)[1];
85
- if (ref?.startsWith('refs/tags/')) {
86
- const tag = ref.slice('refs/tags/'.length);
87
- if (tag) tags.push(tag);
88
- }
89
- }
90
- if (tags.length === 0) {
91
- throw new Error('No tags found in repository');
92
- }
93
- tags.sort(compareSemverTags);
94
- return tags[tags.length - 1]!;
95
- }
96
-
97
- /** @deprecated Use getLatestReleaseTag for the GitHub "Latest" release; this returns an arbitrary tag from git ls-remote. */
98
- export async function resolveLatestReleaseRef(repoUrl: string): Promise<string> {
99
- const tag = await getLatestReleaseTagFromGit(repoUrl);
100
- // Template expects either ref (refs/tags/X) or tag name for archive URL; we use tag name.
101
- return tag;
102
- }
@@ -1,30 +0,0 @@
1
- import type { JSONPath, ModificationOptions } from 'jsonc-parser';
2
- import { applyEdits, modify, parse } from 'jsonc-parser';
3
-
4
- export class JSONCFile<T> {
5
- constructor(
6
- private content: string,
7
- readonly value: T,
8
- ) {}
9
-
10
- static parse<T>(content: string): JSONCFile<T> {
11
- const parsed = parse(content) as T;
12
-
13
- return new JSONCFile(content, parsed);
14
- }
15
-
16
- static fromObject<T>(object: T): JSONCFile<T> {
17
- const content = JSON.stringify(object, null, 2);
18
- return JSONCFile.parse<T>(content);
19
- }
20
-
21
- toJSONString(): string {
22
- return this.content;
23
- }
24
-
25
- updating(path: JSONPath, value: unknown, options: ModificationOptions): JSONCFile<T> {
26
- const edits = modify(this.content, path, value, options);
27
-
28
- return new JSONCFile(applyEdits(this.content, edits), this.value);
29
- }
30
- }
@@ -1,190 +0,0 @@
1
- /**
2
- * Common functions shared between the linting commands
3
- */
4
- import fs from 'fs';
5
- import path from 'path';
6
- import eslint, { ESLint } from 'eslint';
7
- import prettier from 'prettier';
8
- import { ANSI_COLORS, TEMPLATE_BASE_PATHS } from '../core/constants';
9
- import { CliError } from '../core/errors';
10
- import { getUserConfirmation } from './cliUtils';
11
- import { TemplateFile, fileExists, hasExtension, isDirectory } from './fileUtils';
12
- import { wrapInColor } from './logUtils';
13
-
14
- export enum RESULT_STATUS {
15
- SKIPPED = 'skipped',
16
- DIRECTORY = 'directory',
17
- NEEDS_FORMAT = 'needs format',
18
- VALID = 'valid',
19
- CHANGED = 'changed',
20
- }
21
-
22
- export type FileLintStatus = [string, RESULT_STATUS];
23
-
24
- // Returns the config path if it exists, otherwise prompts the user to create one
25
- export async function maybeSetupPrettier(): Promise<string> {
26
- let prettierConfigPath = await getPrettierConfigPath();
27
-
28
- if (prettierConfigPath === null) {
29
- const initMessage = `No prettier config found. Would you like to create one here? ${wrapInColor(process.cwd(), ANSI_COLORS.GREEN_COLOR)}`;
30
- const shouldInitPrettier = await getUserConfirmation(initMessage, true);
31
-
32
- if (!shouldInitPrettier) {
33
- throw new CliError('Prettier config is required, aborting...');
34
- }
35
-
36
- prettierConfigPath = createPrettierConfig();
37
-
38
- // Need to clear the cache so the newly created config can be resolved
39
- // in the same execution cycle
40
- await prettier.clearConfigCache();
41
- }
42
-
43
- return prettierConfigPath;
44
- }
45
-
46
- export async function getPrettierConfigPath(): Promise<string | null> {
47
- // Starts searching at process.cwd() by default
48
- // Note that VALIDing in process.cwd() as a parameter will NOT work
49
- const prettierConfigPath = await prettier.resolveConfigFile();
50
-
51
- return prettierConfigPath;
52
- }
53
-
54
- export function createPrettierConfig(): string {
55
- const prettierTemplateFile = TemplateFile.init(TEMPLATE_BASE_PATHS.PRETTIER_CONFIG);
56
- return prettierTemplateFile.expandTemplate();
57
- }
58
-
59
- // Prompts user to create eslint config files if they don't exist.
60
- export async function maybeSetupEslint() {
61
- if (!fileExists('.eslintrc.js')) {
62
- const initMessage = `No eslintrc found. Would you like to create one here? ${wrapInColor(process.cwd(), ANSI_COLORS.GREEN_COLOR)}`;
63
- const shouldInitEslintrc = await getUserConfirmation(initMessage, true);
64
-
65
- if (!shouldInitEslintrc) {
66
- throw new CliError('eslintrc config is required, aborting...');
67
- }
68
-
69
- createEslintConfig();
70
- }
71
-
72
- if (!fileExists('package.json')) {
73
- const initMessage = `No package.json found. Would you like to create one here? ${wrapInColor(process.cwd(), ANSI_COLORS.GREEN_COLOR)}`;
74
- const shouldInitEslintrc = await getUserConfirmation(initMessage, true);
75
-
76
- if (!shouldInitEslintrc) {
77
- throw new CliError('package.json config is required, aborting...');
78
- }
79
-
80
- createPackageConfig();
81
-
82
- throw new CliError('New package.json created, run `npm install` before trying again.');
83
- }
84
- }
85
-
86
- export function createEslintConfig(): string {
87
- const eslintConfigFile = TemplateFile.init(TEMPLATE_BASE_PATHS.ESLINT_CONFIG);
88
- return eslintConfigFile.expandTemplate();
89
- }
90
-
91
- export function createPackageConfig(): string {
92
- const packageConfigFile = TemplateFile.init(TEMPLATE_BASE_PATHS.ESLINT_PACKAGE_JSON_CONFIG);
93
- return packageConfigFile.expandTemplate();
94
- }
95
-
96
- export async function getPrettierConfig(configPath: string): Promise<prettier.Options | null> {
97
- return await prettier.resolveConfig(configPath);
98
- }
99
-
100
- export async function checkAndFormatFiles(
101
- filePaths: string[],
102
- prettierOptions: prettier.Options,
103
- shouldFormat: boolean = false,
104
- ): Promise<FileLintStatus[]> {
105
- const linter = new eslint.ESLint({fix: true});
106
- const results: FileLintStatus[] = await Promise.all(
107
- filePaths.map(async fp => {
108
- const filePath = path.resolve(fp);
109
-
110
- if (isDirectory(filePath)) {
111
- return [fp, RESULT_STATUS.DIRECTORY];
112
- }
113
-
114
- if (hasExtension(filePath, '.json')) {
115
- return [fp, RESULT_STATUS.SKIPPED];
116
- }
117
-
118
- const fileContent = fs.readFileSync(filePath, 'utf8');
119
- const prettierFileInfo = await prettier.getFileInfo(filePath);
120
-
121
- if (prettierFileInfo.inferredParser === null) {
122
- return [fp, RESULT_STATUS.SKIPPED];
123
- }
124
-
125
- const lintResults = await linter.lintFiles([filePath]);
126
- const needsLint = lintResults.length > 0;
127
- let isLintFormatted = false;
128
-
129
- if (shouldFormat && needsLint) {
130
- console.log(lintResults[0]?.messages[0]?.message);
131
- await ESLint.outputFixes(lintResults);
132
- isLintFormatted = true;
133
- }
134
-
135
- const needsPrettier = await prettier.check(fileContent, { ...prettierOptions, filepath: filePath });
136
- let isPrettierFormatted = false;
137
-
138
- if (shouldFormat && !needsPrettier) {
139
- const formattedContent = await prettier.format(fileContent, { ...prettierOptions, filepath: filePath });
140
- fs.writeFileSync(filePath, formattedContent, 'utf8');
141
-
142
- isPrettierFormatted = true;
143
-
144
- }
145
-
146
- if (isPrettierFormatted || isLintFormatted) {
147
- return [fp, RESULT_STATUS.CHANGED];
148
- }
149
-
150
- const formattedStatus = isPrettierFormatted && isLintFormatted ? RESULT_STATUS.VALID : RESULT_STATUS.NEEDS_FORMAT;
151
- return [fp, formattedStatus];
152
- }),
153
- );
154
-
155
- return results;
156
- }
157
-
158
- export function printStatus(lintResults: FileLintStatus[], showSkipped: boolean = false) {
159
- let textColor = ANSI_COLORS.RESET_COLOR;
160
-
161
- for (const [shortPath, status] of lintResults) {
162
- switch (status) {
163
- case RESULT_STATUS.DIRECTORY: {
164
- continue;
165
- }
166
- case RESULT_STATUS.SKIPPED: {
167
- if (!showSkipped) {
168
- continue;
169
- }
170
-
171
- textColor = ANSI_COLORS.GRAY_COLOR;
172
- break;
173
- }
174
- case RESULT_STATUS.VALID: {
175
- textColor = ANSI_COLORS.GRAY_COLOR;
176
- break;
177
- }
178
- case RESULT_STATUS.NEEDS_FORMAT: {
179
- textColor = ANSI_COLORS.YELLOW_COLOR;
180
- break;
181
- }
182
- case RESULT_STATUS.CHANGED: {
183
- textColor = ANSI_COLORS.YELLOW_COLOR;
184
- break;
185
- }
186
- }
187
-
188
- console.log(`${wrapInColor(shortPath, textColor)} - ${status}`);
189
- }
190
- }