@rushstack/package-deps-hash 4.6.7 → 4.7.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/CHANGELOG.json CHANGED
@@ -1,6 +1,38 @@
1
1
  {
2
2
  "name": "@rushstack/package-deps-hash",
3
3
  "entries": [
4
+ {
5
+ "version": "4.7.0",
6
+ "tag": "@rushstack/package-deps-hash_v4.7.0",
7
+ "date": "Thu, 19 Feb 2026 00:04:53 GMT",
8
+ "comments": {
9
+ "minor": [
10
+ {
11
+ "comment": "Normalize package layout. CommonJS is now under `lib-commonjs`, DTS is now under `lib-dts`, and ESM is now under `lib-esm`. Imports to `lib` still work as before, handled by the `\"exports\"` field in `package.json`."
12
+ }
13
+ ],
14
+ "dependency": [
15
+ {
16
+ "comment": "Updating dependency \"@rushstack/node-core-library\" to `5.20.0`"
17
+ },
18
+ {
19
+ "comment": "Updating dependency \"@rushstack/heft\" to `1.2.0`"
20
+ }
21
+ ]
22
+ }
23
+ },
24
+ {
25
+ "version": "4.6.8",
26
+ "tag": "@rushstack/package-deps-hash_v4.6.8",
27
+ "date": "Sat, 07 Feb 2026 01:13:26 GMT",
28
+ "comments": {
29
+ "dependency": [
30
+ {
31
+ "comment": "Updating dependency \"@rushstack/heft\" to `1.1.14`"
32
+ }
33
+ ]
34
+ }
35
+ },
4
36
  {
5
37
  "version": "4.6.7",
6
38
  "tag": "@rushstack/package-deps-hash_v4.6.7",
package/CHANGELOG.md CHANGED
@@ -1,6 +1,18 @@
1
1
  # Change Log - @rushstack/package-deps-hash
2
2
 
3
- This log was last generated on Wed, 04 Feb 2026 20:42:47 GMT and should not be manually modified.
3
+ This log was last generated on Thu, 19 Feb 2026 00:04:53 GMT and should not be manually modified.
4
+
5
+ ## 4.7.0
6
+ Thu, 19 Feb 2026 00:04:53 GMT
7
+
8
+ ### Minor changes
9
+
10
+ - Normalize package layout. CommonJS is now under `lib-commonjs`, DTS is now under `lib-dts`, and ESM is now under `lib-esm`. Imports to `lib` still work as before, handled by the `"exports"` field in `package.json`.
11
+
12
+ ## 4.6.8
13
+ Sat, 07 Feb 2026 01:13:26 GMT
14
+
15
+ _Version update only_
4
16
 
5
17
  ## 4.6.7
6
18
  Wed, 04 Feb 2026 20:42:47 GMT
@@ -5,7 +5,7 @@
5
5
  "toolPackages": [
6
6
  {
7
7
  "packageName": "@microsoft/api-extractor",
8
- "packageVersion": "7.56.1"
8
+ "packageVersion": "7.56.3"
9
9
  }
10
10
  ]
11
11
  }
@@ -0,0 +1,222 @@
1
+ // Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the MIT license.
2
+ // See LICENSE in the project root for license information.
3
+ import * as path from 'node:path';
4
+ import { Executable } from '@rushstack/node-core-library';
5
+ import { ensureGitMinimumVersion } from './getRepoState';
6
+ /**
7
+ * Parses a quoted filename sourced from the output of the "git status" command.
8
+ *
9
+ * Paths with non-standard characters will be enclosed with double-quotes, and non-standard
10
+ * characters will be backslash escaped (ex. double-quotes, non-ASCII characters). The
11
+ * escaped chars can be included in one of two ways:
12
+ * - backslash-escaped chars (ex. \")
13
+ * - octal encoded chars (ex. \347)
14
+ *
15
+ * See documentation: https://git-scm.com/docs/git-status
16
+ */
17
+ export function parseGitFilename(filename) {
18
+ // If there are no double-quotes around the string, then there are no escaped characters
19
+ // to decode, so just return
20
+ if (!filename.match(/^".+"$/)) {
21
+ return filename;
22
+ }
23
+ // Need to hex encode '%' since we will be decoding the converted octal values from hex
24
+ filename = filename.replace(/%/g, '%25');
25
+ // Replace all instances of octal literals with percent-encoded hex (ex. '\347\275\221' -> '%E7%BD%91').
26
+ // This is done because the octal literals represent UTF-8 bytes, and by converting them to percent-encoded
27
+ // hex, we can use decodeURIComponent to get the Unicode chars.
28
+ filename = filename.replace(/(?:\\(\d{1,3}))/g, (match, ...[octalValue, index, source]) => {
29
+ // We need to make sure that the backslash is intended to escape the octal value. To do this, walk
30
+ // backwards from the match to ensure that it's already escaped.
31
+ const trailingBackslashes = source
32
+ .slice(0, index)
33
+ .match(/\\*$/);
34
+ return trailingBackslashes && trailingBackslashes.length > 0 && trailingBackslashes[0].length % 2 === 0
35
+ ? `%${parseInt(octalValue, 8).toString(16)}`
36
+ : match;
37
+ });
38
+ // Finally, decode the filename and unescape the escaped UTF-8 chars
39
+ return JSON.parse(decodeURIComponent(filename));
40
+ }
41
+ /**
42
+ * Parses the output of the "git ls-tree" command
43
+ */
44
+ export function parseGitLsTree(output) {
45
+ const changes = new Map();
46
+ if (output) {
47
+ // A line is expected to look like:
48
+ // 100644 blob 3451bccdc831cb43d7a70ed8e628dcf9c7f888c8 src/typings/tsd.d.ts
49
+ // 160000 commit c5880bf5b0c6c1f2e2c43c95beeb8f0a808e8bac rushstack
50
+ const gitRegex = /([0-9]{6})\s(blob|commit)\s([a-f0-9]{40})\s*(.*)/;
51
+ // Note: The output of git ls-tree uses \n newlines regardless of OS.
52
+ const outputLines = output.trim().split('\n');
53
+ for (const line of outputLines) {
54
+ if (line) {
55
+ // Take everything after the "100644 blob", which is just the hash and filename
56
+ const matches = line.match(gitRegex);
57
+ if (matches && matches[3] && matches[4]) {
58
+ const hash = matches[3];
59
+ const filename = parseGitFilename(matches[4]);
60
+ changes.set(filename, hash);
61
+ }
62
+ else {
63
+ throw new Error(`Cannot parse git ls-tree input: "${line}"`);
64
+ }
65
+ }
66
+ }
67
+ }
68
+ return changes;
69
+ }
70
+ /**
71
+ * Parses the output of the "git status" command
72
+ */
73
+ export function parseGitStatus(output, packagePath) {
74
+ const changes = new Map();
75
+ /*
76
+ * Typically, output will look something like:
77
+ * M temp_modules/rush-package-deps-hash/package.json
78
+ * D package-deps-hash/src/index.ts
79
+ */
80
+ // If there was an issue with `git ls-tree`, or there are no current changes, processOutputBlocks[1]
81
+ // will be empty or undefined
82
+ if (!output) {
83
+ return changes;
84
+ }
85
+ // Note: The output of git hash-object uses \n newlines regardless of OS.
86
+ const outputLines = output.trim().split('\n');
87
+ for (const line of outputLines) {
88
+ /*
89
+ * changeType is in the format of "XY" where "X" is the status of the file in the index and "Y" is the status of
90
+ * the file in the working tree. Some example statuses:
91
+ * - 'D' == deletion
92
+ * - 'M' == modification
93
+ * - 'A' == addition
94
+ * - '??' == untracked
95
+ * - 'R' == rename
96
+ * - 'RM' == rename with modifications
97
+ * - '[MARC]D' == deleted in work tree
98
+ * Full list of examples: https://git-scm.com/docs/git-status#_short_format
99
+ */
100
+ const match = line.match(/("(\\"|[^"])+")|(\S+\s*)/g);
101
+ if (match && match.length > 1) {
102
+ const [changeType, ...filenameMatches] = match;
103
+ // We always care about the last filename in the filenames array. In the case of non-rename changes,
104
+ // the filenames array only contains one file, so we can join all segments that were split on spaces.
105
+ // In the case of rename changes, the last item in the array is the path to the file in the working tree,
106
+ // which is the only one that we care about. It is also surrounded by double-quotes if spaces are
107
+ // included, so no need to worry about joining different segments
108
+ let lastFilename = changeType.startsWith('R')
109
+ ? filenameMatches[filenameMatches.length - 1]
110
+ : filenameMatches.join('');
111
+ lastFilename = parseGitFilename(lastFilename);
112
+ changes.set(lastFilename, changeType.trimRight());
113
+ }
114
+ }
115
+ return changes;
116
+ }
117
+ /**
118
+ * Takes a list of files and returns the current git hashes for them
119
+ *
120
+ * @public
121
+ */
122
+ export function getGitHashForFiles(filesToHash, packagePath, gitPath) {
123
+ const changes = new Map();
124
+ if (filesToHash.length) {
125
+ // Use --stdin-paths arg to pass the list of files to git in order to avoid issues with
126
+ // command length
127
+ const result = Executable.spawnSync(gitPath || 'git', ['hash-object', '--stdin-paths'], { input: filesToHash.map((x) => path.resolve(packagePath, x)).join('\n') });
128
+ if (result.status !== 0) {
129
+ ensureGitMinimumVersion(gitPath);
130
+ throw new Error(`git hash-object exited with status ${result.status}: ${result.stderr}`);
131
+ }
132
+ const hashStdout = result.stdout.trim();
133
+ // The result of "git hash-object" will be a list of file hashes delimited by newlines
134
+ const hashes = hashStdout.split('\n');
135
+ if (hashes.length !== filesToHash.length) {
136
+ throw new Error(`Passed ${filesToHash.length} file paths to Git to hash, but received ${hashes.length} hashes.`);
137
+ }
138
+ for (let i = 0; i < hashes.length; i++) {
139
+ const hash = hashes[i];
140
+ const filePath = filesToHash[i];
141
+ changes.set(filePath, hash);
142
+ }
143
+ }
144
+ return changes;
145
+ }
146
+ /**
147
+ * Executes "git ls-tree" in a folder
148
+ */
149
+ export function gitLsTree(cwdPath, gitPath) {
150
+ const result = Executable.spawnSync(gitPath || 'git', ['ls-tree', 'HEAD', '-r'], {
151
+ currentWorkingDirectory: cwdPath
152
+ });
153
+ if (result.status !== 0) {
154
+ ensureGitMinimumVersion(gitPath);
155
+ throw new Error(`git ls-tree exited with status ${result.status}: ${result.stderr}`);
156
+ }
157
+ return result.stdout;
158
+ }
159
+ /**
160
+ * Executes "git status" in a folder
161
+ */
162
+ export function gitStatus(cwdPath, gitPath) {
163
+ /**
164
+ * -s - Short format. Will be printed as 'XY PATH' or 'XY ORIG_PATH -> PATH'. Paths with non-standard
165
+ * characters will be escaped using double-quotes, and non-standard characters will be backslash
166
+ * escaped (ex. spaces, tabs, double-quotes)
167
+ * -u - Untracked files are included
168
+ *
169
+ * See documentation here: https://git-scm.com/docs/git-status
170
+ */
171
+ const result = Executable.spawnSync(gitPath || 'git', ['status', '-s', '-u', '.'], {
172
+ currentWorkingDirectory: cwdPath
173
+ });
174
+ if (result.status !== 0) {
175
+ ensureGitMinimumVersion(gitPath);
176
+ throw new Error(`git status exited with status ${result.status}: ${result.stderr}`);
177
+ }
178
+ return result.stdout;
179
+ }
180
+ /**
181
+ * Builds an object containing hashes for the files under the specified `packagePath` folder.
182
+ * @param packagePath - The folder path to derive the package dependencies from. This is typically the folder
183
+ * containing package.json. If omitted, the default value is the current working directory.
184
+ * @param excludedPaths - An optional array of file path exclusions. If a file should be omitted from the list
185
+ * of dependencies, use this to exclude it.
186
+ * @returns the package-deps.json file content
187
+ *
188
+ * @public
189
+ */
190
+ export function getPackageDeps(packagePath = process.cwd(), excludedPaths, gitPath) {
191
+ const gitLsOutput = gitLsTree(packagePath, gitPath);
192
+ // Add all the checked in hashes
193
+ const result = parseGitLsTree(gitLsOutput);
194
+ // Remove excluded paths
195
+ if (excludedPaths) {
196
+ for (const excludedPath of excludedPaths) {
197
+ result.delete(excludedPath);
198
+ }
199
+ }
200
+ // Update the checked in hashes with the current repo status
201
+ const gitStatusOutput = gitStatus(packagePath, gitPath);
202
+ const currentlyChangedFiles = parseGitStatus(gitStatusOutput, packagePath);
203
+ const filesToHash = [];
204
+ const excludedPathSet = new Set(excludedPaths);
205
+ for (const [filename, changeType] of currentlyChangedFiles) {
206
+ // See comments inside parseGitStatus() for more information
207
+ if (changeType === 'D' || (changeType.length === 2 && changeType.charAt(1) === 'D')) {
208
+ result.delete(filename);
209
+ }
210
+ else {
211
+ if (!excludedPathSet.has(filename)) {
212
+ filesToHash.push(filename);
213
+ }
214
+ }
215
+ }
216
+ const currentlyChangedFileHashes = getGitHashForFiles(filesToHash, packagePath, gitPath);
217
+ for (const [filename, hash] of currentlyChangedFileHashes) {
218
+ result.set(filename, hash);
219
+ }
220
+ return result;
221
+ }
222
+ //# sourceMappingURL=getPackageDeps.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"getPackageDeps.js","sourceRoot":"","sources":["../src/getPackageDeps.ts"],"names":[],"mappings":"AAAA,4FAA4F;AAC5F,2DAA2D;AAG3D,OAAO,KAAK,IAAI,MAAM,WAAW,CAAC;AAElC,OAAO,EAAE,UAAU,EAAE,MAAM,8BAA8B,CAAC;AAE1D,OAAO,EAAE,uBAAuB,EAAE,MAAM,gBAAgB,CAAC;AAEzD;;;;;;;;;;GAUG;AACH,MAAM,UAAU,gBAAgB,CAAC,QAAgB;IAC/C,wFAAwF;IACxF,4BAA4B;IAC5B,IAAI,CAAC,QAAQ,CAAC,KAAK,CAAC,QAAQ,CAAC,EAAE,CAAC;QAC9B,OAAO,QAAQ,CAAC;IAClB,CAAC;IAED,uFAAuF;IACvF,QAAQ,GAAG,QAAQ,CAAC,OAAO,CAAC,IAAI,EAAE,KA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AAC;IACH,CAAC;IAED,MAAM,0BAA0B,GAAwB,kBAAkB,CACxE,WAAW,EACX,WAAW,EACX,OAAO,CACR,CAAC;IACF,KAAK,MAAM,CAAC,QAAQ,EAAE,IAAI,CAAC,IAAI,0BAA0B,EAAE,CAAC;QAC1D,MAAM,CAAC,GAAG,CAAC,QAAQ,EAAE,IAAI,CAAC,CAAC;IAC7B,CAAC;IAED,OAAO,MAAM,CAAC;AAChB,CAAC","sourcesContent":["// Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the MIT license.\n// See LICENSE in the project root for license information.\n\nimport type * as child_process from 'node:child_process';\nimport * as path from 'node:path';\n\nimport { Executable } from '@rushstack/node-core-library';\n\nimport { ensureGitMinimumVersion } from './getRepoState';\n\n/**\n * Parses a quoted filename sourced from the output of the \"git status\" command.\n *\n * Paths with non-standard characters will be enclosed with double-quotes, and non-standard\n * characters will be backslash escaped (ex. double-quotes, non-ASCII characters). The\n * escaped chars can be included in one of two ways:\n * - backslash-escaped chars (ex. \\\")\n * - octal encoded chars (ex. \\347)\n *\n * See documentation: https://git-scm.com/docs/git-status\n */\nexport function parseGitFilename(filename: string): string {\n // If there are no double-quotes around the string, then there are no escaped characters\n // to decode, so just return\n if (!filename.match(/^\".+\"$/)) {\n return filename;\n }\n\n // Need to hex encode '%' since we will be decoding the converted octal values from hex\n filename = filename.replace(/%/g, '%25');\n // Replace all instances of octal literals with percent-encoded hex (ex. '\\347\\275\\221' -> '%E7%BD%91').\n // This is done because the octal literals represent UTF-8 bytes, and by converting them to percent-encoded\n // hex, we can use decodeURIComponent to get the Unicode chars.\n filename = filename.replace(/(?:\\\\(\\d{1,3}))/g, (match, ...[octalValue, index, source]) => {\n // We need to make sure that the backslash is intended to escape the octal value. To do this, walk\n // backwards from the match to ensure that it's already escaped.\n const trailingBackslashes: RegExpMatchArray | null = (source as string)\n .slice(0, index as number)\n .match(/\\\\*$/);\n return trailingBackslashes && trailingBackslashes.length > 0 && trailingBackslashes[0].length % 2 === 0\n ? `%${parseInt(octalValue, 8).toString(16)}`\n : match;\n });\n\n // Finally, decode the filename and unescape the escaped UTF-8 chars\n return JSON.parse(decodeURIComponent(filename));\n}\n\n/**\n * Parses the output of the \"git ls-tree\" command\n */\nexport function parseGitLsTree(output: string): Map<string, string> {\n const changes: Map<string, string> = new Map<string, string>();\n\n if (output) {\n // A line is expected to look like:\n // 100644 blob 3451bccdc831cb43d7a70ed8e628dcf9c7f888c8 src/typings/tsd.d.ts\n // 160000 commit c5880bf5b0c6c1f2e2c43c95beeb8f0a808e8bac rushstack\n const gitRegex: RegExp = /([0-9]{6})\\s(blob|commit)\\s([a-f0-9]{40})\\s*(.*)/;\n\n // Note: The output of git ls-tree uses \\n newlines regardless of OS.\n const outputLines: string[] = output.trim().split('\\n');\n for (const line of outputLines) {\n if (line) {\n // Take everything after the \"100644 blob\", which is just the hash and filename\n const matches: RegExpMatchArray | null = line.match(gitRegex);\n if (matches && matches[3] && matches[4]) {\n const hash: string = matches[3];\n const filename: string = parseGitFilename(matches[4]);\n\n changes.set(filename, hash);\n } else {\n throw new Error(`Cannot parse git ls-tree input: \"${line}\"`);\n }\n }\n }\n }\n\n return changes;\n}\n\n/**\n * Parses the output of the \"git status\" command\n */\nexport function parseGitStatus(output: string, packagePath: string): Map<string, string> {\n const changes: Map<string, string> = new Map<string, string>();\n\n /*\n * Typically, output will look something like:\n * M temp_modules/rush-package-deps-hash/package.json\n * D package-deps-hash/src/index.ts\n */\n\n // If there was an issue with `git ls-tree`, or there are no current changes, processOutputBlocks[1]\n // will be empty or undefined\n if (!output) {\n return changes;\n }\n\n // Note: The output of git hash-object uses \\n newlines regardless of OS.\n const outputLines: string[] = output.trim().split('\\n');\n for (const line of outputLines) {\n /*\n * changeType is in the format of \"XY\" where \"X\" is the status of the file in the index and \"Y\" is the status of\n * the file in the working tree. Some example statuses:\n * - 'D' == deletion\n * - 'M' == modification\n * - 'A' == addition\n * - '??' == untracked\n * - 'R' == rename\n * - 'RM' == rename with modifications\n * - '[MARC]D' == deleted in work tree\n * Full list of examples: https://git-scm.com/docs/git-status#_short_format\n */\n const match: RegExpMatchArray | null = line.match(/(\"(\\\\\"|[^\"])+\")|(\\S+\\s*)/g);\n\n if (match && match.length > 1) {\n const [changeType, ...filenameMatches] = match;\n\n // We always care about the last filename in the filenames array. In the case of non-rename changes,\n // the filenames array only contains one file, so we can join all segments that were split on spaces.\n // In the case of rename changes, the last item in the array is the path to the file in the working tree,\n // which is the only one that we care about. It is also surrounded by double-quotes if spaces are\n // included, so no need to worry about joining different segments\n let lastFilename: string = changeType.startsWith('R')\n ? filenameMatches[filenameMatches.length - 1]\n : filenameMatches.join('');\n lastFilename = parseGitFilename(lastFilename);\n\n changes.set(lastFilename, changeType.trimRight());\n }\n }\n\n return changes;\n}\n\n/**\n * Takes a list of files and returns the current git hashes for them\n *\n * @public\n */\nexport function getGitHashForFiles(\n filesToHash: string[],\n packagePath: string,\n gitPath?: string\n): Map<string, string> {\n const changes: Map<string, string> = new Map<string, string>();\n\n if (filesToHash.length) {\n // Use --stdin-paths arg to pass the list of files to git in order to avoid issues with\n // command length\n const result: child_process.SpawnSyncReturns<string> = Executable.spawnSync(\n gitPath || 'git',\n ['hash-object', '--stdin-paths'],\n { input: filesToHash.map((x) => path.resolve(packagePath, x)).join('\\n') }\n );\n\n if (result.status !== 0) {\n ensureGitMinimumVersion(gitPath);\n\n throw new Error(`git hash-object exited with status ${result.status}: ${result.stderr}`);\n }\n\n const hashStdout: string = result.stdout.trim();\n\n // The result of \"git hash-object\" will be a list of file hashes delimited by newlines\n const hashes: string[] = hashStdout.split('\\n');\n\n if (hashes.length !== filesToHash.length) {\n throw new Error(\n `Passed ${filesToHash.length} file paths to Git to hash, but received ${hashes.length} hashes.`\n );\n }\n\n for (let i: number = 0; i < hashes.length; i++) {\n const hash: string = hashes[i];\n const filePath: string = filesToHash[i];\n changes.set(filePath, hash);\n }\n }\n\n return changes;\n}\n\n/**\n * Executes \"git ls-tree\" in a folder\n */\nexport function gitLsTree(cwdPath: string, gitPath?: string): string {\n const result: child_process.SpawnSyncReturns<string> = Executable.spawnSync(\n gitPath || 'git',\n ['ls-tree', 'HEAD', '-r'],\n {\n currentWorkingDirectory: cwdPath\n }\n );\n\n if (result.status !== 0) {\n ensureGitMinimumVersion(gitPath);\n\n throw new Error(`git ls-tree exited with status ${result.status}: ${result.stderr}`);\n }\n\n return result.stdout;\n}\n\n/**\n * Executes \"git status\" in a folder\n */\nexport function gitStatus(cwdPath: string, gitPath?: string): string {\n /**\n * -s - Short format. Will be printed as 'XY PATH' or 'XY ORIG_PATH -> PATH'. Paths with non-standard\n * characters will be escaped using double-quotes, and non-standard characters will be backslash\n * escaped (ex. spaces, tabs, double-quotes)\n * -u - Untracked files are included\n *\n * See documentation here: https://git-scm.com/docs/git-status\n */\n const result: child_process.SpawnSyncReturns<string> = Executable.spawnSync(\n gitPath || 'git',\n ['status', '-s', '-u', '.'],\n {\n currentWorkingDirectory: cwdPath\n }\n );\n\n if (result.status !== 0) {\n ensureGitMinimumVersion(gitPath);\n\n throw new Error(`git status exited with status ${result.status}: ${result.stderr}`);\n }\n\n return result.stdout;\n}\n\n/**\n * Builds an object containing hashes for the files under the specified `packagePath` folder.\n * @param packagePath - The folder path to derive the package dependencies from. This is typically the folder\n * containing package.json. If omitted, the default value is the current working directory.\n * @param excludedPaths - An optional array of file path exclusions. If a file should be omitted from the list\n * of dependencies, use this to exclude it.\n * @returns the package-deps.json file content\n *\n * @public\n */\nexport function getPackageDeps(\n packagePath: string = process.cwd(),\n excludedPaths?: string[],\n gitPath?: string\n): Map<string, string> {\n const gitLsOutput: string = gitLsTree(packagePath, gitPath);\n\n // Add all the checked in hashes\n const result: Map<string, string> = parseGitLsTree(gitLsOutput);\n\n // Remove excluded paths\n if (excludedPaths) {\n for (const excludedPath of excludedPaths) {\n result.delete(excludedPath);\n }\n }\n\n // Update the checked in hashes with the current repo status\n const gitStatusOutput: string = gitStatus(packagePath, gitPath);\n const currentlyChangedFiles: Map<string, string> = parseGitStatus(gitStatusOutput, packagePath);\n const filesToHash: string[] = [];\n const excludedPathSet: Set<string> = new Set<string>(excludedPaths);\n for (const [filename, changeType] of currentlyChangedFiles) {\n // See comments inside parseGitStatus() for more information\n if (changeType === 'D' || (changeType.length === 2 && changeType.charAt(1) === 'D')) {\n result.delete(filename);\n } else {\n if (!excludedPathSet.has(filename)) {\n filesToHash.push(filename);\n }\n }\n }\n\n const currentlyChangedFileHashes: Map<string, string> = getGitHashForFiles(\n filesToHash,\n packagePath,\n gitPath\n );\n for (const [filename, hash] of currentlyChangedFileHashes) {\n result.set(filename, hash);\n }\n\n return result;\n}\n"]}
@@ -0,0 +1,444 @@
1
+ // Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the MIT license.
2
+ // See LICENSE in the project root for license information.
3
+ import { once } from 'node:events';
4
+ import { Readable, pipeline } from 'node:stream';
5
+ import { Executable } from '@rushstack/node-core-library/lib/Executable';
6
+ import { FileSystem } from '@rushstack/node-core-library/lib/FileSystem';
7
+ const MINIMUM_GIT_VERSION = {
8
+ major: 2,
9
+ minor: 35,
10
+ patch: 0
11
+ };
12
+ const STANDARD_GIT_OPTIONS = [
13
+ // Don't request any optional file locks
14
+ '--no-optional-locks',
15
+ // Ensure that commands don't run automatic maintenance, since performance of the command itself is paramount
16
+ '-c',
17
+ 'maintenance.auto=false'
18
+ ];
19
+ const OBJECTMODE_SUBMODULE = '160000';
20
+ const OBJECTMODE_SYMLINK = '120000';
21
+ const OBJECTMODE_FILE_NONEXECUTABLE = '100644';
22
+ const OBJECTMODE_FILE_EXECUTABLE = '100755';
23
+ // Note that `type` is a stub that is being ignored by the parser in favor of using `mode` to infer, since `%(objecttype)` requires git 2.51.0+
24
+ // e.g. 10644 blob <hash>\t<path>
25
+ const GIT_LSTREE_FORMAT = '%(objectmode) type %(objectname)%x09%(path)';
26
+ /**
27
+ * Parses the output of the "git ls-tree -r -z" command or of other commands that have been coerced to match its format.
28
+ * @internal
29
+ */
30
+ export function parseGitLsTree(output) {
31
+ const files = new Map();
32
+ const symlinks = new Map();
33
+ const submodules = new Map();
34
+ // Parse the output
35
+ // With the -z modifier, paths are delimited by nulls
36
+ // A line looks like:
37
+ // <mode> <type> <newhash>\t<path>\0
38
+ // 100644 blob a300ccb0b36bd2c85ef18e3c619a2c747f95959e\ttools/prettier-git/prettier-git.js\0
39
+ let last = 0;
40
+ let index = output.indexOf('\0', last);
41
+ while (index >= 0) {
42
+ const item = output.slice(last, index);
43
+ const tabIndex = item.indexOf('\t');
44
+ const filePath = item.slice(tabIndex + 1);
45
+ // The newHash will be all zeros if the file is deleted, or a hash if it exists
46
+ const hash = item.slice(tabIndex - 40, tabIndex);
47
+ const mode = item.slice(0, item.indexOf(' '));
48
+ switch (mode) {
49
+ case OBJECTMODE_SUBMODULE: {
50
+ // This is a submodule
51
+ submodules.set(filePath, hash);
52
+ break;
53
+ }
54
+ case OBJECTMODE_SYMLINK: {
55
+ // This is a symbolic link
56
+ symlinks.set(filePath, hash);
57
+ break;
58
+ }
59
+ case OBJECTMODE_FILE_NONEXECUTABLE:
60
+ case OBJECTMODE_FILE_EXECUTABLE:
61
+ default: {
62
+ files.set(filePath, hash);
63
+ break;
64
+ }
65
+ }
66
+ last = index + 1;
67
+ index = output.indexOf('\0', last);
68
+ }
69
+ return {
70
+ files,
71
+ symlinks,
72
+ submodules
73
+ };
74
+ }
75
+ /**
76
+ * Parses the output of `git hash-object`
77
+ * yields [filePath, hash] pairs.
78
+ * @internal
79
+ */
80
+ export function* parseGitHashObject(output, filePaths) {
81
+ const expected = filePaths.length;
82
+ if (expected === 0) {
83
+ return;
84
+ }
85
+ output = output.trim();
86
+ let last = 0;
87
+ let i = 0;
88
+ let index = output.indexOf('\n', last);
89
+ for (; i < expected && index > 0; i++) {
90
+ const hash = output.slice(last, index);
91
+ yield [filePaths[i], hash];
92
+ last = index + 1;
93
+ index = output.indexOf('\n', last);
94
+ }
95
+ // Handle last line. Will be non-empty to due trim() call.
96
+ if (index < 0) {
97
+ const hash = output.slice(last);
98
+ yield [filePaths[i], hash];
99
+ i++;
100
+ }
101
+ if (i !== expected) {
102
+ throw new Error(`Expected ${expected} hashes from "git hash-object" but received ${i}`);
103
+ }
104
+ }
105
+ /**
106
+ * Parses the output of `git diff-index --color=never --no-renames --no-commit-id -z <REVISION> --
107
+ * Returns a map of file path to diff
108
+ * @internal
109
+ */
110
+ export function parseGitDiffIndex(output) {
111
+ const result = new Map();
112
+ // Parse the output
113
+ // With the -z modifier, paths are delimited by nulls
114
+ // A line looks like:
115
+ // :<oldmode> <newmode> <oldhash> <newhash> <status>\0<path>\0
116
+ // :100644 100644 a300ccb0b36bd2c85ef18e3c619a2c747f95959e 0000000000000000000000000000000000000000 M\0tools/prettier-git/prettier-git.js\0
117
+ let last = 0;
118
+ let index = output.indexOf('\0', last);
119
+ while (index >= 0) {
120
+ const header = output.slice(last, index);
121
+ const status = header.slice(-1);
122
+ last = index + 1;
123
+ index = output.indexOf('\0', last);
124
+ const filePath = output.slice(last, index);
125
+ // We passed --no-renames above, so a rename will be a delete of the old location and an add at the new.
126
+ // The newHash will be all zeros if the file is deleted, or a hash if it exists
127
+ const mode = header.slice(8, 14);
128
+ const oldhash = header.slice(-83, -43);
129
+ const newhash = header.slice(-42, -2);
130
+ result.set(filePath, {
131
+ mode,
132
+ oldhash,
133
+ newhash,
134
+ status
135
+ });
136
+ last = index + 1;
137
+ index = output.indexOf('\0', last);
138
+ }
139
+ return result;
140
+ }
141
+ /**
142
+ * Parses the output of `git status -z -u` to extract the set of files that have changed since HEAD.
143
+ *
144
+ * @param output - The raw output from Git
145
+ * @returns a map of file path to if it exists
146
+ * @internal
147
+ */
148
+ export function parseGitStatus(output) {
149
+ const result = new Map();
150
+ // Parse the output
151
+ // With the -z modifier, paths are delimited by nulls
152
+ // A line looks like:
153
+ // XY <path>\0
154
+ // M tools/prettier-git/prettier-git.js\0
155
+ let startOfLine = 0;
156
+ let eolIndex = output.indexOf('\0', startOfLine);
157
+ while (eolIndex >= 0) {
158
+ // We passed --no-renames above, so a rename will be a delete of the old location and an add at the new.
159
+ // charAt(startOfLine) is the index status, charAt(startOfLine + 1) is the working tree status
160
+ const workingTreeStatus = output.charAt(startOfLine + 1);
161
+ // Deleted in working tree, or not modified in working tree and deleted in index
162
+ const deleted = workingTreeStatus === 'D' || (workingTreeStatus === ' ' && output.charAt(startOfLine) === 'D');
163
+ const filePath = output.slice(startOfLine + 3, eolIndex);
164
+ result.set(filePath, !deleted);
165
+ startOfLine = eolIndex + 1;
166
+ eolIndex = output.indexOf('\0', startOfLine);
167
+ }
168
+ return result;
169
+ }
170
+ const repoRootCache = new Map();
171
+ /**
172
+ * Finds the root of the current Git repository
173
+ *
174
+ * @param currentWorkingDirectory - The working directory for which to locate the repository
175
+ * @param gitPath - The path to the Git executable
176
+ *
177
+ * @returns The full path to the root directory of the Git repository
178
+ * @beta
179
+ */
180
+ export function getRepoRoot(currentWorkingDirectory, gitPath) {
181
+ let cachedResult = repoRootCache.get(currentWorkingDirectory);
182
+ if (!cachedResult) {
183
+ const result = Executable.spawnSync(gitPath || 'git', ['--no-optional-locks', 'rev-parse', '--show-toplevel'], {
184
+ currentWorkingDirectory
185
+ });
186
+ if (result.status !== 0) {
187
+ ensureGitMinimumVersion(gitPath);
188
+ throw new Error(`git rev-parse exited with status ${result.status}: ${result.stderr}`);
189
+ }
190
+ cachedResult = result.stdout.trim();
191
+ repoRootCache.set(currentWorkingDirectory, cachedResult);
192
+ // To ensure that calling getRepoRoot on the result is a no-op.
193
+ repoRootCache.set(cachedResult, cachedResult);
194
+ }
195
+ return cachedResult;
196
+ }
197
+ /**
198
+ * Helper function for async process invocation with optional stdin support.
199
+ * @param gitPath - Path to the Git executable
200
+ * @param args - The process arguments
201
+ * @param currentWorkingDirectory - The working directory. Should be the repository root.
202
+ * @param stdin - An optional Readable stream to use as stdin to the process.
203
+ */
204
+ async function spawnGitAsync(gitPath, args, currentWorkingDirectory, stdin) {
205
+ const spawnOptions = {
206
+ currentWorkingDirectory,
207
+ stdio: ['pipe', 'pipe', 'pipe']
208
+ };
209
+ let stdout = '';
210
+ let stderr = '';
211
+ const proc = Executable.spawn(gitPath || 'git', args, spawnOptions);
212
+ proc.stdout.setEncoding('utf-8');
213
+ proc.stderr.setEncoding('utf-8');
214
+ proc.stdout.on('data', (chunk) => {
215
+ stdout += chunk.toString();
216
+ });
217
+ proc.stderr.on('data', (chunk) => {
218
+ stderr += chunk.toString();
219
+ });
220
+ if (stdin) {
221
+ /**
222
+ * For `git hash-object` data is piped in asynchronously. In the event that one of the
223
+ * passed filenames cannot be hashed, subsequent writes to `proc.stdin` will error.
224
+ * Silence this error since it will be handled by the non-zero exit code of the process.
225
+ */
226
+ pipeline(stdin, proc.stdin, (err) => { });
227
+ }
228
+ const [status] = await once(proc, 'close');
229
+ if (status !== 0) {
230
+ ensureGitMinimumVersion(gitPath);
231
+ throw new Error(`git ${args[0]} exited with code ${status}:\n${stderr}`);
232
+ }
233
+ return stdout;
234
+ }
235
+ function isIterable(value) {
236
+ return Symbol.iterator in value;
237
+ }
238
+ /**
239
+ * Uses `git hash-object` to hash the provided files. Unlike `getGitHashForFiles`, this API is asynchronous, and also allows for
240
+ * the input file paths to be specified as an async iterable.
241
+ *
242
+ * @param rootDirectory - The root directory to which paths are specified relative. Must be the root of the Git repository.
243
+ * @param filesToHash - The file paths to hash using `git hash-object`
244
+ * @param gitPath - The path to the Git executable
245
+ * @returns An iterable of [filePath, hash] pairs
246
+ *
247
+ * @remarks
248
+ * The input file paths must be specified relative to the Git repository root, or else be absolute paths.
249
+ * @beta
250
+ */
251
+ export async function hashFilesAsync(rootDirectory, filesToHash, gitPath) {
252
+ const hashPaths = [];
253
+ const input = Readable.from(isIterable(filesToHash)
254
+ ? (function* () {
255
+ for (const file of filesToHash) {
256
+ hashPaths.push(file);
257
+ yield `${file}\n`;
258
+ }
259
+ })()
260
+ : (async function* () {
261
+ for await (const file of filesToHash) {
262
+ hashPaths.push(file);
263
+ yield `${file}\n`;
264
+ }
265
+ })(), {
266
+ encoding: 'utf-8',
267
+ objectMode: false,
268
+ autoDestroy: true
269
+ });
270
+ const hashObjectResult = await spawnGitAsync(gitPath, STANDARD_GIT_OPTIONS.concat(['hash-object', '--stdin-paths']), rootDirectory, input);
271
+ return parseGitHashObject(hashObjectResult, hashPaths);
272
+ }
273
+ /**
274
+ * Gets the object hashes for all files in the Git repo, combining the current commit with working tree state.
275
+ * Uses async operations and runs all primary Git calls in parallel.
276
+ * @param rootDirectory - The root directory of the Git repository
277
+ * @param additionalRelativePathsToHash - Root-relative file paths to have Git hash and include in the results
278
+ * @param gitPath - The path to the Git executable
279
+ * @beta
280
+ */
281
+ export async function getRepoStateAsync(rootDirectory, additionalRelativePathsToHash, gitPath, filterPath) {
282
+ const { files } = await getDetailedRepoStateAsync(rootDirectory, additionalRelativePathsToHash, gitPath, filterPath);
283
+ return files;
284
+ }
285
+ /**
286
+ * Gets the object hashes for all files in the Git repo, combining the current commit with working tree state.
287
+ * Uses async operations and runs all primary Git calls in parallel.
288
+ * @param rootDirectory - The root directory of the Git repository
289
+ * @param additionalRelativePathsToHash - Root-relative file paths to have Git hash and include in the results
290
+ * @param gitPath - The path to the Git executable
291
+ * @beta
292
+ */
293
+ export async function getDetailedRepoStateAsync(rootDirectory, additionalRelativePathsToHash, gitPath, filterPath) {
294
+ const statePromise = spawnGitAsync(gitPath, STANDARD_GIT_OPTIONS.concat([
295
+ 'ls-files',
296
+ // Read from the index only
297
+ '--cached',
298
+ // Use NUL as the separator
299
+ '-z',
300
+ // Specify the full path to files relative to the root
301
+ '--full-name',
302
+ // Match the format of "git ls-tree". The %(objecttype) placeholder requires git 2.51.0+, so not using yet.
303
+ `--format=${GIT_LSTREE_FORMAT}`,
304
+ '--',
305
+ ...(filterPath !== null && filterPath !== void 0 ? filterPath : [])
306
+ ]), rootDirectory).then(parseGitLsTree);
307
+ const locallyModifiedPromise = spawnGitAsync(gitPath, STANDARD_GIT_OPTIONS.concat([
308
+ 'status',
309
+ // Use NUL as the separator
310
+ '-z',
311
+ // Include untracked files
312
+ '-u',
313
+ // Disable rename detection so that renames show up as add + delete
314
+ '--no-renames',
315
+ // Don't process submodules with this command; they'll be handled individually
316
+ '--ignore-submodules',
317
+ // Don't compare against the remote
318
+ '--no-ahead-behind',
319
+ '--',
320
+ ...(filterPath !== null && filterPath !== void 0 ? filterPath : [])
321
+ ]), rootDirectory).then(parseGitStatus);
322
+ async function* getFilesToHash() {
323
+ if (additionalRelativePathsToHash) {
324
+ for (const file of additionalRelativePathsToHash) {
325
+ yield file;
326
+ }
327
+ }
328
+ const [{ files, symlinks }, locallyModified] = await Promise.all([statePromise, locallyModifiedPromise]);
329
+ for (const [filePath, exists] of locallyModified) {
330
+ if (exists && !symlinks.has(filePath)) {
331
+ yield filePath;
332
+ }
333
+ else {
334
+ files.delete(filePath);
335
+ symlinks.delete(filePath);
336
+ }
337
+ }
338
+ }
339
+ const hashObjectPromise = hashFilesAsync(rootDirectory, getFilesToHash(), gitPath);
340
+ const [{ files, symlinks, submodules }, locallyModifiedFiles] = await Promise.all([
341
+ statePromise,
342
+ locallyModifiedPromise
343
+ ]);
344
+ // The result of "git hash-object" will be a list of file hashes delimited by newlines
345
+ for (const [filePath, hash] of await hashObjectPromise) {
346
+ files.set(filePath, hash);
347
+ }
348
+ // Existence check for the .gitmodules file
349
+ const hasSubmodules = submodules.size > 0 && FileSystem.exists(`${rootDirectory}/.gitmodules`);
350
+ if (hasSubmodules) {
351
+ // Submodules are not the normal critical path. Accept serial performance rather than investing in complexity.
352
+ // Can revisit if submodules become more commonly used.
353
+ for (const submodulePath of submodules.keys()) {
354
+ const submoduleState = await getRepoStateAsync(`${rootDirectory}/${submodulePath}`, [], gitPath);
355
+ for (const [filePath, hash] of submoduleState) {
356
+ files.set(`${submodulePath}/${filePath}`, hash);
357
+ }
358
+ }
359
+ }
360
+ return {
361
+ hasSubmodules,
362
+ hasUncommittedChanges: locallyModifiedFiles.size > 0,
363
+ files,
364
+ symlinks
365
+ };
366
+ }
367
+ /**
368
+ * Find all changed files tracked by Git, their current hashes, and the nature of the change. Only useful if all changes are staged or committed.
369
+ * @param currentWorkingDirectory - The working directory. Only used to find the repository root.
370
+ * @param revision - The Git revision specifier to detect changes relative to. Defaults to HEAD (i.e. will compare staged vs. committed)
371
+ * If comparing against a different branch, call `git merge-base` first to find the target commit.
372
+ * @param gitPath - The path to the Git executable
373
+ * @returns A map from the Git file path to the corresponding file change metadata
374
+ * @beta
375
+ */
376
+ export function getRepoChanges(currentWorkingDirectory, revision = 'HEAD', gitPath) {
377
+ const rootDirectory = getRepoRoot(currentWorkingDirectory, gitPath);
378
+ const result = Executable.spawnSync(gitPath || 'git', STANDARD_GIT_OPTIONS.concat([
379
+ 'diff-index',
380
+ '--color=never',
381
+ '--no-renames',
382
+ '--no-commit-id',
383
+ '--cached',
384
+ '-z',
385
+ revision,
386
+ '--'
387
+ ]), {
388
+ currentWorkingDirectory: rootDirectory
389
+ });
390
+ if (result.status !== 0) {
391
+ ensureGitMinimumVersion(gitPath);
392
+ throw new Error(`git diff-index exited with status ${result.status}: ${result.stderr}`);
393
+ }
394
+ const changes = parseGitDiffIndex(result.stdout);
395
+ return changes;
396
+ }
397
+ /**
398
+ * Checks the git version and throws an error if it is less than the minimum required version.
399
+ *
400
+ * @public
401
+ */
402
+ export function ensureGitMinimumVersion(gitPath) {
403
+ const gitVersion = getGitVersion(gitPath);
404
+ if (gitVersion.major < MINIMUM_GIT_VERSION.major ||
405
+ (gitVersion.major === MINIMUM_GIT_VERSION.major && gitVersion.minor < MINIMUM_GIT_VERSION.minor) ||
406
+ (gitVersion.major === MINIMUM_GIT_VERSION.major &&
407
+ gitVersion.minor === MINIMUM_GIT_VERSION.minor &&
408
+ gitVersion.patch < MINIMUM_GIT_VERSION.patch)) {
409
+ throw new Error(`The minimum Git version required is ` +
410
+ `${MINIMUM_GIT_VERSION.major}.${MINIMUM_GIT_VERSION.minor}.${MINIMUM_GIT_VERSION.patch}. ` +
411
+ `Your version is ${gitVersion.major}.${gitVersion.minor}.${gitVersion.patch}.`);
412
+ }
413
+ }
414
+ function getGitVersion(gitPath) {
415
+ const result = Executable.spawnSync(gitPath || 'git', STANDARD_GIT_OPTIONS.concat(['version']));
416
+ if (result.status !== 0) {
417
+ throw new Error(`While validating the Git installation, the "git version" command failed with ` +
418
+ `status ${result.status}: ${result.stderr}`);
419
+ }
420
+ return parseGitVersion(result.stdout);
421
+ }
422
+ export function parseGitVersion(gitVersionOutput) {
423
+ // This regexp matches output of "git version" that looks like `git version <number>.<number>.<number>(+whatever)`
424
+ // Examples:
425
+ // - git version 1.2.3
426
+ // - git version 1.2.3.4.5
427
+ // - git version 1.2.3windows.1
428
+ // - git version 1.2.3.windows.1
429
+ const versionRegex = /^git version (\d+)\.(\d+)\.(\d+)/;
430
+ const match = versionRegex.exec(gitVersionOutput);
431
+ if (!match) {
432
+ throw new Error(`While validating the Git installation, the "git version" command produced ` +
433
+ `unexpected output: "${gitVersionOutput}"`);
434
+ }
435
+ const major = parseInt(match[1], 10);
436
+ const minor = parseInt(match[2], 10);
437
+ const patch = parseInt(match[3], 10);
438
+ return {
439
+ major,
440
+ minor,
441
+ patch
442
+ };
443
+ }
444
+ //# sourceMappingURL=getRepoState.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"getRepoState.js","sourceRoot":"","sources":["../src/getRepoState.ts"],"names":[],"mappings":"AAAA,4FAA4F;AAC5F,2DAA2D;AAG3D,OAAO,EAAE,IAAI,EAAE,MAAM,aAAa,CAAC;AACnC,OAAO,EAAE,QAAQ,EAAE,QAAQ,EAAE,MAAM,aAAa,CAAC;AAEjD,OAAO,EAAE,UAAU,EAAgC,MAAM,6CAA6C,CAAC;AACvG,OAAO,EAAE,UAAU,EAAE,MAAM,6CAA6C,CAAC;AAQzE,MAAM,mBAAmB,GAAgB;IACvC,KAAK,EAAE,CAAC;IACR,KAAK,EAAE,EAAE;IACT,KAAK,EAAE,CAAC;CACT,CAAC;AAEF,MAAM,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AC,CAAC,EAAE,EAAE,CAAC,CAAC;IAC7C,MAAM,KAAK,GAAW,QAAQ,CAAC,KAAK,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC;IAE7C,OAAO;QACL,KAAK;QACL,KAAK;QACL,KAAK;KACN,CAAC;AACJ,CAAC","sourcesContent":["// Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the MIT license.\n// See LICENSE in the project root for license information.\n\nimport type * as child_process from 'node:child_process';\nimport { once } from 'node:events';\nimport { Readable, pipeline } from 'node:stream';\n\nimport { Executable, type IExecutableSpawnOptions } from '@rushstack/node-core-library/lib/Executable';\nimport { FileSystem } from '@rushstack/node-core-library/lib/FileSystem';\n\nexport interface IGitVersion {\n major: number;\n minor: number;\n patch: number;\n}\n\nconst MINIMUM_GIT_VERSION: IGitVersion = {\n major: 2,\n minor: 35,\n patch: 0\n};\n\nconst STANDARD_GIT_OPTIONS: readonly string[] = [\n // Don't request any optional file locks\n '--no-optional-locks',\n // Ensure that commands don't run automatic maintenance, since performance of the command itself is paramount\n '-c',\n 'maintenance.auto=false'\n];\n\nconst OBJECTMODE_SUBMODULE: '160000' = '160000';\nconst OBJECTMODE_SYMLINK: '120000' = '120000';\nconst OBJECTMODE_FILE_NONEXECUTABLE: '100644' = '100644';\nconst OBJECTMODE_FILE_EXECUTABLE: '100755' = '100755';\n\n// Note that `type` is a stub that is being ignored by the parser in favor of using `mode` to infer, since `%(objecttype)` requires git 2.51.0+\n// e.g. 10644 blob <hash>\\t<path>\nconst GIT_LSTREE_FORMAT: string = '%(objectmode) type %(objectname)%x09%(path)';\n\ninterface IGitTreeState {\n files: Map<string, string>; // type \"blob\"\n symlinks: Map<string, string>; // type \"link\"\n submodules: Map<string, string>; // type \"commit\"\n}\n\n/**\n * Parses the output of the \"git ls-tree -r -z\" command or of other commands that have been coerced to match its format.\n * @internal\n */\nexport function parseGitLsTree(output: string): IGitTreeState {\n const files: Map<string, string> = new Map();\n const symlinks: Map<string, string> = new Map();\n const submodules: Map<string, string> = new Map();\n\n // Parse the output\n // With the -z modifier, paths are delimited by nulls\n // A line looks like:\n // <mode> <type> <newhash>\\t<path>\\0\n // 100644 blob a300ccb0b36bd2c85ef18e3c619a2c747f95959e\\ttools/prettier-git/prettier-git.js\\0\n\n let last: number = 0;\n let index: number = output.indexOf('\\0', last);\n while (index >= 0) {\n const item: string = output.slice(last, index);\n\n const tabIndex: number = item.indexOf('\\t');\n const filePath: string = item.slice(tabIndex + 1);\n\n // The newHash will be all zeros if the file is deleted, or a hash if it exists\n const hash: string = item.slice(tabIndex - 40, tabIndex);\n\n const mode: string = item.slice(0, item.indexOf(' '));\n\n switch (mode) {\n case OBJECTMODE_SUBMODULE: {\n // This is a submodule\n submodules.set(filePath, hash);\n break;\n }\n case OBJECTMODE_SYMLINK: {\n // This is a symbolic link\n symlinks.set(filePath, hash);\n break;\n }\n case OBJECTMODE_FILE_NONEXECUTABLE:\n case OBJECTMODE_FILE_EXECUTABLE:\n default: {\n files.set(filePath, hash);\n break;\n }\n }\n\n last = index + 1;\n index = output.indexOf('\\0', last);\n }\n\n return {\n files,\n symlinks,\n submodules\n };\n}\n\n/**\n * Parses the output of `git hash-object`\n * yields [filePath, hash] pairs.\n * @internal\n */\nexport function* parseGitHashObject(\n output: string,\n filePaths: ReadonlyArray<string>\n): IterableIterator<[string, string]> {\n const expected: number = filePaths.length;\n if (expected === 0) {\n return;\n }\n\n output = output.trim();\n\n let last: number = 0;\n let i: number = 0;\n let index: number = output.indexOf('\\n', last);\n for (; i < expected && index > 0; i++) {\n const hash: string = output.slice(last, index);\n yield [filePaths[i], hash];\n last = index + 1;\n index = output.indexOf('\\n', last);\n }\n\n // Handle last line. Will be non-empty to due trim() call.\n if (index < 0) {\n const hash: string = output.slice(last);\n yield [filePaths[i], hash];\n i++;\n }\n\n if (i !== expected) {\n throw new Error(`Expected ${expected} hashes from \"git hash-object\" but received ${i}`);\n }\n}\n\n/**\n * Information about the changes to a file.\n * @beta\n */\nexport interface IFileDiffStatus {\n mode: string;\n oldhash: string;\n newhash: string;\n status: 'A' | 'D' | 'M';\n}\n\n/**\n * Parses the output of `git diff-index --color=never --no-renames --no-commit-id -z <REVISION> --\n * Returns a map of file path to diff\n * @internal\n */\nexport function parseGitDiffIndex(output: string): Map<string, IFileDiffStatus> {\n const result: Map<string, IFileDiffStatus> = new Map();\n\n // Parse the output\n // With the -z modifier, paths are delimited by nulls\n // A line looks like:\n // :<oldmode> <newmode> <oldhash> <newhash> <status>\\0<path>\\0\n // :100644 100644 a300ccb0b36bd2c85ef18e3c619a2c747f95959e 0000000000000000000000000000000000000000 M\\0tools/prettier-git/prettier-git.js\\0\n\n let last: number = 0;\n let index: number = output.indexOf('\\0', last);\n while (index >= 0) {\n const header: string = output.slice(last, index);\n const status: IFileDiffStatus['status'] = header.slice(-1) as IFileDiffStatus['status'];\n\n last = index + 1;\n index = output.indexOf('\\0', last);\n const filePath: string = output.slice(last, index);\n\n // We passed --no-renames above, so a rename will be a delete of the old location and an add at the new.\n // The newHash will be all zeros if the file is deleted, or a hash if it exists\n const mode: string = header.slice(8, 14);\n const oldhash: string = header.slice(-83, -43);\n const newhash: string = header.slice(-42, -2);\n result.set(filePath, {\n mode,\n oldhash,\n newhash,\n status\n });\n\n last = index + 1;\n index = output.indexOf('\\0', last);\n }\n\n return result;\n}\n\n/**\n * Parses the output of `git status -z -u` to extract the set of files that have changed since HEAD.\n *\n * @param output - The raw output from Git\n * @returns a map of file path to if it exists\n * @internal\n */\nexport function parseGitStatus(output: string): Map<string, boolean> {\n const result: Map<string, boolean> = new Map();\n\n // Parse the output\n // With the -z modifier, paths are delimited by nulls\n // A line looks like:\n // XY <path>\\0\n // M tools/prettier-git/prettier-git.js\\0\n\n let startOfLine: number = 0;\n let eolIndex: number = output.indexOf('\\0', startOfLine);\n while (eolIndex >= 0) {\n // We passed --no-renames above, so a rename will be a delete of the old location and an add at the new.\n // charAt(startOfLine) is the index status, charAt(startOfLine + 1) is the working tree status\n const workingTreeStatus: string = output.charAt(startOfLine + 1);\n // Deleted in working tree, or not modified in working tree and deleted in index\n const deleted: boolean =\n workingTreeStatus === 'D' || (workingTreeStatus === ' ' && output.charAt(startOfLine) === 'D');\n\n const filePath: string = output.slice(startOfLine + 3, eolIndex);\n result.set(filePath, !deleted);\n\n startOfLine = eolIndex + 1;\n eolIndex = output.indexOf('\\0', startOfLine);\n }\n\n return result;\n}\n\nconst repoRootCache: Map<string, string> = new Map();\n\n/**\n * Finds the root of the current Git repository\n *\n * @param currentWorkingDirectory - The working directory for which to locate the repository\n * @param gitPath - The path to the Git executable\n *\n * @returns The full path to the root directory of the Git repository\n * @beta\n */\nexport function getRepoRoot(currentWorkingDirectory: string, gitPath?: string): string {\n let cachedResult: string | undefined = repoRootCache.get(currentWorkingDirectory);\n if (!cachedResult) {\n const result: child_process.SpawnSyncReturns<string> = Executable.spawnSync(\n gitPath || 'git',\n ['--no-optional-locks', 'rev-parse', '--show-toplevel'],\n {\n currentWorkingDirectory\n }\n );\n\n if (result.status !== 0) {\n ensureGitMinimumVersion(gitPath);\n\n throw new Error(`git rev-parse exited with status ${result.status}: ${result.stderr}`);\n }\n\n cachedResult = result.stdout.trim();\n\n repoRootCache.set(currentWorkingDirectory, cachedResult);\n // To ensure that calling getRepoRoot on the result is a no-op.\n repoRootCache.set(cachedResult, cachedResult);\n }\n\n return cachedResult;\n}\n\n/**\n * Helper function for async process invocation with optional stdin support.\n * @param gitPath - Path to the Git executable\n * @param args - The process arguments\n * @param currentWorkingDirectory - The working directory. Should be the repository root.\n * @param stdin - An optional Readable stream to use as stdin to the process.\n */\nasync function spawnGitAsync(\n gitPath: string | undefined,\n args: string[],\n currentWorkingDirectory: string,\n stdin?: Readable\n): Promise<string> {\n const spawnOptions: IExecutableSpawnOptions = {\n currentWorkingDirectory,\n stdio: ['pipe', 'pipe', 'pipe']\n };\n\n let stdout: string = '';\n let stderr: string = '';\n\n const proc: child_process.ChildProcess = Executable.spawn(gitPath || 'git', args, spawnOptions);\n proc.stdout!.setEncoding('utf-8');\n proc.stderr!.setEncoding('utf-8');\n\n proc.stdout!.on('data', (chunk: string) => {\n stdout += chunk.toString();\n });\n proc.stderr!.on('data', (chunk: string) => {\n stderr += chunk.toString();\n });\n\n if (stdin) {\n /**\n * For `git hash-object` data is piped in asynchronously. In the event that one of the\n * passed filenames cannot be hashed, subsequent writes to `proc.stdin` will error.\n * Silence this error since it will be handled by the non-zero exit code of the process.\n */\n pipeline(stdin, proc.stdin!, (err) => {});\n }\n\n const [status] = await once(proc, 'close');\n if (status !== 0) {\n ensureGitMinimumVersion(gitPath);\n\n throw new Error(`git ${args[0]} exited with code ${status}:\\n${stderr}`);\n }\n\n return stdout;\n}\n\nfunction isIterable<T>(value: Iterable<T> | AsyncIterable<T>): value is Iterable<T> {\n return Symbol.iterator in value;\n}\n\n/**\n * Uses `git hash-object` to hash the provided files. Unlike `getGitHashForFiles`, this API is asynchronous, and also allows for\n * the input file paths to be specified as an async iterable.\n *\n * @param rootDirectory - The root directory to which paths are specified relative. Must be the root of the Git repository.\n * @param filesToHash - The file paths to hash using `git hash-object`\n * @param gitPath - The path to the Git executable\n * @returns An iterable of [filePath, hash] pairs\n *\n * @remarks\n * The input file paths must be specified relative to the Git repository root, or else be absolute paths.\n * @beta\n */\nexport async function hashFilesAsync(\n rootDirectory: string,\n filesToHash: Iterable<string> | AsyncIterable<string>,\n gitPath?: string\n): Promise<Iterable<[string, string]>> {\n const hashPaths: string[] = [];\n\n const input: Readable = Readable.from(\n isIterable(filesToHash)\n ? (function* (): IterableIterator<string> {\n for (const file of filesToHash) {\n hashPaths.push(file);\n yield `${file}\\n`;\n }\n })()\n : (async function* (): AsyncIterableIterator<string> {\n for await (const file of filesToHash) {\n hashPaths.push(file);\n yield `${file}\\n`;\n }\n })(),\n {\n encoding: 'utf-8',\n objectMode: false,\n autoDestroy: true\n }\n );\n\n const hashObjectResult: string = await spawnGitAsync(\n gitPath,\n STANDARD_GIT_OPTIONS.concat(['hash-object', '--stdin-paths']),\n rootDirectory,\n input\n );\n\n return parseGitHashObject(hashObjectResult, hashPaths);\n}\n\n/**\n * Gets the object hashes for all files in the Git repo, combining the current commit with working tree state.\n * Uses async operations and runs all primary Git calls in parallel.\n * @param rootDirectory - The root directory of the Git repository\n * @param additionalRelativePathsToHash - Root-relative file paths to have Git hash and include in the results\n * @param gitPath - The path to the Git executable\n * @beta\n */\nexport async function getRepoStateAsync(\n rootDirectory: string,\n additionalRelativePathsToHash?: string[],\n gitPath?: string,\n filterPath?: string[]\n): Promise<Map<string, string>> {\n const { files } = await getDetailedRepoStateAsync(\n rootDirectory,\n additionalRelativePathsToHash,\n gitPath,\n filterPath\n );\n\n return files;\n}\n\n/**\n * Information about the detailed state of the Git repository.\n * @beta\n */\nexport interface IDetailedRepoState {\n /**\n * The Git file hashes for all files in the repository, including uncommitted changes.\n */\n files: Map<string, string>;\n /**\n * The Git file hashes for all symbolic links in the repository, including uncommitted changes.\n */\n symlinks: Map<string, string>;\n /**\n * A boolean indicating whether the repository has submodules.\n */\n hasSubmodules: boolean;\n /**\n * A boolean indicating whether the repository has uncommitted changes.\n */\n hasUncommittedChanges: boolean;\n}\n\n/**\n * Gets the object hashes for all files in the Git repo, combining the current commit with working tree state.\n * Uses async operations and runs all primary Git calls in parallel.\n * @param rootDirectory - The root directory of the Git repository\n * @param additionalRelativePathsToHash - Root-relative file paths to have Git hash and include in the results\n * @param gitPath - The path to the Git executable\n * @beta\n */\nexport async function getDetailedRepoStateAsync(\n rootDirectory: string,\n additionalRelativePathsToHash?: string[],\n gitPath?: string,\n filterPath?: string[]\n): Promise<IDetailedRepoState> {\n const statePromise: Promise<IGitTreeState> = spawnGitAsync(\n gitPath,\n STANDARD_GIT_OPTIONS.concat([\n 'ls-files',\n // Read from the index only\n '--cached',\n // Use NUL as the separator\n '-z',\n // Specify the full path to files relative to the root\n '--full-name',\n // Match the format of \"git ls-tree\". The %(objecttype) placeholder requires git 2.51.0+, so not using yet.\n `--format=${GIT_LSTREE_FORMAT}`,\n '--',\n ...(filterPath ?? [])\n ]),\n rootDirectory\n ).then(parseGitLsTree);\n const locallyModifiedPromise: Promise<Map<string, boolean>> = spawnGitAsync(\n gitPath,\n STANDARD_GIT_OPTIONS.concat([\n 'status',\n // Use NUL as the separator\n '-z',\n // Include untracked files\n '-u',\n // Disable rename detection so that renames show up as add + delete\n '--no-renames',\n // Don't process submodules with this command; they'll be handled individually\n '--ignore-submodules',\n // Don't compare against the remote\n '--no-ahead-behind',\n '--',\n ...(filterPath ?? [])\n ]),\n rootDirectory\n ).then(parseGitStatus);\n\n async function* getFilesToHash(): AsyncIterableIterator<string> {\n if (additionalRelativePathsToHash) {\n for (const file of additionalRelativePathsToHash) {\n yield file;\n }\n }\n\n const [{ files, symlinks }, locallyModified] = await Promise.all([statePromise, locallyModifiedPromise]);\n\n for (const [filePath, exists] of locallyModified) {\n if (exists && !symlinks.has(filePath)) {\n yield filePath;\n } else {\n files.delete(filePath);\n symlinks.delete(filePath);\n }\n }\n }\n\n const hashObjectPromise: Promise<Iterable<[string, string]>> = hashFilesAsync(\n rootDirectory,\n getFilesToHash(),\n gitPath\n );\n\n const [{ files, symlinks, submodules }, locallyModifiedFiles] = await Promise.all([\n statePromise,\n locallyModifiedPromise\n ]);\n\n // The result of \"git hash-object\" will be a list of file hashes delimited by newlines\n for (const [filePath, hash] of await hashObjectPromise) {\n files.set(filePath, hash);\n }\n\n // Existence check for the .gitmodules file\n const hasSubmodules: boolean = submodules.size > 0 && FileSystem.exists(`${rootDirectory}/.gitmodules`);\n\n if (hasSubmodules) {\n // Submodules are not the normal critical path. Accept serial performance rather than investing in complexity.\n // Can revisit if submodules become more commonly used.\n for (const submodulePath of submodules.keys()) {\n const submoduleState: Map<string, string> = await getRepoStateAsync(\n `${rootDirectory}/${submodulePath}`,\n [],\n gitPath\n );\n for (const [filePath, hash] of submoduleState) {\n files.set(`${submodulePath}/${filePath}`, hash);\n }\n }\n }\n\n return {\n hasSubmodules,\n hasUncommittedChanges: locallyModifiedFiles.size > 0,\n files,\n symlinks\n };\n}\n\n/**\n * Find all changed files tracked by Git, their current hashes, and the nature of the change. Only useful if all changes are staged or committed.\n * @param currentWorkingDirectory - The working directory. Only used to find the repository root.\n * @param revision - The Git revision specifier to detect changes relative to. Defaults to HEAD (i.e. will compare staged vs. committed)\n * If comparing against a different branch, call `git merge-base` first to find the target commit.\n * @param gitPath - The path to the Git executable\n * @returns A map from the Git file path to the corresponding file change metadata\n * @beta\n */\nexport function getRepoChanges(\n currentWorkingDirectory: string,\n revision: string = 'HEAD',\n gitPath?: string\n): Map<string, IFileDiffStatus> {\n const rootDirectory: string = getRepoRoot(currentWorkingDirectory, gitPath);\n\n const result: child_process.SpawnSyncReturns<string> = Executable.spawnSync(\n gitPath || 'git',\n STANDARD_GIT_OPTIONS.concat([\n 'diff-index',\n '--color=never',\n '--no-renames',\n '--no-commit-id',\n '--cached',\n '-z',\n revision,\n '--'\n ]),\n {\n currentWorkingDirectory: rootDirectory\n }\n );\n\n if (result.status !== 0) {\n ensureGitMinimumVersion(gitPath);\n\n throw new Error(`git diff-index exited with status ${result.status}: ${result.stderr}`);\n }\n\n const changes: Map<string, IFileDiffStatus> = parseGitDiffIndex(result.stdout);\n\n return changes;\n}\n\n/**\n * Checks the git version and throws an error if it is less than the minimum required version.\n *\n * @public\n */\nexport function ensureGitMinimumVersion(gitPath?: string): void {\n const gitVersion: IGitVersion = getGitVersion(gitPath);\n if (\n gitVersion.major < MINIMUM_GIT_VERSION.major ||\n (gitVersion.major === MINIMUM_GIT_VERSION.major && gitVersion.minor < MINIMUM_GIT_VERSION.minor) ||\n (gitVersion.major === MINIMUM_GIT_VERSION.major &&\n gitVersion.minor === MINIMUM_GIT_VERSION.minor &&\n gitVersion.patch < MINIMUM_GIT_VERSION.patch)\n ) {\n throw new Error(\n `The minimum Git version required is ` +\n `${MINIMUM_GIT_VERSION.major}.${MINIMUM_GIT_VERSION.minor}.${MINIMUM_GIT_VERSION.patch}. ` +\n `Your version is ${gitVersion.major}.${gitVersion.minor}.${gitVersion.patch}.`\n );\n }\n}\n\nfunction getGitVersion(gitPath?: string): IGitVersion {\n const result: child_process.SpawnSyncReturns<string> = Executable.spawnSync(\n gitPath || 'git',\n STANDARD_GIT_OPTIONS.concat(['version'])\n );\n\n if (result.status !== 0) {\n throw new Error(\n `While validating the Git installation, the \"git version\" command failed with ` +\n `status ${result.status}: ${result.stderr}`\n );\n }\n\n return parseGitVersion(result.stdout);\n}\n\nexport function parseGitVersion(gitVersionOutput: string): IGitVersion {\n // This regexp matches output of \"git version\" that looks like `git version <number>.<number>.<number>(+whatever)`\n // Examples:\n // - git version 1.2.3\n // - git version 1.2.3.4.5\n // - git version 1.2.3windows.1\n // - git version 1.2.3.windows.1\n const versionRegex: RegExp = /^git version (\\d+)\\.(\\d+)\\.(\\d+)/;\n const match: RegExpMatchArray | null = versionRegex.exec(gitVersionOutput);\n if (!match) {\n throw new Error(\n `While validating the Git installation, the \"git version\" command produced ` +\n `unexpected output: \"${gitVersionOutput}\"`\n );\n }\n\n const major: number = parseInt(match[1], 10);\n const minor: number = parseInt(match[2], 10);\n const patch: number = parseInt(match[3], 10);\n\n return {\n major,\n minor,\n patch\n };\n}\n"]}
@@ -0,0 +1,16 @@
1
+ // Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the MIT license.
2
+ // See LICENSE in the project root for license information.
3
+ /**
4
+ * This package builds a JSON object containing the git hashes of all files used to produce a given NPM package.
5
+ * The {@link https://rushjs.io/ | Rush} tool uses this library to implement incremental build detection.
6
+ *
7
+ * @remarks
8
+ *
9
+ * For more info, please see the package {@link https://www.npmjs.com/package/@rushstack/package-deps-hash
10
+ * | README}.
11
+ *
12
+ * @packageDocumentation
13
+ */
14
+ export { getPackageDeps, getGitHashForFiles } from './getPackageDeps';
15
+ export { getDetailedRepoStateAsync, getRepoChanges, getRepoRoot, getRepoStateAsync, ensureGitMinimumVersion, hashFilesAsync } from './getRepoState';
16
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,4FAA4F;AAC5F,2DAA2D;AAE3D;;;;;;;;;;GAUG;AAEH,OAAO,EAAE,cAAc,EAAE,kBAAkB,EAAE,MAAM,kBAAkB,CAAC;AACtE,OAAO,EAGL,yBAAyB,EACzB,cAAc,EACd,WAAW,EACX,iBAAiB,EACjB,uBAAuB,EACvB,cAAc,EACf,MAAM,gBAAgB,CAAC","sourcesContent":["// Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the MIT license.\n// See LICENSE in the project root for license information.\n\n/**\n * This package builds a JSON object containing the git hashes of all files used to produce a given NPM package.\n * The {@link https://rushjs.io/ | Rush} tool uses this library to implement incremental build detection.\n *\n * @remarks\n *\n * For more info, please see the package {@link https://www.npmjs.com/package/@rushstack/package-deps-hash\n * | README}.\n *\n * @packageDocumentation\n */\n\nexport { getPackageDeps, getGitHashForFiles } from './getPackageDeps';\nexport {\n type IFileDiffStatus,\n type IDetailedRepoState,\n getDetailedRepoStateAsync,\n getRepoChanges,\n getRepoRoot,\n getRepoStateAsync,\n ensureGitMinimumVersion,\n hashFilesAsync\n} from './getRepoState';\n"]}
package/package.json CHANGED
@@ -1,9 +1,30 @@
1
1
  {
2
2
  "name": "@rushstack/package-deps-hash",
3
- "version": "4.6.7",
3
+ "version": "4.7.0",
4
4
  "description": "",
5
- "main": "lib/index.js",
6
- "typings": "dist/package-deps-hash.d.ts",
5
+ "main": "./lib-commonjs/index.js",
6
+ "module": "./lib-esm/index.js",
7
+ "types": "./dist/package-deps-hash.d.ts",
8
+ "exports": {
9
+ ".": {
10
+ "types": "./dist/package-deps-hash.d.ts",
11
+ "import": "./lib-esm/index.js",
12
+ "require": "./lib-commonjs/index.js"
13
+ },
14
+ "./lib/*": {
15
+ "types": "./lib-dts/*.d.ts",
16
+ "import": "./lib-esm/*.js",
17
+ "require": "./lib-commonjs/*.js"
18
+ },
19
+ "./package.json": "./package.json"
20
+ },
21
+ "typesVersions": {
22
+ "*": {
23
+ "lib/*": [
24
+ "lib-dts/*"
25
+ ]
26
+ }
27
+ },
7
28
  "license": "MIT",
8
29
  "repository": {
9
30
  "type": "git",
@@ -12,12 +33,13 @@
12
33
  },
13
34
  "devDependencies": {
14
35
  "eslint": "~9.37.0",
15
- "@rushstack/heft": "1.1.13",
36
+ "@rushstack/heft": "1.2.0",
16
37
  "local-node-rig": "1.0.0"
17
38
  },
18
39
  "dependencies": {
19
- "@rushstack/node-core-library": "5.19.1"
40
+ "@rushstack/node-core-library": "5.20.0"
20
41
  },
42
+ "sideEffects": false,
21
43
  "scripts": {
22
44
  "build": "heft build --clean",
23
45
  "_phase:build": "heft run --only build -- --clean",
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes