ts-repo-utils 1.0.0

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.
package/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,3 @@
1
+ # ts-repo-utils
2
+
3
+ Utilities for TypeScript Repositories.
package/package.json ADDED
@@ -0,0 +1,97 @@
1
+ {
2
+ "name": "ts-repo-utils",
3
+ "version": "1.0.0",
4
+ "private": false,
5
+ "keywords": [
6
+ "typescript"
7
+ ],
8
+ "repository": {
9
+ "type": "git",
10
+ "url": "git+https://github.com/noshiro-pf/ts-repo-utils.git"
11
+ },
12
+ "license": "Apache-2.0",
13
+ "author": "noshiro-pf <noshiro.pf@gmail.com>",
14
+ "sideEffects": false,
15
+ "type": "module",
16
+ "exports": {
17
+ ".": {
18
+ "import": {
19
+ "types": "./dist/index.d.mts",
20
+ "default": "./dist/index.mjs"
21
+ }
22
+ }
23
+ },
24
+ "module": "./dist/index.js",
25
+ "types": "./dist/index.d.ts",
26
+ "files": [
27
+ "src",
28
+ "dist",
29
+ "README.md",
30
+ "LICENSE"
31
+ ],
32
+ "scripts": {
33
+ "build": "npm run z:node-eval -- \"import { build } from './scripts/functions/build.mjs'; build();\"",
34
+ "check-all": "npm run z:node-esm -- ./scripts/cmd/check-all.mjs",
35
+ "check:ext": "npm run z:node-esm -- ./scripts/cmd/check-ext.mjs",
36
+ "cspell": "cspell \"**\" --gitignore --gitignore-root ./ --no-progress",
37
+ "doc": "npm run z:node-eval -- \"import { genDocs } from './scripts/functions/gen-docs.mjs'; genDocs();\"",
38
+ "fmt": "prettier --write .",
39
+ "gi": "npm run z:node-esm -- ./scripts/cmd/gi.mjs",
40
+ "lint": "eslint .",
41
+ "lint:fix": "eslint . --fix",
42
+ "md": "markdownlint-cli2",
43
+ "test": "npm run z:vitest -- run",
44
+ "test:cov": "npm run z:vitest -- run --coverage",
45
+ "test:cov:ui": "vite preview --outDir ./coverage",
46
+ "test:ui": "npm run z:vitest -- --ui",
47
+ "testw": "npm run z:vitest -- watch",
48
+ "tsc": "tsc --noEmit",
49
+ "tscw": "tsc --noEmit --watch",
50
+ "type-check": "tsc --noEmit",
51
+ "update-packages": "npx npm-check-updates -u --install always --reject @types/node",
52
+ "z:node-esm": "node --import tsx/esm",
53
+ "z:node-eval": "npm run z:node-esm -- --input-type=module --eval",
54
+ "z:vitest": "vitest --config ./configs/vitest.config.ts"
55
+ },
56
+ "dependencies": {
57
+ "@types/micromatch": "^4.0.9",
58
+ "fast-glob": "^3.3.3",
59
+ "micromatch": "^4.0.8",
60
+ "prettier": "^3.5.3"
61
+ },
62
+ "devDependencies": {
63
+ "@eslint/js": "^9.29.0",
64
+ "@rollup/plugin-replace": "^6.0.2",
65
+ "@rollup/plugin-strip": "^3.0.4",
66
+ "@rollup/plugin-typescript": "^12.1.2",
67
+ "@semantic-release/changelog": "^6.0.3",
68
+ "@semantic-release/commit-analyzer": "^13.0.1",
69
+ "@semantic-release/exec": "^7.1.0",
70
+ "@semantic-release/git": "^10.0.1",
71
+ "@semantic-release/github": "^11.0.3",
72
+ "@semantic-release/npm": "^12.0.1",
73
+ "@semantic-release/release-notes-generator": "^14.0.3",
74
+ "@types/node": "^20.19.0",
75
+ "@vitest/coverage-v8": "^3.2.3",
76
+ "@vitest/ui": "^3.2.3",
77
+ "conventional-changelog-conventionalcommits": "^9.0.0",
78
+ "cspell": "^9.1.1",
79
+ "dedent": "^1.6.0",
80
+ "eslint": "^9.29.0",
81
+ "markdownlint-cli2": "^0.18.1",
82
+ "prettier-plugin-organize-imports": "^4.1.0",
83
+ "prettier-plugin-packagejson": "^2.5.15",
84
+ "rollup": "^4.43.0",
85
+ "semantic-release": "^24.2.5",
86
+ "ts-type-forge": "^2.0.3",
87
+ "tsx": "^4.20.3",
88
+ "typedoc": "^0.28.5",
89
+ "typedoc-plugin-markdown": "^4.6.4",
90
+ "typescript": "^5.8.3",
91
+ "typescript-eslint": "^8.34.0",
92
+ "vitest": "^3.2.3"
93
+ },
94
+ "engines": {
95
+ "node": ">=20.11.0"
96
+ }
97
+ }
@@ -0,0 +1,112 @@
1
+ import '../node-global.mjs';
2
+ import { assertPathExists } from './assert-path-exists.mjs';
3
+
4
+ /**
5
+ * Configuration for directory extension checking.
6
+ */
7
+ export type CheckExtConfig = DeepReadonly<{
8
+ /** Array of directory paths and their expected extensions */
9
+ directories: {
10
+ /** Directory path to check */
11
+ path: string;
12
+ /** Expected file extension (including the dot) */
13
+ extension: string;
14
+ /** Optional glob patterns to ignore (defaults to ['tsconfig.json', 'globals.d.*']) */
15
+ ignorePatterns?: string[];
16
+ }[];
17
+ }>;
18
+
19
+ /**
20
+ * Validates that all files in specified directories have the correct extensions.
21
+ * @param config - Configuration specifying directories and expected extensions.
22
+ * @throws Error with details of all incorrect files found.
23
+ */
24
+ export const assertExt = async (config: CheckExtConfig): Promise<void> => {
25
+ const allIncorrectFiles: string[] = [];
26
+
27
+ // Check all directories in parallel
28
+ const results = await Promise.all(
29
+ config.directories.map(async ({ path: dir, extension, ignorePatterns }) => {
30
+ try {
31
+ return await getFilesWithIncorrectExtension(
32
+ dir,
33
+ extension,
34
+ ignorePatterns,
35
+ );
36
+ } catch (error) {
37
+ console.error(`Failed to check directory ${dir}: ${String(error)}`);
38
+ return [];
39
+ }
40
+ }),
41
+ );
42
+
43
+ // Collect all incorrect files
44
+ results.forEach((incorrectFiles) => {
45
+ allIncorrectFiles.push(...incorrectFiles);
46
+ });
47
+
48
+ if (allIncorrectFiles.length > 0) {
49
+ const generateErrorMessage = (): string => {
50
+ // Group directories by extension for a cleaner message
51
+ const extensionGroups = new Map<string, string[]>();
52
+
53
+ for (const { path: dirPath, extension } of config.directories) {
54
+ const relativePath = path.relative(process.cwd(), dirPath);
55
+ if (!extensionGroups.has(extension)) {
56
+ extensionGroups.set(extension, []);
57
+ }
58
+ extensionGroups.get(extension)?.push(relativePath);
59
+ }
60
+
61
+ // Generate message parts for each extension
62
+ const messageParts = Array.from(extensionGroups.entries()).map(
63
+ ([ext, dirs]) => {
64
+ const dirList = dirs.length === 1 ? dirs[0] : dirs.join(', ');
65
+ return `${dirList} should have ${ext} extension`;
66
+ },
67
+ );
68
+
69
+ return `All files in ${messageParts.join(' and ')}.`;
70
+ };
71
+
72
+ const errorMessage = [
73
+ 'Files with incorrect extensions found:',
74
+ ...allIncorrectFiles.map((file) => ` - ${file}`),
75
+ '',
76
+ generateErrorMessage(),
77
+ ].join('\n');
78
+
79
+ throw new Error(errorMessage);
80
+ }
81
+
82
+ echo('✓ All files have correct extensions');
83
+ };
84
+
85
+ /**
86
+ * Checks if all files in a directory have the expected extension.
87
+ * @param dir - The directory to check.
88
+ * @param expectedExtension - The expected file extension.
89
+ * @param ignorePatterns - Optional glob patterns to ignore.
90
+ * @returns Array of files with incorrect extensions.
91
+ */
92
+ const getFilesWithIncorrectExtension = async (
93
+ dir: string,
94
+ expectedExtension: string,
95
+ ignorePatterns?: readonly string[],
96
+ ): Promise<string[]> => {
97
+ await assertPathExists(dir, 'Directory');
98
+
99
+ const defaultIgnorePatterns = ['tsconfig.json', 'globals.d.*'];
100
+ const finalIgnorePatterns = ignorePatterns ?? defaultIgnorePatterns;
101
+
102
+ // Convert relative patterns to absolute paths for the glob ignore option
103
+ const absoluteIgnorePatterns = finalIgnorePatterns.map((pattern) =>
104
+ path.isAbsolute(pattern) ? pattern : `${dir}/${pattern}`,
105
+ );
106
+
107
+ const files = await glob(`${dir}/**/*`, {
108
+ ignore: absoluteIgnorePatterns,
109
+ });
110
+
111
+ return files.filter((file) => !file.endsWith(expectedExtension));
112
+ };
@@ -0,0 +1,30 @@
1
+ import * as fs from 'node:fs/promises';
2
+
3
+ /**
4
+ * Checks if a file or directory exists.
5
+ * @param filePath - The path to check.
6
+ * @returns True if the path exists.
7
+ */
8
+ export const pathExists = async (filePath: string): Promise<boolean> => {
9
+ try {
10
+ await fs.access(filePath);
11
+ return true;
12
+ } catch {
13
+ return false;
14
+ }
15
+ };
16
+
17
+ /**
18
+ * Validates that a path exists and throws if it doesn't.
19
+ * @param filePath - The path to validate.
20
+ * @param description - Description for error message.
21
+ * @throws Error if path doesn't exist.
22
+ */
23
+ export const assertPathExists = async (
24
+ filePath: string,
25
+ description = 'Path',
26
+ ): Promise<void> => {
27
+ if (!(await pathExists(filePath))) {
28
+ throw new Error(`${description} does not exist: ${filePath}`);
29
+ }
30
+ };
@@ -0,0 +1,66 @@
1
+ import '../node-global.mjs';
2
+
3
+ /**
4
+ * Checks if the repository has uncommitted changes.
5
+ * @returns True if the repo is dirty, false otherwise.
6
+ * @throws Error if git command fails.
7
+ */
8
+ export const repoIsDirty = async (): Promise<boolean> => {
9
+ const status = await getGitStatus();
10
+ return status.isDirty;
11
+ };
12
+
13
+ /**
14
+ * Checks if the repository is dirty and exits with code 1 if it is.
15
+ * @throws Error if git command fails.
16
+ */
17
+ export const assertRepoIsDirty = async (): Promise<void> => {
18
+ try {
19
+ const status = await getGitStatus();
20
+
21
+ if (!status.isDirty) {
22
+ echo('Repo is clean\n');
23
+ return;
24
+ }
25
+
26
+ echo('Repo is dirty\n');
27
+ echo('Changed files:\n');
28
+ echo(status.stdout);
29
+
30
+ // Show files not tracked by git and unstaged changes
31
+ const addResult = await $('git add -N .');
32
+ if (addResult.type === 'error') {
33
+ echo('Warning: Failed to add untracked files for diff\n');
34
+ }
35
+
36
+ const diffResult = await $('git diff');
37
+ if (diffResult.type === 'error') {
38
+ echo('Warning: Failed to show diff\n');
39
+ }
40
+
41
+ process.exit(1);
42
+ } catch (error) {
43
+ echo(`Error checking repository status: ${String(error)}\n`);
44
+ process.exit(1);
45
+ }
46
+ };
47
+
48
+ /**
49
+ * Gets the git status of the repository.
50
+ * @returns An object containing status information.
51
+ */
52
+ const getGitStatus = async (): Promise<{
53
+ isDirty: boolean;
54
+ stdout: string;
55
+ }> => {
56
+ const res = await $('git status --porcelain');
57
+
58
+ if (res.type === 'error') {
59
+ throw new Error(`Failed to get git status: ${res.exception.message}`);
60
+ }
61
+
62
+ return {
63
+ isDirty: res.stdout.trim() !== '',
64
+ stdout: res.stdout,
65
+ };
66
+ };
@@ -0,0 +1,44 @@
1
+ import { exec, type ExecException } from 'node:child_process';
2
+
3
+ export type ExecResult = Readonly<
4
+ | { type: 'ok'; stdout: string; stderr: string }
5
+ | { type: 'error'; exception: ExecException }
6
+ >;
7
+
8
+ /**
9
+ * Executes a shell command asynchronously.
10
+ * @param cmd - The command to execute.
11
+ * @param options - Optional configuration for command execution.
12
+ * @returns A promise that resolves with the command result.
13
+ */
14
+ export const $ = (
15
+ cmd: string,
16
+ options: Readonly<{ silent?: boolean; timeout?: number }> = {},
17
+ ): Promise<ExecResult> => {
18
+ const { silent = false, timeout = 30000 } = options;
19
+
20
+ if (!silent) {
21
+ console.log(`$ ${cmd}`);
22
+ }
23
+
24
+ return new Promise((resolve) => {
25
+ const execOptions = { timeout };
26
+
27
+ exec(cmd, execOptions, (error, stdout, stderr) => {
28
+ if (!silent) {
29
+ if (stdout !== '') {
30
+ console.log(stdout);
31
+ }
32
+ if (stderr !== '') {
33
+ console.error(stderr);
34
+ }
35
+ }
36
+
37
+ if (error !== null) {
38
+ resolve({ type: 'error', exception: error });
39
+ } else {
40
+ resolve({ type: 'ok', stdout, stderr });
41
+ }
42
+ });
43
+ });
44
+ };
@@ -0,0 +1,241 @@
1
+ import glob from 'fast-glob';
2
+ import { exec } from 'node:child_process';
3
+ import { readFile, writeFile } from 'node:fs/promises';
4
+ import { promisify } from 'node:util';
5
+ import * as prettier from 'prettier';
6
+
7
+ const execAsync = promisify(exec);
8
+
9
+ /**
10
+ * Format files matching the given glob pattern using Prettier
11
+ * @param pathGlob - Glob pattern to match files
12
+ * @returns 'ok' if successful, 'err' if any errors occurred
13
+ */
14
+ export const formatFiles = async (pathGlob: string): Promise<'ok' | 'err'> => {
15
+ try {
16
+ // Find all files matching the glob
17
+ const files = await glob(pathGlob, {
18
+ absolute: true,
19
+ ignore: ['**/node_modules/**', '**/.git/**'],
20
+ dot: true,
21
+ });
22
+
23
+ if (files.length === 0) {
24
+ console.log('No files found matching pattern:', pathGlob);
25
+ return 'ok';
26
+ }
27
+
28
+ console.log(`Formatting ${files.length} files...`);
29
+
30
+ // Format each file
31
+ const results = await Promise.allSettled(
32
+ files.map(async (filePath) => {
33
+ try {
34
+ // Read file content
35
+ const content = await readFile(filePath, 'utf8');
36
+
37
+ // Resolve prettier config for this file
38
+ const options = await prettier.resolveConfig(filePath);
39
+
40
+ // Check if file is ignored by prettier
41
+ const fileInfo = await prettier.getFileInfo(filePath, {
42
+ ignorePath: '.prettierignore',
43
+ });
44
+
45
+ if (fileInfo.ignored) {
46
+ console.log(`Skipping ignored file: ${filePath}`);
47
+ return;
48
+ }
49
+
50
+ // Format the content
51
+ const formatted = await prettier.format(content, {
52
+ ...options,
53
+ filepath: filePath,
54
+ });
55
+
56
+ // Only write if content changed
57
+ if (formatted !== content) {
58
+ await writeFile(filePath, formatted, 'utf8');
59
+ console.log(`Formatted: ${filePath}`);
60
+ }
61
+ } catch (error) {
62
+ console.error(`Error formatting ${filePath}:`, error);
63
+ throw error;
64
+ }
65
+ }),
66
+ );
67
+
68
+ // Check if any formatting failed
69
+ const hasErrors = results.some((result) => result.status === 'rejected');
70
+ return hasErrors ? 'err' : 'ok';
71
+ } catch (error) {
72
+ console.error('Error in formatFiles:', error);
73
+ return 'err';
74
+ }
75
+ };
76
+
77
+ /**
78
+ * Format only files that have been changed (git status)
79
+ * @returns 'ok' if successful, 'err' if any errors occurred
80
+ */
81
+ export const formatChanged = async (): Promise<'ok' | 'err'> => {
82
+ try {
83
+ // Get changed files from git status
84
+ const { stdout, stderr } = await execAsync('git status --porcelain');
85
+
86
+ if (stderr !== '') {
87
+ console.error('Git error:', stderr);
88
+ return 'err';
89
+ }
90
+
91
+ // Parse git status output
92
+ const files = stdout
93
+ .split('\n')
94
+ .filter((line) => line.trim() !== '')
95
+ .map((line) => {
96
+ // Status format: "XY filename" where X and Y are status codes
97
+ const match = /^..\s+(.+)$/u.exec(line);
98
+ return match?.[1];
99
+ })
100
+ .filter(
101
+ (file): file is string =>
102
+ // Filter out deleted files (status starts with 'D')
103
+ file !== undefined && !stdout.includes(`D ${file}`),
104
+ );
105
+
106
+ if (files.length === 0) {
107
+ console.log('No changed files to format');
108
+ return 'ok';
109
+ }
110
+
111
+ console.log('Formatting changed files:', files);
112
+
113
+ // Format each changed file
114
+ const results = await Promise.allSettled(
115
+ files.map(async (filePath) => {
116
+ try {
117
+ // Check if file exists and is not deleted
118
+ const content = await readFile(filePath, 'utf8').catch(() => null);
119
+ if (content === null) {
120
+ console.log(`Skipping non-existent file: ${filePath}`);
121
+ return;
122
+ }
123
+
124
+ // Resolve prettier config for this file
125
+ const options = await prettier.resolveConfig(filePath);
126
+
127
+ // Check if file is ignored by prettier
128
+ const fileInfo = await prettier.getFileInfo(filePath, {
129
+ ignorePath: '.prettierignore',
130
+ });
131
+
132
+ if (fileInfo.ignored) {
133
+ console.log(`Skipping ignored file: ${filePath}`);
134
+ return;
135
+ }
136
+
137
+ // Format the content
138
+ const formatted = await prettier.format(content, {
139
+ ...options,
140
+ filepath: filePath,
141
+ });
142
+
143
+ // Only write if content changed
144
+ if (formatted !== content) {
145
+ await writeFile(filePath, formatted, 'utf8');
146
+ console.log(`Formatted: ${filePath}`);
147
+ }
148
+ } catch (error) {
149
+ console.error(`Error formatting ${filePath}:`, error);
150
+ throw error;
151
+ }
152
+ }),
153
+ );
154
+
155
+ // Check if any formatting failed
156
+ const hasErrors = results.some((result) => result.status === 'rejected');
157
+ return hasErrors ? 'err' : 'ok';
158
+ } catch (error) {
159
+ console.error('Error in formatChanged:', error);
160
+ return 'err';
161
+ }
162
+ };
163
+
164
+ /**
165
+ * Format only files that differ from the specified base branch or commit
166
+ * @param base - Base branch name or commit hash to compare against (defaults to 'main')
167
+ * @returns 'ok' if successful, 'err' if any errors occurred
168
+ */
169
+ export const formatDiffFrom = async (
170
+ base: string = 'main',
171
+ ): Promise<'ok' | 'err'> => {
172
+ try {
173
+ // Get files that differ from base branch/commit (excluding deleted files)
174
+ const { stdout, stderr } = await execAsync(
175
+ `git diff --name-only ${base} --diff-filter=d`,
176
+ );
177
+
178
+ if (stderr !== '') {
179
+ console.error('Git error:', stderr);
180
+ return 'err';
181
+ }
182
+
183
+ // Parse git diff output
184
+ const files = stdout
185
+ .split('\n')
186
+ .map((line) => line.trim())
187
+ .filter((line) => line !== '');
188
+
189
+ if (files.length === 0) {
190
+ console.log(`No files differ from ${base}`);
191
+ return 'ok';
192
+ }
193
+
194
+ console.log(`Formatting files that differ from ${base}:`, files);
195
+
196
+ // Format each file
197
+ const results = await Promise.allSettled(
198
+ files.map(async (filePath) => {
199
+ try {
200
+ // Read file content
201
+ const content = await readFile(filePath, 'utf8');
202
+
203
+ // Resolve prettier config for this file
204
+ const options = await prettier.resolveConfig(filePath);
205
+
206
+ // Check if file is ignored by prettier
207
+ const fileInfo = await prettier.getFileInfo(filePath, {
208
+ ignorePath: '.prettierignore',
209
+ });
210
+
211
+ if (fileInfo.ignored) {
212
+ console.log(`Skipping ignored file: ${filePath}`);
213
+ return;
214
+ }
215
+
216
+ // Format the content
217
+ const formatted = await prettier.format(content, {
218
+ ...options,
219
+ filepath: filePath,
220
+ });
221
+
222
+ // Only write if content changed
223
+ if (formatted !== content) {
224
+ await writeFile(filePath, formatted, 'utf8');
225
+ console.log(`Formatted: ${filePath}`);
226
+ }
227
+ } catch (error) {
228
+ console.error(`Error formatting ${filePath}:`, error);
229
+ throw error;
230
+ }
231
+ }),
232
+ );
233
+
234
+ // Check if any formatting failed
235
+ const hasErrors = results.some((result) => result.status === 'rejected');
236
+ return hasErrors ? 'err' : 'ok';
237
+ } catch (error) {
238
+ console.error('Error in formatDiffFrom:', error);
239
+ return 'err';
240
+ }
241
+ };
@@ -0,0 +1,138 @@
1
+ import dedent from 'dedent';
2
+ import { mkdir, rm, writeFile } from 'node:fs/promises';
3
+ import { join } from 'node:path';
4
+ import { formatDiffFrom, formatFiles } from './format.mjs';
5
+
6
+ describe('formatFiles', () => {
7
+ const testDir = join(process.cwd(), 'test-format-files');
8
+
9
+ // Helper to create a test file with unformatted content
10
+ const createTestFile = async (
11
+ filename: string,
12
+ content: string,
13
+ ): Promise<string> => {
14
+ const filePath = join(testDir, filename);
15
+ await writeFile(filePath, content, 'utf8');
16
+ return filePath;
17
+ };
18
+
19
+ // Helper to read file content
20
+ const readTestFile = async (filePath: string): Promise<string> => {
21
+ const { readFile } = await import('node:fs/promises');
22
+ return readFile(filePath, 'utf8');
23
+ };
24
+
25
+ test('should format files matching glob pattern', async () => {
26
+ // Setup test directory
27
+ await mkdir(testDir, { recursive: true });
28
+
29
+ try {
30
+ // Create test files with unformatted code
31
+ const file1 = await createTestFile(
32
+ 'test1.ts',
33
+ dedent`
34
+ const foo = "bar"
35
+ const baz = {a:1,b:2}
36
+ `,
37
+ );
38
+
39
+ const file2 = await createTestFile(
40
+ 'test2.ts',
41
+ dedent`
42
+ function test ( x:number,y:string ) {
43
+ return x+1
44
+ }
45
+ `,
46
+ );
47
+
48
+ // Create a non-matching file
49
+ await createTestFile('test.md', '# Test\n\nSome spaces');
50
+
51
+ // Format TypeScript files
52
+ const result = await formatFiles(`${testDir}/*.ts`);
53
+ expect(result).toBe('ok');
54
+
55
+ // Check that files were formatted
56
+ const content1 = await readTestFile(file1);
57
+ expect(content1).toBe(
58
+ `${dedent`
59
+ const foo = 'bar';
60
+ const baz = { a: 1, b: 2 };
61
+ `}\n`,
62
+ );
63
+
64
+ const content2 = await readTestFile(file2);
65
+ expect(content2).toBe(
66
+ `${dedent`
67
+ function test(x: number, y: string) {
68
+ return x + 1;
69
+ }
70
+ `}\n`,
71
+ );
72
+
73
+ // Check that non-matching file was not touched
74
+ const mdContent = await readTestFile(join(testDir, 'test.md'));
75
+ expect(mdContent).toBe('# Test\n\nSome spaces');
76
+ } finally {
77
+ // Cleanup
78
+ await rm(testDir, { recursive: true, force: true });
79
+ }
80
+ });
81
+
82
+ test('should return ok when no files match pattern', async () => {
83
+ const result = await formatFiles('/non-existent-path/*.ts');
84
+ expect(result).toBe('ok');
85
+ });
86
+
87
+ test('should handle nested directories with glob pattern', async () => {
88
+ // Setup test directory with nested structure
89
+ await mkdir(join(testDir, 'src', 'utils'), { recursive: true });
90
+
91
+ try {
92
+ // Create nested test file
93
+ const nestedFile = await createTestFile(
94
+ join('src', 'utils', 'helper.ts'),
95
+ dedent`
96
+ export const helper=(x:number)=>{return x*2}
97
+ `,
98
+ );
99
+
100
+ // Format with recursive glob
101
+ const result = await formatFiles(`${testDir}/**/*.ts`);
102
+ expect(result).toBe('ok');
103
+
104
+ // Check that nested file was formatted
105
+ const content = await readTestFile(nestedFile);
106
+ expect(content).toBe(
107
+ `${dedent`
108
+ export const helper = (x: number) => {
109
+ return x * 2;
110
+ };
111
+ `}\n`,
112
+ );
113
+ } finally {
114
+ // Cleanup
115
+ await rm(testDir, { recursive: true, force: true });
116
+ }
117
+ });
118
+ });
119
+
120
+ describe('formatDiffFrom', () => {
121
+ test('should use default base branch "main"', () => {
122
+ // This test would require a git repository setup, so we'll just verify the function exists
123
+ // and can be called with no arguments
124
+ expect(typeof formatDiffFrom).toBe('function');
125
+ expect(formatDiffFrom.length).toBe(0); // Function has default parameter
126
+ });
127
+
128
+ test('should accept custom base branch or commit', () => {
129
+ // Verify the function can be called with a custom base
130
+ const customBases = ['develop', 'feature/test', 'abc123'];
131
+
132
+ for (const base of customBases) {
133
+ // This would normally test against a real git repo, but we're just verifying
134
+ // the function signature accepts the parameter
135
+ expect(() => formatDiffFrom(base)).not.toThrow();
136
+ }
137
+ });
138
+ });
@@ -0,0 +1,228 @@
1
+ import micromatch from 'micromatch';
2
+ import '../node-global.mjs';
3
+ import { assertExt } from './assert-ext.mjs';
4
+ import { assertPathExists } from './assert-path-exists.mjs';
5
+
6
+ /**
7
+ * Configuration for index file generation.
8
+ */
9
+ export type GenIndexConfig = DeepReadonly<{
10
+ /** Target directories to generate index files for (string or array of strings) */
11
+ targetDirectory: string | string[];
12
+
13
+ /** File extension of source files to export (default: '.mts') */
14
+ sourceExtension?: `.${string}`;
15
+
16
+ /** File extension to use in export statements (default: '.mjs') */
17
+ exportExtension?: `.${string}`;
18
+
19
+ /** Glob patterns of files to exclude from exports (default: excludes .d.* and .test.* files) */
20
+ excludePatterns?: string[];
21
+ }>;
22
+
23
+ /**
24
+ * Generates index.mts files recursively in `config.targetDirectory`.
25
+ * @param config - Configuration for index file generation
26
+ * @throws Error if any step fails.
27
+ */
28
+ export const genIndex = async (config: GenIndexConfig): Promise<void> => {
29
+ echo('Starting index file generation...\n');
30
+
31
+ // Merge config with defaults
32
+ const filledConfig: DeepRequired<GenIndexConfig> = fillConfig(config);
33
+
34
+ // Normalize target directories to array
35
+ const targetDirs =
36
+ typeof config.targetDirectory === 'string'
37
+ ? [config.targetDirectory]
38
+ : config.targetDirectory;
39
+
40
+ try {
41
+ // Step 1: Validate file extensions
42
+ echo('1. Validating file extensions...');
43
+ await assertExt({
44
+ directories: [
45
+ {
46
+ path: path.resolve(projectRootPath, './src'),
47
+ extension: '.mts',
48
+ ignorePatterns: ['tsconfig.json', 'globals.d.mts'],
49
+ },
50
+ {
51
+ path: path.resolve(projectRootPath, './scripts'),
52
+ extension: '.mts',
53
+ ignorePatterns: ['tsconfig.json'],
54
+ },
55
+ ],
56
+ });
57
+ echo('✓ File extensions validated\n');
58
+
59
+ // Step 2: Verify target directories exist
60
+ for (const dir of targetDirs) {
61
+ const resolvedDir = path.resolve(dir);
62
+ // eslint-disable-next-line no-await-in-loop
63
+ await assertPathExists(resolvedDir, `Target directory: ${dir}`);
64
+ }
65
+
66
+ // Step 3: Generate index files
67
+ echo('2. Generating index files...');
68
+ for (const dir of targetDirs) {
69
+ const resolvedDir = path.resolve(dir);
70
+ // eslint-disable-next-line no-await-in-loop
71
+ await generateIndexFileForDir(resolvedDir, filledConfig);
72
+ }
73
+ echo('✓ Index files generated\n');
74
+
75
+ // Step 4: Format generated files
76
+ echo('3. Formatting generated files...');
77
+ const fmtResult = await $('npm run fmt');
78
+ if (fmtResult.type === 'error') {
79
+ throw new Error(`Formatting failed: ${fmtResult.exception.message}`);
80
+ }
81
+ echo('✓ Formatting completed\n');
82
+
83
+ echo('✅ Index file generation completed successfully!\n');
84
+ } catch (error) {
85
+ echo(`❌ Index generation failed: ${String(error)}\n`);
86
+ throw error;
87
+ }
88
+ };
89
+
90
+ const fillConfig = (config: GenIndexConfig): DeepRequired<GenIndexConfig> => {
91
+ const sourceExtension = config.sourceExtension ?? '.mts';
92
+ const exportExtension = config.exportExtension ?? '.mjs'; // For ESM imports, .mts resolves to .mjs
93
+
94
+ return {
95
+ targetDirectory: config.targetDirectory,
96
+ sourceExtension,
97
+ exportExtension,
98
+ excludePatterns: config.excludePatterns ?? [
99
+ `*.d${sourceExtension}`,
100
+ `*.test${sourceExtension}`,
101
+ ],
102
+ };
103
+ };
104
+
105
+ /**
106
+ * Generates an index.mts file for the given directory.
107
+ * Recursively calls itself for subdirectories.
108
+ * @param dirPath - The absolute path to the directory to process.
109
+ * @param config - The merged configuration object.
110
+ * @param baseDir - The base directory path for calculating relative paths (optional, defaults to dirPath).
111
+ * @throws Error if directory processing fails.
112
+ */
113
+ const generateIndexFileForDir = async (
114
+ dirPath: string,
115
+ config: DeepReadonly<{
116
+ sourceExtension: `.${string}`;
117
+ exportExtension: `.${string}`;
118
+ excludePatterns: string[];
119
+ }>,
120
+ baseDir?: string,
121
+ ): Promise<void> => {
122
+ try {
123
+ const actualBaseDir = baseDir ?? dirPath;
124
+ const entries = await fs.readdir(dirPath, { withFileTypes: true });
125
+
126
+ const subDirectories: string[] = [];
127
+ const filesToExport: string[] = [];
128
+
129
+ for (const entry of entries) {
130
+ const entryName = entry.name;
131
+ const entryPath = path.join(dirPath, entryName);
132
+ const relativePath = path.relative(actualBaseDir, entryPath);
133
+
134
+ if (entry.isDirectory()) {
135
+ subDirectories.push(entryName);
136
+ // Recursively call for subdirectories first
137
+ // eslint-disable-next-line no-await-in-loop
138
+ await generateIndexFileForDir(entryPath, config, actualBaseDir);
139
+ } else if (entry.isFile() && shouldExportFile(relativePath, config)) {
140
+ filesToExport.push(entryName);
141
+ }
142
+ }
143
+
144
+ const indexContent = generateIndexContent(
145
+ subDirectories,
146
+ filesToExport,
147
+ config,
148
+ );
149
+
150
+ const indexPath = path.join(dirPath, `index${config.sourceExtension}`);
151
+
152
+ await fs.writeFile(indexPath, indexContent);
153
+ echo(`Generated: ${path.relative(process.cwd(), indexPath)}`);
154
+ } catch (error) {
155
+ throw new Error(
156
+ `Failed to generate index for directory ${dirPath}: ${String(error)}`,
157
+ );
158
+ }
159
+ };
160
+
161
+ /**
162
+ * Determines if a file should be exported in the index file.
163
+ * @param filePath - The relative path to the file from the target directory.
164
+ * @param config - The merged configuration object.
165
+ * @returns True if the file should be exported.
166
+ */
167
+ const shouldExportFile = (
168
+ filePath: string,
169
+ config: DeepReadonly<{
170
+ sourceExtension: `.${string}`;
171
+ excludePatterns: string[];
172
+ }>,
173
+ ): boolean => {
174
+ const fileName = path.basename(filePath);
175
+
176
+ // Must have the correct source extension
177
+ if (!fileName.endsWith(config.sourceExtension)) {
178
+ return false;
179
+ }
180
+
181
+ // Don't export the index file itself
182
+ if (fileName === `index${config.sourceExtension}`) {
183
+ return false;
184
+ }
185
+
186
+ // Check against exclusion patterns
187
+ for (const pattern of config.excludePatterns) {
188
+ if (
189
+ micromatch.isMatch(filePath, pattern) ||
190
+ micromatch.isMatch(fileName, pattern)
191
+ ) {
192
+ return false;
193
+ }
194
+ }
195
+
196
+ return true;
197
+ };
198
+
199
+ /**
200
+ * Generates the content for an index file.
201
+ * @param subDirectories - Array of subdirectory names.
202
+ * @param filesToExport - Array of file names to export.
203
+ * @param config - The merged configuration object.
204
+ * @returns The index file content.
205
+ */
206
+ const generateIndexContent = (
207
+ subDirectories: readonly string[],
208
+ filesToExport: readonly string[],
209
+ config: DeepReadonly<{
210
+ sourceExtension: string;
211
+ exportExtension: `.${string}`;
212
+ }>,
213
+ ): string => {
214
+ const exportStatements = [
215
+ ...subDirectories.map(
216
+ (subDir) => `export * from "./${subDir}/index${config.exportExtension}";`,
217
+ ),
218
+ ...filesToExport.map((file) => {
219
+ const fileNameWithoutExt = path.basename(file, config.sourceExtension);
220
+
221
+ return `export * from "./${fileNameWithoutExt}${config.exportExtension}";`;
222
+ }),
223
+ ];
224
+
225
+ return exportStatements.length === 0
226
+ ? 'export {};'
227
+ : exportStatements.join('\n');
228
+ };
@@ -0,0 +1,6 @@
1
+ export * from './assert-ext.mjs';
2
+ export * from './assert-path-exists.mjs';
3
+ export * from './assert-repo-is-dirty.mjs';
4
+ export * from './exec-async.mjs';
5
+ export * from './format.mjs';
6
+ export * from './gen-index.mjs';
@@ -0,0 +1 @@
1
+ /// <reference types="ts-type-forge" />
package/src/index.mts ADDED
@@ -0,0 +1 @@
1
+ export * from './functions/index.mjs';
@@ -0,0 +1,27 @@
1
+ import { default as glob_ } from 'fast-glob';
2
+ import * as fs_ from 'node:fs/promises';
3
+ import * as path_ from 'node:path';
4
+ import { $ as $_ } from './functions/exec-async.mjs';
5
+ import { projectRootPath as projectRootPath_ } from './project-root-path.mjs';
6
+
7
+ const globalsDef = {
8
+ $: $_,
9
+ echo: console.log,
10
+ projectRootPath: projectRootPath_,
11
+
12
+ path: path_,
13
+ fs: fs_,
14
+ glob: glob_,
15
+ } as const;
16
+
17
+ Object.assign(globalThis, globalsDef);
18
+
19
+ declare global {
20
+ const $: typeof $_;
21
+ const echo: typeof console.log;
22
+ const projectRootPath: typeof projectRootPath_;
23
+
24
+ const path: typeof path_;
25
+ const fs: typeof fs_;
26
+ const glob: typeof glob_;
27
+ }
@@ -0,0 +1,3 @@
1
+ import * as path from 'node:path';
2
+
3
+ export const projectRootPath = path.resolve(import.meta.dirname, '..');