ts-repo-utils 5.3.0 → 6.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 (40) hide show
  1. package/README.md +176 -0
  2. package/dist/cmd/assert-repo-is-clean.d.mts +3 -0
  3. package/dist/cmd/assert-repo-is-clean.d.mts.map +1 -0
  4. package/dist/cmd/assert-repo-is-clean.mjs +32 -0
  5. package/dist/cmd/assert-repo-is-clean.mjs.map +1 -0
  6. package/dist/cmd/check-should-run-type-checks.d.mts +3 -0
  7. package/dist/cmd/check-should-run-type-checks.d.mts.map +1 -0
  8. package/dist/cmd/check-should-run-type-checks.mjs +42 -0
  9. package/dist/cmd/check-should-run-type-checks.mjs.map +1 -0
  10. package/dist/cmd/format-diff-from.d.mts +3 -0
  11. package/dist/cmd/format-diff-from.d.mts.map +1 -0
  12. package/dist/cmd/format-diff-from.mjs +45 -0
  13. package/dist/cmd/format-diff-from.mjs.map +1 -0
  14. package/dist/cmd/format-untracked.d.mts +3 -0
  15. package/dist/cmd/format-untracked.d.mts.map +1 -0
  16. package/dist/cmd/format-untracked.mjs +34 -0
  17. package/dist/cmd/format-untracked.mjs.map +1 -0
  18. package/dist/cmd/gen-index-ts.d.mts +3 -0
  19. package/dist/cmd/gen-index-ts.d.mts.map +1 -0
  20. package/dist/cmd/gen-index-ts.mjs +119 -0
  21. package/dist/cmd/gen-index-ts.mjs.map +1 -0
  22. package/dist/functions/format.mjs +1 -1
  23. package/dist/functions/gen-index.d.mts +5 -11
  24. package/dist/functions/gen-index.d.mts.map +1 -1
  25. package/dist/functions/gen-index.mjs +21 -15
  26. package/dist/functions/gen-index.mjs.map +1 -1
  27. package/dist/functions/should-run.d.mts +53 -13
  28. package/dist/functions/should-run.d.mts.map +1 -1
  29. package/dist/functions/should-run.mjs +82 -23
  30. package/dist/functions/should-run.mjs.map +1 -1
  31. package/dist/index.d.mts.map +1 -1
  32. package/package.json +23 -12
  33. package/src/cmd/assert-repo-is-clean.mts +28 -0
  34. package/src/cmd/check-should-run-type-checks.mts +43 -0
  35. package/src/cmd/format-diff-from.mts +49 -0
  36. package/src/cmd/format-untracked.mts +31 -0
  37. package/src/cmd/gen-index-ts.mts +147 -0
  38. package/src/functions/gen-index.mts +36 -30
  39. package/src/functions/should-run.mts +92 -27
  40. package/src/index.mts +0 -2
@@ -0,0 +1,147 @@
1
+ #!/usr/bin/env -S npx tsx
2
+
3
+ import * as cmd from 'cmd-ts';
4
+
5
+ // eslint-disable-next-line import/no-internal-modules
6
+ import { type InputOf, type OutputOf } from 'cmd-ts/dist/esm/from.js';
7
+ import { expectType } from 'ts-data-forge';
8
+ import { genIndex } from '../functions/index.mjs';
9
+
10
+ type Ext = `.${string}`;
11
+
12
+ const extensionType = cmd.extendType(cmd.string, {
13
+ from: (s) => {
14
+ if (!s.startsWith('.')) {
15
+ throw new Error(`ext should start with '.'`);
16
+ }
17
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-type-assertion
18
+ return Promise.resolve(s as Ext);
19
+ },
20
+ });
21
+
22
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
23
+ const nonEmptyArray = <T extends cmd.Type<any, any>>(
24
+ t: T,
25
+ commandName: string,
26
+ ): cmd.Type<InputOf<T>[], NonEmptyArray<OutputOf<T>>> =>
27
+ cmd.extendType(cmd.array(t), {
28
+ from: (arr) => {
29
+ if (arr.length === 0) {
30
+ throw new Error(
31
+ `No value provided for --${commandName}. At least one value is required.`,
32
+ );
33
+ }
34
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-type-assertion
35
+ return Promise.resolve(arr as unknown as NonEmptyArray<OutputOf<T>>);
36
+ },
37
+ });
38
+
39
+ const cmdDef = cmd.command({
40
+ name: 'gen-index-ts-cli',
41
+ version: '6.0.1',
42
+ args: {
43
+ // required args
44
+ targetDirectory: cmd.positional({
45
+ type: cmd.string,
46
+ displayName: 'target-directory',
47
+ description:
48
+ 'Directory where the index file will be generated (Comma-separated list can be used)',
49
+ }),
50
+
51
+ targetExtensions: cmd.multioption({
52
+ long: 'target-ext',
53
+ type: nonEmptyArray(extensionType, 'target-ext'),
54
+ description: 'File extensions to include in the index file',
55
+ }),
56
+ indexFileExtension: cmd.option({
57
+ long: 'index-ext',
58
+ type: extensionType,
59
+ description: 'Extension of the index file to be generated',
60
+ }),
61
+ exportStatementExtension: cmd.option({
62
+ long: 'export-ext',
63
+ type: cmd.union([
64
+ extensionType,
65
+ cmd.extendType(cmd.string, {
66
+ from: (s) => {
67
+ if (s !== 'none') {
68
+ throw new Error(
69
+ `export-ext should be 'none' or a valid extension`,
70
+ );
71
+ }
72
+ return Promise.resolve('none' as const);
73
+ },
74
+ }),
75
+ ]),
76
+ description: 'Extension of the export statements in the index file',
77
+ }),
78
+
79
+ // optional args
80
+ exclude: cmd.multioption({
81
+ long: 'exclude',
82
+ type: cmd.optional(cmd.array(cmd.string)),
83
+ description:
84
+ 'Glob patterns of files to exclude from the index file (e.g., "*.d.mts", "*.test.mts")',
85
+ }),
86
+ formatCommand: cmd.option({
87
+ long: 'fmt',
88
+ type: cmd.optional(cmd.string),
89
+ description:
90
+ 'Command to format after generating the index file (e.g., "npm run fmt")',
91
+ }),
92
+ silent: cmd.flag({
93
+ long: 'silent',
94
+ type: cmd.optional(cmd.boolean),
95
+ description: 'If true, suppresses output messages (default: false)',
96
+ }),
97
+ },
98
+ handler: (args) => {
99
+ console.log(args);
100
+
101
+ expectType<typeof args.targetDirectory, string>('=');
102
+ expectType<typeof args.targetExtensions, NonEmptyArray<Ext>>('=');
103
+ expectType<typeof args.exportStatementExtension, Ext | 'none'>('=');
104
+ expectType<typeof args.indexFileExtension, Ext>('=');
105
+
106
+ expectType<typeof args.exclude, string[] | undefined>('=');
107
+ expectType<typeof args.formatCommand, string | undefined>('=');
108
+ expectType<typeof args.silent, boolean | undefined>('=');
109
+
110
+ main(args).catch((error) => {
111
+ console.error('An error occurred:', error);
112
+ process.exit(1);
113
+ });
114
+ },
115
+ });
116
+
117
+ const main = async ({
118
+ targetDirectory,
119
+ targetExtensions,
120
+ exportStatementExtension,
121
+ indexFileExtension,
122
+ exclude,
123
+ formatCommand,
124
+ silent,
125
+ }: Readonly<{
126
+ targetDirectory: string;
127
+ targetExtensions: readonly Ext[];
128
+ exportStatementExtension: Ext | 'none';
129
+ indexFileExtension: Ext;
130
+ exclude?: readonly string[] | undefined;
131
+ formatCommand?: string | undefined;
132
+ silent?: boolean | undefined;
133
+ }>): Promise<void> => {
134
+ await genIndex({
135
+ targetDirectory: targetDirectory.includes(',')
136
+ ? targetDirectory.split(',').map((dir) => dir.trim())
137
+ : targetDirectory,
138
+ exportStatementExtension,
139
+ targetExtensions,
140
+ exclude,
141
+ indexFileExtension,
142
+ formatCommand,
143
+ silent,
144
+ });
145
+ };
146
+
147
+ await cmd.run(cmdDef, process.argv.slice(2));
@@ -10,7 +10,8 @@ export type GenIndexConfig = DeepReadonly<{
10
10
 
11
11
  /**
12
12
  * Glob patterns of files or predicate function to exclude from exports
13
- * (default: excludes `'**\/*.{test,spec}.?(c|m)[jt]s?(x)'`)
13
+ * (default: excludes `'**\/*.{test,spec}.?(c|m)[jt]s?(x)'` and
14
+ * `'**\/*.d.?(c|m)ts'`)
14
15
  */
15
16
  exclude?:
16
17
  | readonly string[]
@@ -22,22 +23,14 @@ export type GenIndexConfig = DeepReadonly<{
22
23
  }>,
23
24
  ) => boolean);
24
25
 
25
- /**
26
- * Glob patterns of files or predicate function to exclude from exports
27
- * (default: excludes `'**\/*.{test,spec}.?(c|m)[jt]s?(x)'`)
28
- *
29
- * @deprecated Use `exclude` instead.
30
- */
31
- excludePatterns?: readonly string[];
32
-
33
26
  /** File extensions of source files to export (default: ['.ts', '.tsx']) */
34
- sourceExtensions?: readonly `.${string}`[];
27
+ targetExtensions?: readonly `.${string}`[];
35
28
 
36
29
  /** File extension of index files to generate (default: '.ts') */
37
- indexExtension?: `.${string}`;
30
+ indexFileExtension?: `.${string}`;
38
31
 
39
32
  /** File extension to use in export statements (default: '.js') */
40
- exportExtension?: `.${string}` | 'none';
33
+ exportStatementExtension?: `.${string}` | 'none';
41
34
 
42
35
  /** Command to run for formatting generated files (optional) */
43
36
  formatCommand?: string;
@@ -46,6 +39,16 @@ export type GenIndexConfig = DeepReadonly<{
46
39
  silent?: boolean;
47
40
  }>;
48
41
 
42
+ const defaultConfig = {
43
+ exclude: ['**/*.{test,spec}.?(c|m)[jt]s?(x)', '**/*.d.?(c|m)ts'],
44
+ targetExtensions: ['.ts', '.tsx'],
45
+ indexFileExtension: '.ts',
46
+ exportStatementExtension: '.js', // For ESM imports, .mts resolves to .mjs
47
+ silent: false,
48
+ } as const satisfies Required<
49
+ StrictOmit<GenIndexConfig, 'targetDirectory' | 'formatCommand'>
50
+ >;
51
+
49
52
  type GenIndexConfigInternal = DeepReadonly<{
50
53
  formatCommand: string | undefined;
51
54
  targetDirectory: ISet<string>;
@@ -56,9 +59,9 @@ type GenIndexConfigInternal = DeepReadonly<{
56
59
  fileName: string;
57
60
  }>,
58
61
  ) => boolean;
59
- sourceExtensions: ISet<`.${string}`>;
60
- indexExtension: `.${string}`;
61
- exportExtension: `.${string}` | 'none';
62
+ targetExtensions: ISet<`.${string}`>;
63
+ indexFileExtension: `.${string}`;
64
+ exportStatementExtension: `.${string}` | 'none';
62
65
  silent: boolean;
63
66
  }>;
64
67
 
@@ -117,8 +120,11 @@ export const genIndex = async (config: GenIndexConfig): Promise<void> => {
117
120
  };
118
121
 
119
122
  const fillConfig = (config: GenIndexConfig): GenIndexConfigInternal => {
120
- const sourceExtensions = config.sourceExtensions ?? ['.ts'];
121
- const exportExtension = config.exportExtension ?? '.js'; // For ESM imports, .mts resolves to .mjs
123
+ const targetExtensions =
124
+ config.targetExtensions ?? defaultConfig.targetExtensions;
125
+
126
+ const exportExtension =
127
+ config.exportStatementExtension ?? defaultConfig.exportStatementExtension;
122
128
 
123
129
  return {
124
130
  formatCommand: config.formatCommand,
@@ -127,8 +133,7 @@ const fillConfig = (config: GenIndexConfig): GenIndexConfigInternal => {
127
133
  ? [config.targetDirectory]
128
134
  : config.targetDirectory,
129
135
  ),
130
- // eslint-disable-next-line @typescript-eslint/no-deprecated
131
- exclude: pipe(config.exclude ?? config.excludePatterns).map((exclude) =>
136
+ exclude: pipe(config.exclude).map((exclude) =>
132
137
  typeof exclude === 'function'
133
138
  ? exclude
134
139
  : pipe(
@@ -137,7 +142,7 @@ const fillConfig = (config: GenIndexConfig): GenIndexConfigInternal => {
137
142
  if (exclude !== undefined && Array.isArray(exclude)) {
138
143
  yield* exclude;
139
144
  }
140
- yield '**/*.{test,spec}.?(c|m)[jt]s?(x)';
145
+ yield* defaultConfig.exclude;
141
146
  }),
142
147
  ),
143
148
  ).map(
@@ -162,10 +167,11 @@ const fillConfig = (config: GenIndexConfig): GenIndexConfigInternal => {
162
167
  },
163
168
  ).value,
164
169
  ).value,
165
- sourceExtensions: ISet.create(sourceExtensions),
166
- indexExtension: config.indexExtension ?? '.ts',
167
- exportExtension,
168
- silent: config.silent ?? false,
170
+ targetExtensions: ISet.create(targetExtensions),
171
+ indexFileExtension:
172
+ config.indexFileExtension ?? defaultConfig.indexFileExtension,
173
+ exportStatementExtension: exportExtension,
174
+ silent: config.silent ?? defaultConfig.silent,
169
175
  };
