@lage-run/hasher 0.2.2 → 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.
Files changed (47) hide show
  1. package/CHANGELOG.json +37 -1
  2. package/CHANGELOG.md +11 -2
  3. package/lib/FileHasher.d.ts +13 -0
  4. package/lib/FileHasher.js +181 -0
  5. package/lib/PackageTree.d.ts +20 -0
  6. package/lib/PackageTree.js +178 -0
  7. package/lib/TargetHasher.d.ts +47 -0
  8. package/lib/TargetHasher.js +218 -0
  9. package/lib/__tests__/TargetHasher.test.js +128 -0
  10. package/lib/__tests__/getPackageDeps.test.js +70 -67
  11. package/lib/__tests__/resolveDependenciesHelper.js +19 -13
  12. package/lib/__tests__/resolveExternalDependencies.test.js +16 -16
  13. package/lib/__tests__/resolveInternalDependencies.test.js +12 -12
  14. package/lib/getPackageDeps.js +25 -15
  15. package/lib/hashStrings.d.ts +1 -0
  16. package/lib/hashStrings.js +28 -0
  17. package/lib/index.d.ts +1 -14
  18. package/lib/index.js +6 -70
  19. package/lib/nameAtVersion.d.ts +1 -0
  20. package/lib/nameAtVersion.js +13 -0
  21. package/lib/resolveExternalDependencies.js +18 -12
  22. package/lib/resolveInternalDependencies.js +8 -4
  23. package/package.json +9 -5
  24. package/lib/__tests__/createPackageHashes.test.js +0 -44
  25. package/lib/__tests__/getRepoDeps.test.d.ts +0 -1
  26. package/lib/__tests__/getRepoDeps.test.js +0 -253
  27. package/lib/__tests__/getRepoState.test.d.ts +0 -1
  28. package/lib/__tests__/getRepoState.test.js +0 -104
  29. package/lib/__tests__/hashOfFiles.test.d.ts +0 -1
  30. package/lib/__tests__/hashOfFiles.test.js +0 -103
  31. package/lib/__tests__/helpers.test.d.ts +0 -1
  32. package/lib/__tests__/helpers.test.js +0 -28
  33. package/lib/__tests__/index.test.d.ts +0 -1
  34. package/lib/__tests__/index.test.js +0 -99
  35. package/lib/createPackageHashes.d.ts +0 -4
  36. package/lib/createPackageHashes.js +0 -48
  37. package/lib/getRepoState.d.ts +0 -76
  38. package/lib/getRepoState.js +0 -256
  39. package/lib/hashOfFiles.d.ts +0 -14
  40. package/lib/hashOfFiles.js +0 -71
  41. package/lib/hashOfPackage.d.ts +0 -9
  42. package/lib/hashOfPackage.js +0 -65
  43. package/lib/helpers.d.ts +0 -3
  44. package/lib/helpers.js +0 -47
  45. package/lib/repoInfo.d.ts +0 -26
  46. package/lib/repoInfo.js +0 -65
  47. /package/lib/__tests__/{createPackageHashes.test.d.ts → TargetHasher.test.d.ts} +0 -0
@@ -1,76 +0,0 @@
1
- export interface IGitVersion {
2
- major: number;
3
- minor: number;
4
- patch: number;
5
- }
6
- /**
7
- * Parses the output of the "git ls-tree -r -z" command
8
- * @internal
9
- */
10
- export declare function parseGitLsTree(output: string): Map<string, string>;
11
- /**
12
- * Information about the changes to a file.
13
- * @beta
14
- */
15
- export interface IFileDiffStatus {
16
- mode: string;
17
- oldhash: string;
18
- newhash: string;
19
- status: "A" | "D" | "M";
20
- }
21
- /**
22
- * Parses the output of `git diff-index --color=never --no-renames --no-commit-id -z <REVISION> --
23
- * Returns a map of file path to diff
24
- * @internal
25
- */
26
- export declare function parseGitDiffIndex(output: string): Map<string, IFileDiffStatus>;
27
- /**
28
- * Parses the output of `git status -z -u` to extract the set of files that have changed since HEAD.
29
- *
30
- * @param output - The raw output from Git
31
- * @returns a map of file path to if it exists
32
- * @internal
33
- */
34
- export declare function parseGitStatus(output: string): Map<string, boolean>;
35
- /**
36
- * Finds the root of the current Git repository
37
- *
38
- * @param cwd - The working directory for which to locate the repository
39
- * @param gitPath - The path to the Git executable
40
- *
41
- * @returns The full path to the root directory of the Git repository
42
- * @beta
43
- */
44
- export declare function getRepoRoot(cwd: string, gitPath?: string): string;
45
- /**
46
- * Augments the state value with modifications that are not in the index.
47
- * @param rootDirectory - The root directory of the Git repository
48
- * @param state - The current map of git path -> object hash. Will be mutated.
49
- * @param gitPath - The path to the Git executable
50
- * @internal
51
- */
52
- export declare function applyWorkingTreeState(rootDirectory: string, state: Map<string, string>, gitPath?: string): void;
53
- /**
54
- * Gets the object hashes for all files in the Git repo, combining the current commit with working tree state.
55
- * @param cwd - The working directory. Only used to find the repository root.
56
- * @param gitPath - The path to the Git executable
57
- * @beta
58
- */
59
- export declare function getRepoState(cwd: string, gitPath?: string): Map<string, string>;
60
- /**
61
- * 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.
62
- * @param cwd - The working directory. Only used to find the repository root.
63
- * @param revision - The Git revision specifier to detect changes relative to. Defaults to HEAD (i.e. will compare staged vs. committed)
64
- * If comparing against a different branch, call `git merge-base` first to find the target commit.
65
- * @param gitPath - The path to the Git executable
66
- * @returns A map from the Git file path to the corresponding file change metadata
67
- * @beta
68
- */
69
- export declare function getRepoChanges(cwd: string, revision?: string, gitPath?: string): Map<string, IFileDiffStatus>;
70
- /**
71
- * Checks the git version and throws an error if it is less than the minimum required version.
72
- *
73
- * @public
74
- */
75
- export declare function ensureGitMinimumVersion(gitPath?: string): void;
76
- export declare function parseGitVersion(gitVersionOutput: string): IGitVersion;
@@ -1,256 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", {
3
- value: true
4
- });
5
- function _export(target, all) {
6
- for(var name in all)Object.defineProperty(target, name, {
7
- enumerable: true,
8
- get: all[name]
9
- });
10
- }
11
- _export(exports, {
12
- parseGitLsTree: ()=>parseGitLsTree,
13
- parseGitDiffIndex: ()=>parseGitDiffIndex,
14
- parseGitStatus: ()=>parseGitStatus,
15
- getRepoRoot: ()=>getRepoRoot,
16
- applyWorkingTreeState: ()=>applyWorkingTreeState,
17
- getRepoState: ()=>getRepoState,
18
- getRepoChanges: ()=>getRepoChanges,
19
- ensureGitMinimumVersion: ()=>ensureGitMinimumVersion,
20
- parseGitVersion: ()=>parseGitVersion
21
- });
22
- const _execa = /*#__PURE__*/ _interopRequireDefault(require("execa"));
23
- function _interopRequireDefault(obj) {
24
- return obj && obj.__esModule ? obj : {
25
- default: obj
26
- };
27
- }
28
- const MINIMUM_GIT_VERSION = {
29
- major: 2,
30
- minor: 20,
31
- patch: 0
32
- };
33
- function parseGitLsTree(output) {
34
- const result = new Map();
35
- // Parse the output
36
- // With the -z modifier, paths are delimited by nulls
37
- // A line looks like:
38
- // <mode> <type> <newhash>\t<path>\0
39
- // 100644 blob a300ccb0b36bd2c85ef18e3c619a2c747f95959e\ttools/prettier-git/prettier-git.js\0
40
- let last = 0;
41
- let index = output.indexOf("\0", last);
42
- while(index >= 0){
43
- const item = output.slice(last, index);
44
- const tabIndex = item.indexOf("\t");
45
- const filePath = item.slice(tabIndex + 1);
46
- // The newHash will be all zeros if the file is deleted, or a hash if it exists
47
- const hash = item.slice(tabIndex - 40, tabIndex);
48
- result.set(filePath, hash);
49
- last = index + 1;
50
- index = output.indexOf("\0", last);
51
- }
52
- return result;
53
- }
54
- function parseGitDiffIndex(output) {
55
- const result = new Map();
56
- // Parse the output
57
- // With the -z modifier, paths are delimited by nulls
58
- // A line looks like:
59
- // :<oldmode> <newmode> <oldhash> <newhash> <status>\0<path>\0
60
- // :100644 100644 a300ccb0b36bd2c85ef18e3c619a2c747f95959e 0000000000000000000000000000000000000000 M\0tools/prettier-git/prettier-git.js\0
61
- let last = 0;
62
- let index = output.indexOf("\0", last);
63
- while(index >= 0){
64
- const header = output.slice(last, index);
65
- const status = header.slice(-1);
66
- last = index + 1;
67
- index = output.indexOf("\0", last);
68
- const filePath = output.slice(last, index);
69
- // We passed --no-renames above, so a rename will be a delete of the old location and an add at the new.
70
- // The newHash will be all zeros if the file is deleted, or a hash if it exists
71
- const mode = header.slice(8, 14);
72
- const oldhash = header.slice(-83, -43);
73
- const newhash = header.slice(-42, -2);
74
- result.set(filePath, {
75
- mode,
76
- oldhash,
77
- newhash,
78
- status
79
- });
80
- last = index + 1;
81
- index = output.indexOf("\0", last);
82
- }
83
- return result;
84
- }
85
- function parseGitStatus(output) {
86
- const result = new Map();
87
- // Parse the output
88
- // With the -z modifier, paths are delimited by nulls
89
- // A line looks like:
90
- // XY <path>\0
91
- // M tools/prettier-git/prettier-git.js\0
92
- let startOfLine = 0;
93
- let eolIndex = output.indexOf("\0", startOfLine);
94
- while(eolIndex >= 0){
95
- // We passed --no-renames above, so a rename will be a delete of the old location and an add at the new.
96
- // charAt(startOfLine) is the index status, charAt(startOfLine + 1) is the working tree status
97
- const workingTreeStatus = output.charAt(startOfLine + 1);
98
- // Deleted in working tree, or not modified in working tree and deleted in index
99
- const deleted = workingTreeStatus === "D" || workingTreeStatus === " " && output.charAt(startOfLine) === "D";
100
- const filePath = output.slice(startOfLine + 3, eolIndex);
101
- result.set(filePath, !deleted);
102
- startOfLine = eolIndex + 1;
103
- eolIndex = output.indexOf("\0", startOfLine);
104
- }
105
- return result;
106
- }
107
- const repoRootCache = new Map();
108
- function getRepoRoot(cwd, gitPath) {
109
- let cachedResult = repoRootCache.get(cwd);
110
- if (!cachedResult) {
111
- const result = _execa.default.sync(gitPath || "git", [
112
- "--no-optional-locks",
113
- "rev-parse",
114
- "--show-toplevel"
115
- ], {
116
- cwd
117
- });
118
- if (result.exitCode !== 0) {
119
- ensureGitMinimumVersion(gitPath);
120
- throw new Error(`git rev-parse exited with status ${result.exitCode}: ${result.stderr}`);
121
- }
122
- repoRootCache.set(cwd, cachedResult = result.stdout.trim());
123
- }
124
- return cachedResult;
125
- }
126
- function applyWorkingTreeState(rootDirectory, state, gitPath) {
127
- const statusResult = _execa.default.sync(gitPath || "git", [
128
- "--no-optional-locks",
129
- "status",
130
- "-z",
131
- "-u",
132
- "--no-renames",
133
- "--"
134
- ], {
135
- cwd: rootDirectory
136
- });
137
- if (statusResult.exitCode !== 0) {
138
- ensureGitMinimumVersion(gitPath);
139
- throw new Error(`git status exited with status ${statusResult.exitCode}: ${statusResult.stderr}`);
140
- }
141
- const locallyModified = parseGitStatus(statusResult.stdout);
142
- const filesToHash = [];
143
- for (const [filePath, exists] of locallyModified){
144
- if (exists) {
145
- filesToHash.push(filePath);
146
- } else {
147
- state.delete(filePath);
148
- }
149
- }
150
- if (filesToHash.length) {
151
- // Use --stdin-paths arg to pass the list of files to git in order to avoid issues with
152
- // command length
153
- const hashObjectResult = _execa.default.sync(gitPath || "git", [
154
- "hash-object",
155
- "--stdin-paths"
156
- ], {
157
- cwd: rootDirectory,
158
- input: filesToHash.join("\n")
159
- });
160
- if (hashObjectResult.exitCode !== 0) {
161
- ensureGitMinimumVersion(gitPath);
162
- throw new Error(`git hash-object exited with status ${hashObjectResult.exitCode}: ${hashObjectResult.stderr}`);
163
- }
164
- const hashStdout = hashObjectResult.stdout.trim();
165
- // The result of "git hash-object" will be a list of file hashes delimited by newlines
166
- const hashes = hashStdout.split("\n");
167
- if (hashes.length !== filesToHash.length) {
168
- throw new Error(`Passed ${filesToHash.length} file paths to Git to hash, but received ${hashes.length} hashes.`);
169
- }
170
- const len = hashes.length;
171
- for(let i = 0; i < len; i++){
172
- const hash = hashes[i];
173
- const filePath = filesToHash[i];
174
- state.set(filePath, hash);
175
- }
176
- }
177
- }
178
- function getRepoState(cwd, gitPath) {
179
- const rootDirectory = getRepoRoot(cwd, gitPath);
180
- const lsTreeResult = _execa.default.sync(gitPath || "git", [
181
- "--no-optional-locks",
182
- "ls-tree",
183
- "-r",
184
- "-z",
185
- "--full-name",
186
- "HEAD",
187
- "--"
188
- ], {
189
- cwd: rootDirectory
190
- });
191
- if (lsTreeResult.exitCode !== 0) {
192
- ensureGitMinimumVersion(gitPath);
193
- throw new Error(`git ls-tree exited with status ${lsTreeResult.exitCode}: ${lsTreeResult.stderr}`);
194
- }
195
- const state = parseGitLsTree(lsTreeResult.stdout);
196
- applyWorkingTreeState(rootDirectory, state, gitPath);
197
- return state;
198
- }
199
- function getRepoChanges(cwd, revision = "HEAD", gitPath) {
200
- const rootDirectory = getRepoRoot(cwd, gitPath);
201
- const result = _execa.default.sync(gitPath || "git", [
202
- "--no-optional-locks",
203
- "diff-index",
204
- "--color=never",
205
- "--no-renames",
206
- "--no-commit-id",
207
- "--cached",
208
- "-z",
209
- revision,
210
- "--"
211
- ], {
212
- cwd: rootDirectory
213
- });
214
- if (result.exitCode !== 0) {
215
- ensureGitMinimumVersion(gitPath);
216
- throw new Error(`git diff-index exited with status ${result.exitCode}: ${result.stderr}`);
217
- }
218
- const changes = parseGitDiffIndex(result.stdout);
219
- return changes;
220
- }
221
- function ensureGitMinimumVersion(gitPath) {
222
- const gitVersion = getGitVersion(gitPath);
223
- if (gitVersion.major < MINIMUM_GIT_VERSION.major || gitVersion.major === MINIMUM_GIT_VERSION.major && gitVersion.minor < MINIMUM_GIT_VERSION.minor || gitVersion.major === MINIMUM_GIT_VERSION.major && gitVersion.minor === MINIMUM_GIT_VERSION.minor && gitVersion.patch < MINIMUM_GIT_VERSION.patch) {
224
- throw new Error(`The minimum Git version required is ` + `${MINIMUM_GIT_VERSION.major}.${MINIMUM_GIT_VERSION.minor}.${MINIMUM_GIT_VERSION.patch}. ` + `Your version is ${gitVersion.major}.${gitVersion.minor}.${gitVersion.patch}.`);
225
- }
226
- }
227
- function getGitVersion(gitPath) {
228
- const result = _execa.default.sync(gitPath || "git", [
229
- "version"
230
- ]);
231
- if (result.exitCode !== 0) {
232
- throw new Error(`While validating the Git installation, the "git version" command failed with ` + `status ${result.exitCode}: ${result.stderr}`);
233
- }
234
- return parseGitVersion(result.stdout);
235
- }
236
- function parseGitVersion(gitVersionOutput) {
237
- // This regexp matches output of "git version" that looks like `git version <number>.<number>.<number>(+whatever)`
238
- // Examples:
239
- // - git version 1.2.3
240
- // - git version 1.2.3.4.5
241
- // - git version 1.2.3windows.1
242
- // - git version 1.2.3.windows.1
243
- const versionRegex = /^git version (\d+)\.(\d+)\.(\d+)/;
244
- const match = versionRegex.exec(gitVersionOutput);
245
- if (!match) {
246
- throw new Error(`While validating the Git installation, the "git version" command produced ` + `unexpected output: "${gitVersionOutput}"`);
247
- }
248
- const major = parseInt(match[1], 10);
249
- const minor = parseInt(match[2], 10);
250
- const patch = parseInt(match[3], 10);
251
- return {
252
- major,
253
- minor,
254
- patch
255
- };
256
- }
@@ -1,14 +0,0 @@
1
- import type { RepoInfo } from "./repoInfo.js";
2
- /**
3
- * Generates a hash string based on files in a package
4
- *
5
- * This implementation relies on `git hash-object` to quickly calculate all files
6
- * in the repo, caching this result so repeated calls to this function will be
7
- * a simple lookup.
8
- *
9
- * Note: We have to force the types because globby types are wrong
10
- *
11
- * @param packageRoot The root of the package
12
- * @param repoInfo The repoInfo that carries information about repo-wide hashes
13
- */
14
- export declare function generateHashOfFiles(packageRoot: string, repoInfo: RepoInfo): Promise<string>;
@@ -1,71 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", {
3
- value: true
4
- });
5
- Object.defineProperty(exports, "generateHashOfFiles", {
6
- enumerable: true,
7
- get: ()=>generateHashOfFiles
8
- });
9
- const _path = /*#__PURE__*/ _interopRequireWildcard(require("path"));
10
- const _helpersJs = require("./helpers.js");
11
- function _getRequireWildcardCache(nodeInterop) {
12
- if (typeof WeakMap !== "function") return null;
13
- var cacheBabelInterop = new WeakMap();
14
- var cacheNodeInterop = new WeakMap();
15
- return (_getRequireWildcardCache = function(nodeInterop) {
16
- return nodeInterop ? cacheNodeInterop : cacheBabelInterop;
17
- })(nodeInterop);
18
- }
19
- function _interopRequireWildcard(obj, nodeInterop) {
20
- if (!nodeInterop && obj && obj.__esModule) {
21
- return obj;
22
- }
23
- if (obj === null || typeof obj !== "object" && typeof obj !== "function") {
24
- return {
25
- default: obj
26
- };
27
- }
28
- var cache = _getRequireWildcardCache(nodeInterop);
29
- if (cache && cache.has(obj)) {
30
- return cache.get(obj);
31
- }
32
- var newObj = {};
33
- var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor;
34
- for(var key in obj){
35
- if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) {
36
- var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null;
37
- if (desc && (desc.get || desc.set)) {
38
- Object.defineProperty(newObj, key, desc);
39
- } else {
40
- newObj[key] = obj[key];
41
- }
42
- }
43
- }
44
- newObj.default = obj;
45
- if (cache) {
46
- cache.set(obj, newObj);
47
- }
48
- return newObj;
49
- }
50
- async function generateHashOfFiles(packageRoot, repoInfo) {
51
- const { repoHashes , root , packageHashes } = repoInfo;
52
- const hashes = [];
53
- const packageRelativeRoot = _path.default.relative(root, packageRoot).replace(/\\/g, "/");
54
- if (packageHashes[packageRelativeRoot]) {
55
- // Fast path: if files are clearly inside a package as per the packageHashes cache
56
- for (const hash of packageHashes[packageRelativeRoot]){
57
- hashes.push(hash[0], hash[1]);
58
- }
59
- return (0, _helpersJs.hashStrings)(hashes);
60
- } else {
61
- // Slow old path: if files are not clearly inside a package (mostly the case for malformed monorepos, like tests)
62
- const normalized = _path.default.normalize(packageRoot) + _path.sep;
63
- const files = Object.keys(repoHashes).filter((f)=>_path.default.join(root, f).includes(normalized));
64
- files.sort((a, b)=>a.localeCompare(b));
65
- const hashes = [];
66
- for (const file of files){
67
- hashes.push(file, repoHashes[file]);
68
- }
69
- return (0, _helpersJs.hashStrings)(hashes);
70
- }
71
- }
@@ -1,9 +0,0 @@
1
- import type { RepoInfo } from "./repoInfo.js";
2
- export type PackageHashInfo = {
3
- name: string;
4
- filesHash: string;
5
- dependenciesHash: string;
6
- internalDependencies: string[];
7
- };
8
- export declare function generateHashOfInternalPackages(internalPackages: PackageHashInfo[]): string;
9
- export declare function getPackageHash(packageRoot: string, repoInfo: RepoInfo): Promise<PackageHashInfo>;
@@ -1,65 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", {
3
- value: true
4
- });
5
- function _export(target, all) {
6
- for(var name in all)Object.defineProperty(target, name, {
7
- enumerable: true,
8
- get: all[name]
9
- });
10
- }
11
- _export(exports, {
12
- generateHashOfInternalPackages: ()=>generateHashOfInternalPackages,
13
- getPackageHash: ()=>getPackageHash
14
- });
15
- const _crypto = /*#__PURE__*/ _interopRequireDefault(require("crypto"));
16
- const _path = /*#__PURE__*/ _interopRequireDefault(require("path"));
17
- const _fs = /*#__PURE__*/ _interopRequireDefault(require("fs"));
18
- const _resolveInternalDependenciesJs = require("./resolveInternalDependencies.js");
19
- const _resolveExternalDependenciesJs = require("./resolveExternalDependencies.js");
20
- const _hashOfFilesJs = require("./hashOfFiles.js");
21
- const _helpersJs = require("./helpers.js");
22
- function _interopRequireDefault(obj) {
23
- return obj && obj.__esModule ? obj : {
24
- default: obj
25
- };
26
- }
27
- function generateHashOfInternalPackages(internalPackages) {
28
- internalPackages.sort((a, b)=>a.name.localeCompare(b.name));
29
- const hasher = _crypto.default.createHash("sha1");
30
- internalPackages.forEach((pkg)=>{
31
- hasher.update(pkg.name);
32
- hasher.update(pkg.filesHash);
33
- hasher.update(pkg.dependenciesHash);
34
- });
35
- return hasher.digest("hex");
36
- }
37
- const memoization = {};
38
- async function getPackageHash(packageRoot, repoInfo) {
39
- const { workspaceInfo , parsedLock } = repoInfo;
40
- const memoizationKey = _path.default.resolve(packageRoot);
41
- if (memoization[memoizationKey]) {
42
- return memoization[memoizationKey];
43
- }
44
- const { name , dependencies , devDependencies } = JSON.parse(_fs.default.readFileSync(_path.default.join(packageRoot, "package.json"), "utf-8"));
45
- const allDependencies = {
46
- ...dependencies,
47
- ...devDependencies
48
- };
49
- const internalDependencies = (0, _resolveInternalDependenciesJs.resolveInternalDependencies)(allDependencies, workspaceInfo);
50
- const externalDeoendencies = (0, _resolveExternalDependenciesJs.resolveExternalDependencies)(allDependencies, workspaceInfo, parsedLock);
51
- const resolvedDependencies = [
52
- ...internalDependencies,
53
- ...externalDeoendencies
54
- ];
55
- const filesHash = await (0, _hashOfFilesJs.generateHashOfFiles)(packageRoot, repoInfo);
56
- const dependenciesHash = (0, _helpersJs.hashStrings)(resolvedDependencies);
57
- const packageHash = {
58
- name,
59
- filesHash,
60
- dependenciesHash,
61
- internalDependencies
62
- };
63
- memoization[memoizationKey] = packageHash;
64
- return packageHash;
65
- }
package/lib/helpers.d.ts DELETED
@@ -1,3 +0,0 @@
1
- export declare function hashStrings(strings: string | string[]): string;
2
- export declare function getPackageRoot(cwd: string): Promise<string>;
3
- export declare function nameAtVersion(name: string, version: string): string;
package/lib/helpers.js DELETED
@@ -1,47 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", {
3
- value: true
4
- });
5
- function _export(target, all) {
6
- for(var name in all)Object.defineProperty(target, name, {
7
- enumerable: true,
8
- get: all[name]
9
- });
10
- }
11
- _export(exports, {
12
- hashStrings: ()=>hashStrings,
13
- getPackageRoot: ()=>getPackageRoot,
14
- nameAtVersion: ()=>nameAtVersion
15
- });
16
- const _path = /*#__PURE__*/ _interopRequireDefault(require("path"));
17
- const _crypto = /*#__PURE__*/ _interopRequireDefault(require("crypto"));
18
- const _findUp = /*#__PURE__*/ _interopRequireDefault(require("find-up"));
19
- function _interopRequireDefault(obj) {
20
- return obj && obj.__esModule ? obj : {
21
- default: obj
22
- };
23
- }
24
- function hashStrings(strings) {
25
- const hasher = _crypto.default.createHash("sha1");
26
- const anArray = typeof strings === "string" ? [
27
- strings
28
- ] : strings;
29
- const elements = [
30
- ...anArray
31
- ];
32
- elements.sort((a, b)=>a.localeCompare(b));
33
- elements.forEach((element)=>hasher.update(element));
34
- return hasher.digest("hex");
35
- }
36
- async function getPackageRoot(cwd) {
37
- const packageRoot = await (0, _findUp.default)("package.json", {
38
- cwd
39
- });
40
- if (!packageRoot) {
41
- throw new Error(`Could not find package.json inside ${cwd}.`);
42
- }
43
- return _path.default.dirname(packageRoot);
44
- }
45
- function nameAtVersion(name, version) {
46
- return `${name}@${version}`;
47
- }
package/lib/repoInfo.d.ts DELETED
@@ -1,26 +0,0 @@
1
- import type { WorkspaceInfo, ParsedLock } from "workspace-tools";
2
- export interface RepoInfo {
3
- root: string;
4
- workspaceInfo: WorkspaceInfo;
5
- parsedLock: ParsedLock;
6
- repoHashes: {
7
- [key: string]: string;
8
- };
9
- packageHashes: Record<string, [string, string][]>;
10
- }
11
- export declare function getRepoInfoNoCache(cwd: string): Promise<{
12
- root: string;
13
- workspaceInfo: WorkspaceInfo;
14
- parsedLock: ParsedLock;
15
- repoHashes: Record<string, string>;
16
- packageHashes: Record<string, [string, string][]>;
17
- }>;
18
- /**
19
- * Retrieves the repoInfo, one at a time
20
- *
21
- * No parallel of this function is allowed; this maximizes the cache hit even
22
- * though the getWorkspaces and parseLockFile are async functions from workspace-tools
23
- *
24
- * @param cwd
25
- */
26
- export declare function getRepoInfo(cwd: string): Promise<RepoInfo>;
package/lib/repoInfo.js DELETED
@@ -1,65 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", {
3
- value: true
4
- });
5
- function _export(target, all) {
6
- for(var name in all)Object.defineProperty(target, name, {
7
- enumerable: true,
8
- get: all[name]
9
- });
10
- }
11
- _export(exports, {
12
- getRepoInfoNoCache: ()=>getRepoInfoNoCache,
13
- getRepoInfo: ()=>getRepoInfo
14
- });
15
- const _workspaceTools = require("workspace-tools");
16
- const _getPackageDepsJs = require("./getPackageDeps.js");
17
- const _createPackageHashesJs = require("./createPackageHashes.js");
18
- const repoInfoCache = [];
19
- /**
20
- * repoInfo cache lookup - it is specialized to be using a substring match to make it run as fast as possible
21
- * @param packageRoot
22
- */ function searchRepoInfoCache(packageRoot) {
23
- for (const repoInfo of repoInfoCache){
24
- if (repoInfo.workspaceInfo && packageRoot.startsWith(repoInfo.root)) {
25
- return repoInfo;
26
- }
27
- }
28
- }
29
- async function getRepoInfoNoCache(cwd) {
30
- const root = (0, _workspaceTools.getWorkspaceRoot)(cwd);
31
- if (!root) {
32
- throw new Error("Cannot initialize Repo class without a workspace root");
33
- }
34
- // Assuming the package-deps-hash package returns a map of files to hashes that are unordered
35
- const unorderedRepoHashes = Object.fromEntries((0, _getPackageDepsJs.getPackageDeps)(root));
36
- // Sorting repoHash by key because we want to consistent hashing based on the order of the files
37
- const repoHashes = Object.keys(unorderedRepoHashes).sort((a, b)=>a.localeCompare(b)).reduce((obj, key)=>{
38
- obj[key] = unorderedRepoHashes[key];
39
- return obj;
40
- }, {});
41
- const workspaceInfo = (0, _workspaceTools.getWorkspaces)(root);
42
- const parsedLock = await (0, _workspaceTools.parseLockFile)(root);
43
- const packageHashes = (0, _createPackageHashesJs.createPackageHashes)(root, workspaceInfo, repoHashes);
44
- const repoInfo = {
45
- root,
46
- workspaceInfo,
47
- parsedLock,
48
- repoHashes,
49
- packageHashes
50
- };
51
- repoInfoCache.push(repoInfo);
52
- return repoInfo;
53
- }
54
- // A promise to guarantee the getRepoInfo is done one at a time
55
- let oneAtATime = Promise.resolve();
56
- async function getRepoInfo(cwd) {
57
- oneAtATime = oneAtATime.then(async ()=>{
58
- const searchResult = searchRepoInfoCache(cwd);
59
- if (searchResult) {
60
- return searchResult;
61
- }
62
- return getRepoInfoNoCache(cwd);
63
- });
64
- return oneAtATime;
65
- }