@snap/valdi 1.0.1

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 (143) hide show
  1. package/.bazelignore +2 -0
  2. package/.bootstrap/apps/cli_application/AGENTS.md.template +215 -0
  3. package/.bootstrap/apps/cli_application/BUILD.bazel.template +7 -0
  4. package/.bootstrap/apps/cli_application/modules/{{MODULE_NAME}}/BUILD.bazel.template +11 -0
  5. package/.bootstrap/apps/cli_application/modules/{{MODULE_NAME}}/src/index.ts +1 -0
  6. package/.bootstrap/apps/ui_application/.eslint.rc +27 -0
  7. package/.bootstrap/apps/ui_application/AGENTS.md.template +202 -0
  8. package/.bootstrap/apps/ui_application/BUILD.bazel.template +19 -0
  9. package/.bootstrap/apps/ui_application/modules/{{MODULE_NAME}}/BUILD.bazel.template +21 -0
  10. package/.bootstrap/apps/ui_application/modules/{{MODULE_NAME}}/res/valdi@3x.png +0 -0
  11. package/.bootstrap/apps/ui_application/modules/{{MODULE_NAME}}/src/App.tsx +133 -0
  12. package/.bootstrap/apps/ui_application/package.json +24 -0
  13. package/.bootstrap/modules/cpp_bridge_module/BUILD.bazel.template +21 -0
  14. package/.bootstrap/modules/cpp_bridge_module/cpp/CalculatorModuleFactory.cpp.template +29 -0
  15. package/.bootstrap/modules/cpp_bridge_module/src/Calculator.d.ts +1 -0
  16. package/.bootstrap/modules/ios_android_bridge_module/BUILD.bazel.template +39 -0
  17. package/.bootstrap/modules/ios_android_bridge_module/android/CalculatorModuleFactory.kt.template +18 -0
  18. package/.bootstrap/modules/ios_android_bridge_module/ios/SCCCalculatorModuleFactory.m.template +31 -0
  19. package/.bootstrap/modules/ios_android_bridge_module/src/Calculator.d.ts +4 -0
  20. package/.bootstrap/modules/ios_android_view_module/BUILD.bazel.template +41 -0
  21. package/.bootstrap/modules/ios_android_view_module/android/CircleView.kt.template +42 -0
  22. package/.bootstrap/modules/ios_android_view_module/android/CircleViewAttributesBinder.kt.template +60 -0
  23. package/.bootstrap/modules/ios_android_view_module/ios/SCCCircleView.h +6 -0
  24. package/.bootstrap/modules/ios_android_view_module/ios/SCCCircleView.m +82 -0
  25. package/.bootstrap/modules/ios_android_view_module/src/Circle.tsx.template +15 -0
  26. package/.bootstrap/modules/ui_component/BUILD.bazel.template +34 -0
  27. package/.bootstrap/modules/ui_component/src/NewModuleComponent.tsx +45 -0
  28. package/.config/copyconfig.json +10 -0
  29. package/.editorconfig +21 -0
  30. package/.eslintignore +1 -0
  31. package/.eslintrc.js +72 -0
  32. package/.metadata/.bazelrc.template +91 -0
  33. package/.metadata/.bazelversion.template +1 -0
  34. package/.metadata/.eslintrc.js.template +27 -0
  35. package/.metadata/.gitignore.template +4 -0
  36. package/.metadata/.prettierrc.json.template +7 -0
  37. package/.metadata/.watchmanconfig.template +8 -0
  38. package/.metadata/README.md.template +31 -0
  39. package/.metadata/WORKSPACE.template +57 -0
  40. package/.metadata/config.yaml.template +1 -0
  41. package/.metadata/package.json.template +23 -0
  42. package/.prettierignore +2 -0
  43. package/.prettierrc.json +7 -0
  44. package/README.md +123 -0
  45. package/dist/commands/bootstrap.js +233 -0
  46. package/dist/commands/build.js +67 -0
  47. package/dist/commands/devSetup.js +18 -0
  48. package/dist/commands/doctor.js +892 -0
  49. package/dist/commands/export.js +84 -0
  50. package/dist/commands/hotreload.js +89 -0
  51. package/dist/commands/install.js +71 -0
  52. package/dist/commands/lint.js +18 -0
  53. package/dist/commands/lint_commands/lintCheck.js +31 -0
  54. package/dist/commands/lint_commands/lintFormat.js +31 -0
  55. package/dist/commands/log.js +84 -0
  56. package/dist/commands/newModule.js +208 -0
  57. package/dist/commands/package.js +66 -0
  58. package/dist/commands/projectsync.js +316 -0
  59. package/dist/commands/test.js +54 -0
  60. package/dist/core/constants.js +76 -0
  61. package/dist/core/errors.js +12 -0
  62. package/dist/index.js +22 -0
  63. package/dist/setup/DevSetupHelper.js +146 -0
  64. package/dist/setup/linuxSetup.js +31 -0
  65. package/dist/setup/macOSSetup.js +35 -0
  66. package/dist/setup/setupEntryPoint.js +56 -0
  67. package/dist/setup/versions.js +8 -0
  68. package/dist/utils/ArgumentsResolver.js +23 -0
  69. package/dist/utils/BazelClient.js +219 -0
  70. package/dist/utils/Digraph.js +71 -0
  71. package/dist/utils/LoadingIndicator.js +38 -0
  72. package/dist/utils/applicationUtils.js +201 -0
  73. package/dist/utils/buildInfo.js +60 -0
  74. package/dist/utils/byString.js +6 -0
  75. package/dist/utils/cliUtils.js +93 -0
  76. package/dist/utils/copyBootstrapFiles.js +26 -0
  77. package/dist/utils/deviceUtils.js +72 -0
  78. package/dist/utils/errorUtils.js +55 -0
  79. package/dist/utils/fileUtils.js +204 -0
  80. package/dist/utils/githubUtils.js +8 -0
  81. package/dist/utils/jsonUtils.js +28 -0
  82. package/dist/utils/lintUtils.js +149 -0
  83. package/dist/utils/logUtils.js +8 -0
  84. package/dist/utils/pathUtils.js +12 -0
  85. package/dist/utils/stringUtils.js +17 -0
  86. package/dist/utils/stringUtils.spec.js +18 -0
  87. package/dist/utils/tempDir.js +26 -0
  88. package/dist/utils/zipUtils.js +16 -0
  89. package/package.json +51 -0
  90. package/prettier.config.js +4 -0
  91. package/spec/support/jasmine.json +6 -0
  92. package/src/commands/bootstrap.ts +317 -0
  93. package/src/commands/build.ts +89 -0
  94. package/src/commands/devSetup.ts +17 -0
  95. package/src/commands/doctor.ts +1422 -0
  96. package/src/commands/export.ts +131 -0
  97. package/src/commands/hotreload.ts +108 -0
  98. package/src/commands/install.ts +93 -0
  99. package/src/commands/lint.ts +15 -0
  100. package/src/commands/lint_commands/lintCheck.ts +53 -0
  101. package/src/commands/lint_commands/lintFormat.ts +49 -0
  102. package/src/commands/log.ts +108 -0
  103. package/src/commands/newModule.ts +287 -0
  104. package/src/commands/package.ts +102 -0
  105. package/src/commands/projectsync.ts +488 -0
  106. package/src/commands/test.ts +68 -0
  107. package/src/core/constants.ts +95 -0
  108. package/src/core/errors.ts +10 -0
  109. package/src/index.ts +22 -0
  110. package/src/setup/DevSetupHelper.ts +188 -0
  111. package/src/setup/linuxSetup.ts +38 -0
  112. package/src/setup/macOSSetup.ts +42 -0
  113. package/src/setup/setupEntryPoint.ts +64 -0
  114. package/src/setup/versions.ts +8 -0
  115. package/src/utils/ArgumentsResolver.ts +23 -0
  116. package/src/utils/BazelClient.ts +285 -0
  117. package/src/utils/Digraph.ts +81 -0
  118. package/src/utils/LoadingIndicator.ts +43 -0
  119. package/src/utils/applicationUtils.ts +276 -0
  120. package/src/utils/buildInfo.ts +99 -0
  121. package/src/utils/byString.ts +3 -0
  122. package/src/utils/cliUtils.ts +112 -0
  123. package/src/utils/copyBootstrapFiles.ts +30 -0
  124. package/src/utils/deviceUtils.ts +76 -0
  125. package/src/utils/errorUtils.ts +63 -0
  126. package/src/utils/fileUtils.ts +257 -0
  127. package/src/utils/githubUtils.ts +6 -0
  128. package/src/utils/jsonUtils.ts +30 -0
  129. package/src/utils/lintUtils.ts +190 -0
  130. package/src/utils/logUtils.ts +9 -0
  131. package/src/utils/pathUtils.ts +12 -0
  132. package/src/utils/stringUtils.spec.ts +19 -0
  133. package/src/utils/stringUtils.ts +15 -0
  134. package/src/utils/tempDir.ts +24 -0
  135. package/src/utils/zipUtils.ts +14 -0
  136. package/test/ValdiSmokeTest.ts +278 -0
  137. package/test/helpers/AsyncHelpers.ts +113 -0
  138. package/test/helpers/CommandHelpers.ts +37 -0
  139. package/test/helpers/ProjectHelpers.ts +153 -0
  140. package/test/helpers/StreamHelpers.ts +37 -0
  141. package/test/helpers/TypeScriptClient.ts +217 -0
  142. package/tsconfig.dist.json +8 -0
  143. package/tsconfig.json +42 -0