170
176
  };
171
177
 
@@ -229,7 +235,7 @@ const generateIndexFileForDir = async (
229
235
  config,
230
236
  );
231
237
 
232
- const indexPath = path.join(dirPath, `index${config.indexExtension}`);
238
+ const indexPath = path.join(dirPath, `index${config.indexFileExtension}`);
233
239
 
234
240
  await fs.writeFile(indexPath, indexContent);
235
241
  echo(`Generated: ${path.relative(process.cwd(), indexPath)}`);
@@ -269,7 +275,7 @@ const shouldExportFile = ({
269
275
  const ext = path.extname(fileName);
270
276
 
271
277
  // Must have the correct source extension
272
- if (!config.sourceExtensions.has(ext)) {
278
+ if (!config.targetExtensions.has(ext)) {
273
279
  return false;
274
280
  }
275
281
 
@@ -328,16 +334,16 @@ const generateIndexContent = (
328
334
  ): string => {
329
335
  const exportStatements = [
330
336
  ...subDirectories.map((subDir) =>
331
- config.exportExtension === 'none'
337
+ config.exportStatementExtension === 'none'
332
338
  ? `export * from "./${subDir}";`
333
- : `export * from "./${subDir}/index${config.exportExtension}";`,
339
+ : `export * from "./${subDir}/index${config.exportStatementExtension}";`,
334
340
  ),
335
341
  ...filesToExport.map((file) => {
336
342
  const fileNameWithoutExt = path.basename(file, path.extname(file));
337
343
 
338
- return config.exportExtension === 'none'
344
+ return config.exportStatementExtension === 'none'
339
345
  ? `export * from "./${fileNameWithoutExt}";`
340
- : `export * from "./${fileNameWithoutExt}${config.exportExtension}";`;
346
+ : `export * from "./${fileNameWithoutExt}${config.exportStatementExtension}";`;
341
347
  }),
342
348
  ];
343
349
 
@@ -1,47 +1,112 @@
1
- import { pipe, Result } from 'ts-data-forge';
1
+ import { Result } from 'ts-data-forge';
2
2
  import '../node-global.mjs';
3
3
  import { getDiffFrom } from './diff.mjs';
4
4
 
5
5
  /**
6
- * Checks if TypeScript type checks should run based on the diff from
7
- * origin/main. Skips type checks if all changed files are documentation files,
8
- * spell check config, or other non-TypeScript files that don't affect type
9
- * checking.
6
+ * Checks if TypeScript type checks should run based on the diff from a base
7
+ * branch. Skips type checks if all changed files match the ignored patterns.
10
8
  *
11
- * Ignored file patterns:
9
+ * This function is typically used in CI/CD pipelines to determine whether
10
+ * expensive type checking operations should be performed. If all changed files
11
+ * are documentation, configuration, or other non-TypeScript files, type checks
12
+ * can be safely skipped to improve build performance.
12
13
  *
13
- * - '.cspell.json'
14
- * - '**.md'
15
- * - '**.txt'
16
- * - 'docs/**'
14
+ * @example
15
+ * ```typescript
16
+ * // Use default settings (compare against origin/main, ignore docs/md/txt files)
17
+ * await checkShouldRunTypeChecks();
17
18
  *
18
- * @returns A promise that resolves when the check is complete. Sets
19
- * GITHUB_OUTPUT environment variable with should_run=true/false if running in
20
- * GitHub Actions.
19
+ * // Custom ignore patterns
20
+ * await checkShouldRunTypeChecks({
21
+ * pathsIgnore: ['.eslintrc.json', 'docs/', '**.md', 'scripts/'],
22
+ * });
23
+ *
24
+ * // Custom base branch
25
+ * await checkShouldRunTypeChecks({
26
+ * baseBranch: 'origin/develop',
27
+ * });
28
+ * ```;
29
+ *
30
+ * @example
31
+ * GitHub Actions usage
32
+ * ```yaml
33
+ * - name: Check if type checks should run
34
+ * id: check_diff
35
+ * run: npx check-should-run-type-checks
36
+ *
37
+ * - name: Run type checks
38
+ * if: steps.check_diff.outputs.should_run == 'true'
39
+ * run: npm run type-check
40
+ * ```
41
+ *
42
+ * @param options - Configuration options
43
+ * @param options.pathsIgnore - Array of patterns to ignore when determining if
44
+ * type checks should run. Supports three pattern types:
45
+ *
46
+ * - **Exact file matches**: e.g., `.cspell.json` matches only that file
47
+ * - **Directory prefixes**: e.g., `docs/` matches any file in docs directory
48
+ * - **File extensions**: e.g., `**.md` matches any markdown file Defaults to:
49
+ * `['LICENSE', '.editorconfig', '.gitignore', '.cspell.json',
50
+ * '.markdownlint-cli2.mjs', '.npmignore', '.prettierignore',
51
+ * '.prettierrc', 'docs/', '**.md', '**.txt']`
52
+ *
53
+ * @param options.baseBranch - Base branch to compare against for determining
54
+ * changed files. Defaults to `'origin/main'`
55
+ * @returns A promise that resolves when the check is complete. The function
56
+ * will set the GITHUB_OUTPUT environment variable with `should_run=true` or
57
+ * `should_run=false` if running in GitHub Actions environment.
21
58
  */
22
- export const checkShouldRunTypeChecks = async (): Promise<void> => {
23
- // paths-ignore:
24
- // - '.cspell.json'
25
- // - '**.md'
26
- // - '**.txt'
27
- // - 'docs/**'
59
+ export const checkShouldRunTypeChecks = async (
60
+ options?: Readonly<{
61
+ pathsIgnore?: readonly string[];
62
+ baseBranch?: string;
63
+ }>,
64
+ ): Promise<void> => {
65
+ const pathsIgnore = options?.pathsIgnore ?? [
66
+ 'LICENSE',
67
+ '.editorconfig',
68
+ '.gitignore',
69
+ '.cspell.json',
70
+ '.markdownlint-cli2.mjs',
71
+ '.npmignore',
72
+ '.prettierignore',
73
+ '.prettierrc',
74
+ 'docs/',
75
+ '**.md',
76
+ '**.txt',
77
+ ];
78
+
79
+ const baseBranch = options?.baseBranch ?? 'origin/main';
28
80
 
29
81
  const GITHUB_OUTPUT = process.env['GITHUB_OUTPUT'];
30
82
 
31
- const files = await getDiffFrom('origin/main');
83
+ const files = await getDiffFrom(baseBranch);
32
84
 
33
85
  if (Result.isErr(files)) {
34
86
  console.error('Error getting diff:', files.value);
35
87
  process.exit(1);
36
88
  }
37
89
 
38
- const shouldRunTsChecks: boolean = !files.value.every(
39
- (file) =>
40
- file === '.cspell.json' ||
41
- file.startsWith('docs/') ||
42
- pipe(path.basename(file)).map(
43
- (filename) => filename.endsWith('.md') || filename.endsWith('.txt'),
44
- ).value,
90
+ const shouldRunTsChecks: boolean = !files.value.every((file) =>
91
+ pathsIgnore.some((pattern) => {
92
+ // Exact file match
93
+ if (pattern === file) {
94
+ return true;
95
+ }
96
+
97
+ // Directory prefix match (pattern ends with '/')
98
+ if (pattern.endsWith('/') && file.startsWith(pattern)) {
99
+ return true;
100
+ }
101
+
102
+ // File extension pattern match (pattern starts with '**.')
103
+ if (pattern.startsWith('**.')) {
104
+ const extension = pattern.slice(2); // Remove '**'
105
+ return path.basename(file).endsWith(extension);
106
+ }
107
+
108
+ return false;
109
+ }),
45
110
  );
46
111
 
47
112
  if (GITHUB_OUTPUT !== undefined) {
package/src/index.mts CHANGED
@@ -1,3 +1 @@
1
- /// <reference types="ts-type-forge" />
2
-
3
1
  export * from './functions/index.mjs';