@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,131 @@
1
+ import * as fs from 'fs';
2
+ import path from 'path';
3
+ import type { Argv } from 'yargs';
4
+ import { ALL_ARCHITECTURES, ANSI_COLORS, PLATFORM } from '../core/constants';
5
+ import { CliError } from '../core/errors';
6
+ import type { ArgumentsResolver } from '../utils/ArgumentsResolver';
7
+ import { BazelClient } from '../utils/BazelClient';
8
+ import type { SharedCommandParameters } from '../utils/applicationUtils';
9
+ import {
10
+ exportedLibraryExtensionForPlatform,
11
+ getExportedLibraryTargetTagForPlatform,
12
+ getOutputFilePath,
13
+ makeArgsBuilder,
14
+ resolveBazelBuildArgs,
15
+ selectBazelTarget,
16
+ } from '../utils/applicationUtils';
17
+ import { logReproduceThisCommandIfNeeded, makeCommandHandler } from '../utils/errorUtils';
18
+ import { removeFileOrDirAtPath } from '../utils/fileUtils';
19
+ import { wrapInColor } from '../utils/logUtils';
20
+ import { withTempDir } from '../utils/tempDir';
21
+ import { decompressTo } from '../utils/zipUtils';
22
+
23
+ interface CommandParameters extends SharedCommandParameters {
24
+ library: string | undefined;
25
+ target_output_path: string | undefined;
26
+ output_path: string;
27
+ }
28
+
29
+ async function decompressAndMoveXCFrameworkIntoDestination(
30
+ bazelOutputFilePath: string,
31
+ resolvedOutputPath: string,
32
+ ): Promise<void> {
33
+ await withTempDir(async tempDir => {
34
+ await decompressTo(bazelOutputFilePath, tempDir);
35
+
36
+ const decompressedOutputs = fs.readdirSync(tempDir);
37
+ if (decompressedOutputs.length !== 1) {
38
+ throw new Error(
39
+ `Expected 1 unzipped output, got ${decompressedOutputs.length} (${decompressedOutputs.join(', ')})`,
40
+ );
41
+ }
42
+
43
+ // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
44
+ const inputDir = path.join(tempDir, decompressedOutputs[0]!);
45
+
46
+ await fs.promises.rename(inputDir, resolvedOutputPath);
47
+ });
48
+ }
49
+
50
+ async function valdiExport(argv: ArgumentsResolver<CommandParameters>): Promise<void> {
51
+ const bazel = new BazelClient();
52
+ // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
53
+ const platform = argv.getArgument('platform') as PLATFORM;
54
+ const bazelArgs = resolveBazelBuildArgs(
55
+ platform,
56
+ argv.getArgument('build_config'),
57
+ ALL_ARCHITECTURES,
58
+ /* forDevice */ false,
59
+ argv.getArgument('enable_runtime_logs'),
60
+ argv.getArgument('enable_runtime_traces'),
61
+ argv.getArgument('bazel_args'),
62
+ );
63
+
64
+ const resolvedOutputPath = path.resolve(argv.getArgument('output_path'));
65
+ const expectedExtension = exportedLibraryExtensionForPlatform(platform);
66
+ if (!resolvedOutputPath.endsWith(expectedExtension)) {
67
+ throw new CliError(`Output path for platform '${platform}' must have ${expectedExtension} file extension`);
68
+ }
69
+
70
+ removeFileOrDirAtPath(resolvedOutputPath);
71
+ const directoryPath = path.dirname(resolvedOutputPath);
72
+ if (!fs.existsSync(directoryPath)) {
73
+ fs.mkdirSync(directoryPath, { recursive: true });
74
+ }
75
+
76
+ const library = await argv.getArgumentOrResolve('library', () => {
77
+ console.log('No library specified querying available targets...');
78
+ return selectBazelTarget(
79
+ bazel,
80
+ getExportedLibraryTargetTagForPlatform(platform),
81
+ 'valdi_exported_library',
82
+ 'Please select a library to export:',
83
+ );
84
+ });
85
+
86
+ console.log('Resolving output paths...');
87
+
88
+ const bazelOutputExtension = platform === PLATFORM.IOS ? '.zip' : expectedExtension;
89
+ const bazelOutputFilePath = await argv.getArgumentOrResolve('target_output_path', () => {
90
+ console.log('Resolving output paths...');
91
+ return getOutputFilePath(bazel, bazelOutputExtension, library, bazelArgs);
92
+ });
93
+
94
+ console.log(`Building: ${wrapInColor(library, ANSI_COLORS.GREEN_COLOR)}`);
95
+
96
+ await bazel.buildTarget(library, bazelArgs);
97
+
98
+ console.log(`Copying built target to ${resolvedOutputPath}...`);
99
+ if (platform === PLATFORM.IOS) {
100
+ await decompressAndMoveXCFrameworkIntoDestination(bazelOutputFilePath, resolvedOutputPath);
101
+ } else {
102
+ await fs.promises.copyFile(bazelOutputFilePath, resolvedOutputPath);
103
+ }
104
+
105
+ logReproduceThisCommandIfNeeded(argv);
106
+
107
+ console.log('All done!');
108
+ }
109
+
110
+ export const command = 'export <platform>';
111
+ export const describe = 'Build and export a Valdi library';
112
+ export const builder = makeArgsBuilder((yargs: Argv<CommandParameters>) => {
113
+ yargs
114
+ .option('library', {
115
+ describe: 'Name of the library to build',
116
+ type: 'string',
117
+ requiresArg: true,
118
+ })
119
+ .option('target_output_path', {
120
+ describe: 'The output path for the Bazel target',
121
+ type: 'string',
122
+ requiresArg: true,
123
+ })
124
+ .option('output_path', {
125
+ describe: 'The path where to store the built application package',
126
+ type: 'string',
127
+ requiresArg: true,
128
+ })
129
+ .demandOption('output_path');
130
+ });
131
+ export const handler = makeCommandHandler(valdiExport);
@@ -0,0 +1,108 @@
1
+ import type { Argv } from 'yargs';
2
+ import { ANSI_COLORS } from '../core/constants';
3
+ import { CliError } from '../core/errors';
4
+ import type { ArgumentsResolver } from '../utils/ArgumentsResolver';
5
+ import { BazelClient } from '../utils/BazelClient';
6
+ import type { CliChoice } from '../utils/cliUtils';
7
+ import { getUserChoice, spawnCliCommand } from '../utils/cliUtils';
8
+ import { logReproduceThisCommandIfNeeded, makeCommandHandler } from '../utils/errorUtils';
9
+ import { wrapInColor } from '../utils/logUtils';
10
+
11
+ interface CommandParameters {
12
+ module: string | undefined;
13
+ target: string | undefined;
14
+ }
15
+
16
+ async function hotreloadResolvedTarget(client: BazelClient, resolvedTarget: string) {
17
+ await client.buildTarget(resolvedTarget);
18
+ const workspaceRoot = await client.getWorkspaceRoot();
19
+ const buildOutputs = await client.queryBuildOutputs([resolvedTarget]);
20
+
21
+ if (buildOutputs.length === 0) {
22
+ throw new CliError(`No build outputs found for target: ${resolvedTarget}`);
23
+ }
24
+
25
+ const hotreloadCommand = buildOutputs[0] ?? '';
26
+
27
+ await spawnCliCommand(hotreloadCommand, workspaceRoot, 'inherit', true, false);
28
+ }
29
+
30
+ async function hotreloadTarget(client: BazelClient, target: string) {
31
+ const resolvedLabel = await client.resolveLabel(target);
32
+ let resolvedTarget: string;
33
+ if (resolvedLabel.name) {
34
+ resolvedTarget = resolvedLabel.toString();
35
+ } else {
36
+ const targets = await client.query(`kind('valdi_hotreload', ${resolvedLabel.toString()}/...)`);
37
+ if (targets.length === 0) {
38
+ throw new Error(`Could not resolve hot reload target for label ${resolvedLabel.toString()}`);
39
+ }
40
+ if (targets.length !== 1) {
41
+ throw new Error(`Resolved more than 1 hot reload target for ${resolvedLabel.toString()}: ${targets.join(',')}`);
42
+ }
43
+ resolvedTarget = targets[0] as string;
44
+ }
45
+
46
+ await hotreloadResolvedTarget(client, resolvedTarget);
47
+ }
48
+
49
+ async function getHotreloadTargetByModuleName(client: BazelClient, moduleName: string): Promise<string> {
50
+ const targets = await client.query(`filter(${moduleName}_hotreload, kind('valdi_hotreload rule', //...))`);
51
+ if (targets.length === 0) {
52
+ throw new CliError(`No hotreload target found for module: ${moduleName}`);
53
+ }
54
+
55
+ return targets[0]?.trim() ?? '';
56
+ }
57
+
58
+ async function valdiHotreload(argv: ArgumentsResolver<CommandParameters>) {
59
+ const client = new BazelClient();
60
+
61
+ // TODO(3136): Try discovering and building with default path to modules first
62
+ const target = await argv.getArgumentOrResolve('target', async () => {
63
+ const module = argv.getArgument('module');
64
+ if (module) {
65
+ console.log('Finding target for module:', wrapInColor(module, ANSI_COLORS.GREEN_COLOR));
66
+ const target = await getHotreloadTargetByModuleName(client, module);
67
+ console.log('Found target:', wrapInColor(target, ANSI_COLORS.GREEN_COLOR));
68
+ return target;
69
+ }
70
+ const targets = await client.query('attr("tags", "valdi_application", //...)');
71
+ if (targets.length === 0) {
72
+ throw new CliError(`Could not resolve Valdi application Bazel target`);
73
+ }
74
+
75
+ if (targets.length === 1) {
76
+ return targets[0] as string;
77
+ } else {
78
+ const choices: Array<CliChoice<string>> = targets.map((target, index) => ({
79
+ name: `${index + 1}. ${target}`,
80
+ value: target,
81
+ }));
82
+
83
+ return await getUserChoice(choices, 'Please choose a target to hot reload:');
84
+ }
85
+ });
86
+
87
+ logReproduceThisCommandIfNeeded(argv);
88
+
89
+ await hotreloadResolvedTarget(client, target);
90
+ }
91
+
92
+ export const command = 'hotreload [--module module_name] [--target target_name]';
93
+ export const describe = 'Starts the hotreloader for the application';
94
+ export const builder = (yargs: Argv<CommandParameters>) => {
95
+ yargs
96
+ .option('module', {
97
+ describe: 'Name of the module to hotreload',
98
+ type: 'string',
99
+ requiresArg: true,
100
+ })
101
+ .option('target', {
102
+ describe: 'Bazel target path to hotreload',
103
+ type: 'string',
104
+ requiresArg: true,
105
+ });
106
+ };
107
+
108
+ export const handler = makeCommandHandler(valdiHotreload);
@@ -0,0 +1,93 @@
1
+ import { type Argv } from 'yargs';
2
+ import { ANSI_COLORS, PLATFORM } from '../core/constants';
3
+ import type { ArgumentsResolver } from '../utils/ArgumentsResolver';
4
+ import { BazelClient } from '../utils/BazelClient';
5
+ import {
6
+ applicationExtensionForPlatform,
7
+ getOutputFilePath,
8
+ makeArgsBuilder,
9
+ } from '../utils/applicationUtils';
10
+ import type { CommandParameters} from '../utils/buildInfo';
11
+ import { getBuildInfo } from '../utils/buildInfo';
12
+ import { installAndroidApk } from '../utils/deviceUtils';
13
+ import { logReproduceThisCommandIfNeeded, makeCommandHandler } from '../utils/errorUtils';
14
+ import { wrapInColor } from '../utils/logUtils';
15
+
16
+
17
+ async function valdiInstall(argv: ArgumentsResolver<CommandParameters>) {
18
+ const bazel = new BazelClient();
19
+
20
+ const buildInfo = await getBuildInfo(argv, bazel, true);
21
+
22
+ // Output Selection
23
+ // ----------------
24
+
25
+ // Perform build and install
26
+ // -------------------------
27
+ console.log(`Building: ${wrapInColor(buildInfo.application, ANSI_COLORS.GREEN_COLOR)}`);
28
+
29
+ switch (buildInfo.platform) {
30
+ case PLATFORM.ANDROID: {
31
+ const outputFilePath = await argv.getArgumentOrResolve('target_output_path', () => {
32
+ console.log('Resolving output paths...');
33
+ return getOutputFilePath(bazel, applicationExtensionForPlatform(buildInfo.platform), buildInfo.application, buildInfo.bazelArgs);
34
+ });
35
+ await bazel.buildTarget(buildInfo.application, buildInfo.bazelArgs);
36
+
37
+ console.log('Installing Android application...');
38
+ await installAndroidApk(outputFilePath, buildInfo.selectedDevice);
39
+ logReproduceThisCommandIfNeeded(argv);
40
+ break;
41
+ }
42
+ case PLATFORM.IOS: {
43
+ console.log('Installing iOS application...');
44
+ await bazel.runTarget(buildInfo.application, buildInfo.bazelArgs);
45
+ logReproduceThisCommandIfNeeded(argv);
46
+ break;
47
+ }
48
+ case PLATFORM.MACOS: {
49
+ logReproduceThisCommandIfNeeded(argv);
50
+ console.log('Installing MacOS application...');
51
+ await bazel.runTarget(buildInfo.application, buildInfo.bazelArgs);
52
+ break;
53
+ }
54
+ case PLATFORM.CLI: {
55
+ logReproduceThisCommandIfNeeded(argv);
56
+ console.log('Running CLI application...');
57
+ await bazel.runTarget(buildInfo.application, buildInfo.bazelArgs);
58
+ break;
59
+ }
60
+ }
61
+ }
62
+
63
+ export const command = 'install <platform>';
64
+ export const describe = 'Build and install the application to the connected device';
65
+ export const builder = makeArgsBuilder((yargs: Argv<CommandParameters>) => {
66
+ yargs
67
+ .option('application', {
68
+ describe: 'Name of the application to install',
69
+ type: 'string',
70
+ requiresArg: true,
71
+ })
72
+ .option('device_id', {
73
+ describe: 'Device ID that will receive the application',
74
+ type: 'string',
75
+ requiresArg: true,
76
+ })
77
+ .option('target_output_path', {
78
+ describe: 'The output path for the Bazel target',
79
+ type: 'string',
80
+ requiresArg: true,
81
+ })
82
+ .option('simulator', {
83
+ describe: 'Whether to build for simulator or for device',
84
+ type: 'boolean',
85
+ });
86
+ });
87
+ export const handler = makeCommandHandler(valdiInstall);
88
+
89
+ // TODOs:
90
+ // - Cached bazel query results
91
+
92
+ // Extract 'custom_package' from android_binary
93
+ // Extract 'bundle_id' from ios_application target
@@ -0,0 +1,15 @@
1
+ import type { Argv } from 'yargs';
2
+
3
+ export const command = 'lint <command>';
4
+ export const describe = 'Checks and formats the code';
5
+ export const builder = (yargs: Argv) => {
6
+ return yargs
7
+ .commandDir('lint_commands', {
8
+ extensions: ['js', 'ts'],
9
+ })
10
+ .demandCommand(1, 'Use "check" or "format" to execute prettier')
11
+ .recommendCommands()
12
+ .wrap(yargs.terminalWidth())
13
+ .help();
14
+ };
15
+ export const handler = () => {};
@@ -0,0 +1,53 @@
1
+ import type { Argv } from 'yargs';
2
+ import { ANSI_COLORS } from '../../core/constants';
3
+ import type { ArgumentsResolver } from '../../utils/ArgumentsResolver';
4
+ import { makeCommandHandler } from '../../utils/errorUtils';
5
+ import type { FileLintStatus } from '../../utils/lintUtils';
6
+ import {
7
+ checkAndFormatFiles,
8
+ getPrettierConfig,
9
+ maybeSetupEslint,
10
+ maybeSetupPrettier,
11
+ printStatus,
12
+ } from '../../utils/lintUtils';
13
+ import { wrapInColor } from '../../utils/logUtils';
14
+
15
+ interface CommandParameters {
16
+ files: string[] | undefined;
17
+ showSkipped: boolean;
18
+ }
19
+
20
+ async function lintCheck(argv: ArgumentsResolver<CommandParameters>) {
21
+ const configPath = await maybeSetupPrettier();
22
+ const prettierConfig = await getPrettierConfig(configPath);
23
+ await maybeSetupEslint();
24
+
25
+ console.log(`Using config at: ${wrapInColor(configPath, ANSI_COLORS.GREEN_COLOR)}\n`);
26
+
27
+ const filePaths = argv.getArgument('files');
28
+
29
+ if (filePaths === undefined || prettierConfig === null) {
30
+ return;
31
+ }
32
+
33
+ const results: FileLintStatus[] = await checkAndFormatFiles(filePaths, prettierConfig);
34
+
35
+ // Output list of files and their status
36
+ printStatus(results, argv.getArgument('showSkipped'));
37
+
38
+ // TODO (yhuang6): Implement the following
39
+ // Default checks changed files based on git
40
+ // Default checks the current directory otherwise
41
+ }
42
+
43
+ export const command = 'check [files..]';
44
+ export const describe = 'Checks the file formatting and lint rules';
45
+ export const builder = (yargs: Argv<CommandParameters>) => {
46
+ yargs.option('show-skipped', {
47
+ describe: 'Shows files skipped during linting (e.g. no format parsers)',
48
+ type: 'boolean',
49
+ alias: 's',
50
+ default: false,
51
+ });
52
+ };
53
+ export const handler = makeCommandHandler(lintCheck);
@@ -0,0 +1,49 @@
1
+ import type { Argv } from 'yargs';
2
+ import { ANSI_COLORS } from '../../core/constants';
3
+ import type { ArgumentsResolver } from '../../utils/ArgumentsResolver';
4
+ import { makeCommandHandler } from '../../utils/errorUtils';
5
+ import type { FileLintStatus } from '../../utils/lintUtils';
6
+ import {
7
+ checkAndFormatFiles,
8
+ getPrettierConfig,
9
+ maybeSetupEslint,
10
+ maybeSetupPrettier,
11
+ printStatus,
12
+ } from '../../utils/lintUtils';
13
+ import { wrapInColor } from '../../utils/logUtils';
14
+
15
+ interface CommandParameters {
16
+ files: [string] | undefined;
17
+ showSkipped: boolean;
18
+ }
19
+
20
+ async function lintFormat(argv: ArgumentsResolver<CommandParameters>) {
21
+ const configPath = await maybeSetupPrettier();
22
+ const prettierConfig = await getPrettierConfig(configPath);
23
+ await maybeSetupEslint();
24
+
25
+ console.log(`Using config at: ${wrapInColor(configPath, ANSI_COLORS.GREEN_COLOR)}\n`);
26
+
27
+ const filePaths = argv.getArgument('files');
28
+
29
+ if (filePaths === undefined || prettierConfig === null) {
30
+ return;
31
+ }
32
+
33
+ const results: FileLintStatus[] = await checkAndFormatFiles(filePaths, prettierConfig, true);
34
+
35
+ // Output list of files and their status
36
+ printStatus(results, argv.getArgument('showSkipped'));
37
+ }
38
+
39
+ export const command = 'format [files..]';
40
+ export const describe = 'Apply prettier formatting to files';
41
+ export const builder = (yargs: Argv<CommandParameters>) => {
42
+ yargs.option('show-skipped', {
43
+ describe: 'Shows files skipped during linting (e.g. no format parsers)',
44
+ type: 'boolean',
45
+ alias: 's',
46
+ default: false,
47
+ });
48
+ };
49
+ export const handler = makeCommandHandler(lintFormat);
@@ -0,0 +1,108 @@
1
+ import fs from 'fs';
2
+ import path from 'path';
3
+ import { CliError } from '../core/errors';
4
+ import { getUserChoice } from '../utils/cliUtils';
5
+ import { makeCommandHandler } from '../utils/errorUtils';
6
+ import * as fileUtils from '../utils/fileUtils';
7
+
8
+ function readAndWatchFile(filePath: string) {
9
+ filePath = fileUtils.resolveFilePath(filePath);
10
+
11
+ let fileSize = 0;
12
+ let isWatching = false;
13
+ const abortController = new AbortController();
14
+
15
+ const readInitialContent = () => {
16
+ const fileStream = fs.createReadStream(filePath, { encoding: 'utf8', start: 0 });
17
+
18
+ fileStream.on('data', chunk => {
19
+ process.stdout.write(chunk);
20
+ });
21
+
22
+ fileStream.on('end', () => {
23
+ fileSize = fs.statSync(filePath).size;
24
+
25
+ if (!isWatching) {
26
+ startWatching();
27
+ }
28
+ });
29
+ };
30
+
31
+ const startWatching = () => {
32
+ isWatching = true;
33
+ fs.watch(filePath, { signal: abortController.signal }, eventType => {
34
+ if (eventType === 'change') {
35
+ const newFileSize = fs.statSync(filePath).size;
36
+ if (newFileSize > fileSize) {
37
+ const readStream = fs.createReadStream(filePath, { encoding: 'utf8', start: fileSize });
38
+ readStream.on('data', chunk => {
39
+ process.stdout.write(chunk);
40
+ });
41
+ fileSize = newFileSize;
42
+ }
43
+ } else if (eventType === 'rename') {
44
+ isWatching = false;
45
+ if (fs.existsSync(filePath)) {
46
+ // When files is written, sometimes the first reported event
47
+ // occurs when the write is incomplete, so verifying the file exists
48
+ // before reading and restarting the watch
49
+ readInitialContent();
50
+ }
51
+ }
52
+ });
53
+ };
54
+
55
+ readInitialContent();
56
+
57
+ // Liten for (Ctrl+D) to exit as otherwise it would not do anything
58
+ process.stdin.on('end', () => {
59
+ abortController.abort();
60
+ });
61
+
62
+ // Keep the process running
63
+ process.stdin.resume();
64
+ }
65
+
66
+ async function showValdiLogs() {
67
+ const userConfig = fileUtils.getUserConfig();
68
+
69
+ if (userConfig.logs_output_dir === undefined) {
70
+ throw new CliError("Missing 'logs_output_dir' config value in config.yaml");
71
+ }
72
+
73
+ const allFilePaths = fileUtils.getFilesSortedByUpdatedTime(userConfig.logs_output_dir).filter(path => {
74
+ return path.endsWith('.log');
75
+ });
76
+
77
+ if (allFilePaths.length <= 0) {
78
+ throw new CliError(
79
+ 'No logs available. Please start up hot reloader and the app first to make sure there are logs available',
80
+ );
81
+ }
82
+
83
+ let logPath = '';
84
+
85
+ if (allFilePaths.length === 1) {
86
+ logPath = allFilePaths[0] as string;
87
+ } else {
88
+ const choices = allFilePaths.map((filePath, index) => ({
89
+ name: `${index + 1}. ${path.basename(filePath)}`,
90
+ value: filePath,
91
+ }));
92
+
93
+ logPath = await getUserChoice(
94
+ choices,
95
+ 'Please select the log file to use (this list is ordered by modification time, the most updated log will be displayed first):',
96
+ );
97
+
98
+ console.log(logPath);
99
+ }
100
+
101
+ // Read and show log file content
102
+ readAndWatchFile(logPath);
103
+ }
104
+
105
+ export const command = 'log';
106
+ export const describe = 'Streams Valdi logs from the connected device to console';
107
+ export const builder = () => {};
108
+ export const handler = makeCommandHandler(showValdiLogs);