@@ -0,0 +1,76 @@
1
+ import { Architecture, PLATFORM } from '../core/constants';
2
+ import { CliError } from '../core/errors';
3
+ import { runCliCommand, spawnCliCommand } from './cliUtils';
4
+
5
+ function parseAndroidDevices(devicesString: string): string[] {
6
+ const deviceIDs: string[] = devicesString
7
+ .split('\n')
8
+ .filter(line => line.trim().endsWith('device') && !line.startsWith('List of devices'))
9
+ .map(line => line.split('\t')?.[0]?.trim() ?? ''); // Extract the device ID
10
+
11
+ return deviceIDs ?? [];
12
+ }
13
+
14
+ export async function getArchitectureForAndroidDevice(deviceId: string): Promise<Architecture> {
15
+ const { stdout } = await runCliCommand(`adb -s ${deviceId} shell getprop ro.product.cpu.abi`, undefined, true);
16
+
17
+ const architectureString = stdout.trim();
18
+
19
+ switch (architectureString) {
20
+ case 'arm64-v8a': {
21
+ return Architecture.ARM64;
22
+ }
23
+ case 'armeabi-v7a': {
24
+ return Architecture.ARMV7;
25
+ }
26
+ case 'armeabi': {
27
+ return Architecture.ARMV7;
28
+ }
29
+ case 'x86_64': {
30
+ return Architecture.X86_64;
31
+ }
32
+ default: {
33
+ throw new CliError(`Unsupported device architecture: ${architectureString}`);
34
+ }
35
+ }
36
+ }
37
+
38
+ export function getAllArchitecturesForAndroid() {
39
+ return [Architecture.ARM64, Architecture.ARMV7, Architecture.X86_64];
40
+ }
41
+
42
+ export async function getConnectedAndroidDevices(): Promise<string[]> {
43
+ const commandListDevices = 'adb devices';
44
+ const { stdout: devicesString } = await runCliCommand(commandListDevices, undefined, true);
45
+ const androidDevices = parseAndroidDevices(devicesString);
46
+
47
+ return androidDevices;
48
+ }
49
+
50
+ export async function getConnectedIOSDevices(): Promise<string[]> {
51
+ // eslint-disable-next-line unicorn/no-useless-promise-resolve-reject
52
+ return Promise.resolve(['-1']);
53
+ }
54
+
55
+ export async function getConnectedDevices(platform: string): Promise<string[]> {
56
+ if (platform === PLATFORM.ANDROID) {
57
+ const androidDevices = await getConnectedAndroidDevices();
58
+ return androidDevices;
59
+ } else if (platform === PLATFORM.IOS) {
60
+ const iosDevices = await getConnectedIOSDevices();
61
+ return iosDevices;
62
+ }
63
+
64
+ return [];
65
+ }
66
+
67
+ export async function installAndroidApk(apkPath: string, emulatorId?: string) {
68
+ const idString = emulatorId ? ` -s ${emulatorId} ` : ' ';
69
+ const commandInstallApk = `adb${idString}install -r ${apkPath}`;
70
+ await spawnCliCommand(commandInstallApk, undefined, 'pipe', false, true);
71
+ }
72
+
73
+ export async function startAndroidActivity(activityName: string) {
74
+ const commandStartActivity = `adb shell am start -n ${activityName}`;
75
+ await spawnCliCommand(commandStartActivity, undefined, 'pipe', false, true);
76
+ }
@@ -0,0 +1,63 @@
1
+ /* eslint-disable @typescript-eslint/no-unsafe-call */
2
+ /* eslint-disable @typescript-eslint/no-unsafe-member-access */
3
+ /* eslint-disable @typescript-eslint/no-unsafe-assignment */
4
+ /* eslint-disable @typescript-eslint/no-unsafe-argument */
5
+ import { ANSI_COLORS } from '../core/constants';
6
+ import { CliError } from '../core/errors';
7
+ import { ArgumentsResolver } from './ArgumentsResolver';
8
+ import { wrapInColor } from './logUtils';
9
+
10
+ function logReproduceWith(keys: string[], additionalResolvedArguments: any) {
11
+ const allArguments = ['valdi', ...process.argv.slice(2)];
12
+ keys.sort();
13
+
14
+ for (const key of keys.sort()) {
15
+ const value = additionalResolvedArguments[key];
16
+ if (Array.isArray(value)) {
17
+ for (const item of value) {
18
+ allArguments.push(`--${key}`, item.toString());
19
+ }
20
+ } else {
21
+ allArguments.push(`--${key}`, value.toString());
22
+ }
23
+ }
24
+
25
+ console.log(
26
+ `\n${wrapInColor('Note: Use the following command next time to reproduce without prompts', ANSI_COLORS.GREEN_COLOR)}\n${allArguments.join(' ')}\n`,
27
+ );
28
+ }
29
+
30
+ export function logReproduceThisCommandIfNeeded<T>(argumentsResolver: ArgumentsResolver<T>) {
31
+ const keys = Object.keys(argumentsResolver.additionalResolvedArguments);
32
+ if (keys.length > 0) {
33
+ logReproduceWith(keys, argumentsResolver.additionalResolvedArguments);
34
+ }
35
+ }
36
+
37
+ export function makeCommandHandler<T>(cb: (argv: ArgumentsResolver<T>) => Promise<void>): (argv: T) => void {
38
+ const command = async (argv: T) => {
39
+ const argumentsResolver = new ArgumentsResolver(argv);
40
+ try {
41
+ await cb(argumentsResolver);
42
+ process.exitCode = 0;
43
+ } catch (error) {
44
+ process.exitCode = 1;
45
+
46
+ if (error instanceof CliError) {
47
+ // Managed Error
48
+ console.log(wrapInColor(error.message, error.textColor));
49
+ } else if (error instanceof Error) {
50
+ // Unmanaged Error
51
+ console.log(error.stack);
52
+ console.log(wrapInColor(error.message, ANSI_COLORS.RED_COLOR));
53
+ } else {
54
+ // Something went really wrong
55
+ throw error;
56
+ }
57
+ }
58
+ };
59
+
60
+ return (argv: T) => {
61
+ void command(argv);
62
+ };
63
+ }
@@ -0,0 +1,257 @@
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
+ }
@@ -0,0 +1,6 @@
1
+ import { runCliCommand } from './cliUtils';
2
+
3
+ export async function resolveLatestReleaseRef(repoUrl: string): Promise<string> {
4
+ const result = await runCliCommand(`git ls-remote --tags --refs ${repoUrl}`, undefined, true);
5
+ return result.stdout.trim().split(/\s+/)[1]!;
6
+ }
@@ -0,0 +1,30 @@
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
+ }
@@ -0,0 +1,190 @@
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
+ }
@@ -0,0 +1,9 @@
1
+ import * as Constants from '../core/constants';
2
+
3
+ export function wrapInColor(
4
+ s: string | undefined,
5
+ color: Constants.ANSI_COLORS,
6
+ reset_color: Constants.ANSI_COLORS = Constants.ANSI_COLORS.RESET_COLOR,
7
+ ): string {
8
+ return `${color}${s ?? ''}${reset_color}`;
9
+ }
@@ -0,0 +1,12 @@
1
+ import path from 'path';
2
+
3
+ /**
4
+ * Version of path.relative() that resolves equal paths to .
5
+ */
6
+ export function relativePathTo(from: string, to: string): string {
7
+ const output = path.relative(from, to);
8
+ if (!output) {
9
+ return '.';
10
+ }
11
+ return output;
12
+ }
@@ -0,0 +1,19 @@
1
+ import 'jasmine';
2
+ import { toPascalCase, toSnakeCase } from './stringUtils';
3
+
4
+ describe('stringUtils', () => {
5
+ it('converts strings to pascal case', () => {
6
+ const testCases: [string, string][] = [['hello', 'Hello'], ['hello world', 'HelloWorld'], ['My New Module', 'MyNewModule'], ['my_new_module', 'MyNewModule']];
7
+ testCases.forEach(([input, expected]) => {
8
+ expect(toPascalCase(input)).toBe(expected);
9
+ });
10
+ });
11
+
12
+ it('converts strings to snake case', () => {
13
+ const testCases: [string, string][] = [['hello', 'hello'], ['hello world', 'hello_world']];
14
+ testCases.forEach(([input, expected]) => {
15
+ expect(toSnakeCase(input)).toBe(expected);
16
+ });
17
+ });
18
+ });
19
+
@@ -0,0 +1,15 @@
1
+ const wordSplitRegex = /[\W_]/;
2
+
3
+ export function toPascalCase(str: string): string {
4
+ const words = str.trim().toLowerCase().split(wordSplitRegex);
5
+ return words.reduce((acc, curr) => {
6
+ const [firstChar, ...rest] = curr;
7
+ const pascalCaseWord = firstChar?.toUpperCase()?.concat(rest.join('')) ?? '';
8
+ return acc + pascalCaseWord;
9
+ }, '');
10
+ }
11
+
12
+ export function toSnakeCase(str: string): string {
13
+ const words = str.trim().toLowerCase().split(wordSplitRegex);
14
+ return words.join('_');
15
+ }