Skip to content

Commit 70f0e26

Browse files
author
Nicholas Pape
authored
Refactor package-deps-hash for improved testability (microsoft#245)
* Refactor package-deps-hash for improved testability * Add a changefile * Tests
1 parent 7bc5a65 commit 70f0e26

6 files changed

Lines changed: 181 additions & 65 deletions

File tree

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
{
2+
"changes": [
3+
{
4+
"comment": "",
5+
"packageName": "@microsoft/package-deps-hash",
6+
"type": "none"
7+
}
8+
],
9+
"packageName": "@microsoft/package-deps-hash",
10+
"email": "nickpape@users.noreply.github.com"
11+
}

‎common/reviews/api/package-deps-hash.api.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
// @public (undocumented)
1+
// @public
22
export function getPackageDeps(packagePath: string = process.cwd(), excludedPaths?: string[]): IPackageDeps;
33

44
// @public (undocumented)

‎libraries/package-deps-hash/package.json‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,9 @@
1414
"clean": "gulp clean",
1515
"test": "gulp test"
1616
},
17+
"dependencies": {
18+
"@types/es6-collections": "0.5.29"
19+
},
1720
"devDependencies": {
1821
"@microsoft/node-library-build": ">=3.0.1 <4.0.0",
1922
"chai": "~3.5.0",
Lines changed: 127 additions & 61 deletions
Original file line numberDiff line numberDiff line change
@@ -1,86 +1,152 @@
11
import * as child_process from 'child_process';
22
import { IPackageDeps } from './IPackageDeps';
33

4-
const PROCESS_OUTPUT_DELIMITER: string = '///~X~X~X~X~X~X~///';
4+
export type GitStatusChangeType = 'D' | 'M' | 'A';
5+
6+
/**
7+
* Parses the output of the "git ls-tree" command
8+
*/
9+
export function parseGitLsTree(output: string): Map<string, string> {
10+
const changes: Map<string, string> = new Map<string, string>();
11+
12+
if (output) {
13+
// Note: The output of git ls-tree uses \n newlines regardless of OS.
14+
output.split('\n').forEach(line => {
15+
16+
// A line is expected to look like:
17+
// 100644 blob 3451bccdc831cb43d7a70ed8e628dcf9c7f888c8 src/typings/tsd.d.ts
18+
19+
if (line) {
20+
// Take everything after the "100644 blob", which is just the hash and filename
21+
const [hash, filename]: string[] = line.substr(line.indexOf('blob ') + 5).split('\t');
22+
if (!filename || !hash) {
23+
throw new Error(`Cannot parse git ls-tree input: "${line}"`);
24+
}
25+
26+
changes.set(filename, hash);
27+
}
28+
});
29+
}
530

6-
/** @public */
31+
return changes;
32+
}
33+
34+
/**
35+
* Parses the output of the "git status" command
36+
*/
37+
export function parseGitStatus(output: string, packagePath: string): Map<string, GitStatusChangeType> {
38+
const changes: Map<string, GitStatusChangeType> = new Map<string, GitStatusChangeType>();
39+
const filesToHash: string[] = [];
40+
41+
/*
42+
* Typically, output will look something like:
43+
* M temp_modules/rush-package-deps-hash/package.json
44+
* D package-deps-hash/src/index.ts
45+
*/
46+
47+
// If there was an issue with `git ls-tree`, or there are no current changes, processOutputBlocks[1]
48+
// will be empty or undefined
49+
if (!output) {
50+
return changes;
51+
}
52+
53+
// Note: The output of git hash-object uses \n newlines regardless of OS.
54+
output
55+
.trim()
56+
.split('\n')
57+
.forEach(line => {
58+
const [changeType, filename]: string[] = line.trim().split(' ');
59+
/*
60+
* changeType == 'D' or 'M' or 'A'
61+
* filename == path to the file
62+
*/
63+
if (changeType && filename) {
64+
changes.set(filename, changeType as GitStatusChangeType);
65+
}
66+
});
67+
68+
return changes;
69+
}
70+
71+
/**
72+
* Takes a list of files and returns the current git hashes for them
73+
*/
74+
export function gitHashFiles(filesToHash: string[], packagePath: string): Map<string, string> {
75+
const changes: Map<string, string> = new Map<string, string>();
76+
if (filesToHash.length) {
77+
const hashStdout: string = child_process.execSync(
78+
'git hash-object ' + filesToHash.join(' '),
79+
{ cwd: packagePath }).toString();
80+
81+
// The result of hashStdout will be a list of file hashes delimited by newlines
82+
const hashes: string[] = hashStdout.split('\n');
83+
84+
filesToHash.forEach((filename, i) => changes.set(filename, hashes[i]));
85+
}
86+
return changes;
87+
}
88+
89+
/**
90+
* Executes "git ls-tree" in a folder
91+
*/
92+
export function gitLsTree(path: string): string {
93+
return child_process.execSync(
94+
`git ls-tree HEAD -r`,
95+
{ cwd: path }).toString();
96+
}
97+
98+
/**
99+
* Executes "git status" in a folder
100+
*/
101+
export function gitStatus(path: string): string {
102+
return child_process.execSync(
103+
`git status -s -u .`,
104+
{ cwd: path }).toString();
105+
}
106+
107+
/**
108+
* Collects the current git filehashes for a directory
109+
* @public
110+
*/
7111
export function getPackageDeps(packagePath: string = process.cwd(), excludedPaths?: string[]): IPackageDeps {
8112
const excludedHashes: { [key: string]: boolean } = {};
9113

10114
if (excludedPaths) {
11115
excludedPaths.forEach(path => excludedHashes[path] = true);
12116
}
13117

14-
const stdout: string = child_process.execSync(
15-
`git ls-tree HEAD -r && echo ${PROCESS_OUTPUT_DELIMITER} && git status -s -u .`,
16-
{ cwd: packagePath }).toString();
17-
18118
const changes: IPackageDeps = {
19119
files: {}
20120
};
21-
const processOutputBlocks: string[] = stdout.split(PROCESS_OUTPUT_DELIMITER);
22121

23-
// Note: The output of git ls-tree uses \n newlines regardless of OS.
24-
processOutputBlocks[0].split('\n').forEach(line => {
122+
const gitLsOutput: string = gitLsTree(packagePath);
123+
124+
// Add all the checked in hashes
125+
parseGitLsTree(gitLsOutput).forEach((hash: string, filename: string) => {
126+
if (!excludedHashes[filename]) {
127+
changes.files[filename] = hash;
128+
}
129+
});
25130

26-
// A line is expected to look like:
27-
// 100644 blob 3451bccdc831cb43d7a70ed8e628dcf9c7f888c8 src/typings/tsd.d.ts
131+
// Update the checked in hashes with the current repo status
132+
const gitStatusOutput: string = gitStatus(packagePath);
133+
const currentlyChangedFiles: Map<string, GitStatusChangeType > =
134+
parseGitStatus(gitStatusOutput, packagePath);
28135

29-
if (line) {
30-
// Take everything after the "100644 blob", which is just the hash and filename
31-
const [hash, filename]: string[] = line.substr(line.indexOf('blob ') + 5).split('\t');
136+
const filesToHash: string[] = [];
137+
currentlyChangedFiles.forEach((changeType: GitStatusChangeType, filename: string) => {
138+
if (changeType === 'D') {
139+
delete changes.files[filename];
140+
} else {
32141
if (!excludedHashes[filename]) {
33-
changes.files[filename] = hash;
142+
filesToHash.push(filename);
34143
}
35144
}
36145
});
37146

38-
// If there was an issue with `git ls-tree`, or there are no current changes, processOutputBlocks[1]
39-
// will be empty or undefined
40-
if (processOutputBlocks[1]) {
41-
const filesToHash: string[] = [];
42-
43-
/*
44-
* Typically, processOutputBlocks[1] will look something like:
45-
* M temp_modules/rush-package-deps-hash/package.json
46-
* D package-deps-hash/src/index.ts
47-
*/
48-
49-
// Note: The output of git hash-object uses \n newlines regardless of OS.
50-
processOutputBlocks[1]
51-
.trim()
52-
.split('\n')
53-
.forEach(line => {
54-
const [changeType, filename]: string[] = line.trim().split(' ');
55-
/*
56-
* changeType == 'D' or 'M' or 'A'
57-
* filename == path to the file
58-
*/
59-
60-
if (changeType && filename) {
61-
// If the file is currently deleted, then it will have a 'D'
62-
if (changeType === 'D') {
63-
delete changes.files[filename];
64-
} else {
65-
// Otherwise the file was changed or added and we should get the current hash
66-
if (!excludedHashes[filename]) {
67-
filesToHash.push(filename);
68-
}
69-
}
70-
}
71-
});
72-
73-
if (filesToHash.length) {
74-
const hashStdout: string = child_process.execSync(
75-
'git hash-object ' + filesToHash.join(' '),
76-
{ cwd: packagePath }).toString();
77-
78-
// The result of hashStdout will be a list of file hashes delimited by newlines
79-
80-
const hashes: string[] = hashStdout.split('\n');
147+
gitHashFiles(filesToHash, packagePath).forEach((hash: string, filename: string) => {
148+
changes.files[filename] = hash;
149+
});
81150

82-
filesToHash.forEach((filename, i) => changes.files[filename] = hashes[i]);
83-
}
84-
}
85151
return changes;
86152
}

‎libraries/package-deps-hash/src/tests/getPackageDeps.test.ts‎

Lines changed: 37 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
1-
import { getPackageDeps } from '../getPackageDeps';
1+
import { getPackageDeps, parseGitLsTree } from '../getPackageDeps';
22
import { IPackageDeps } from '../IPackageDeps';
3-
import { expect } from 'chai';
3+
import { expect, assert } from 'chai';
44
import * as path from 'path';
55
import * as fs from 'fs';
66
import { execSync } from 'child_process';
@@ -12,6 +12,41 @@ const SOURCE_PATH: string = path.join(__dirname).replace(
1212
const TEST_PROJECT_PATH: string = path.join(SOURCE_PATH, 'testProject');
1313
const NESTED_TEST_PROJECT_PATH: string = path.join(SOURCE_PATH, 'nestedTestProject');
1414

15+
describe('parseGitLsTree', () => {
16+
it('can handle a blob', (done) => {
17+
const filename: string = 'src/typings/tsd.d.ts';
18+
const hash: string = '3451bccdc831cb43d7a70ed8e628dcf9c7f888c8';
19+
20+
const output: string = `100644 blob ${hash}\t${filename}`;
21+
const changes: Map<string, string> = parseGitLsTree(output);
22+
23+
assert.equal(changes.size, 1, 'Expect there to be exactly 1 change');
24+
assert.equal(changes.get(filename), hash, `Expect the hash to be ${hash}`);
25+
done();
26+
});
27+
28+
it('can handle multiple lines', (done) => {
29+
const filename1: string = 'src/typings/tsd.d.ts';
30+
const hash1: string = '3451bccdc831cb43d7a70ed8e628dcf9c7f888c8';
31+
32+
const filename2: string = 'src/foo bar/tsd.d.ts';
33+
const hash2: string = '0123456789abcdef1234567890abcdef01234567';
34+
35+
const output: string = `100644 blob ${hash1}\t${filename1}\n100666 blob ${hash2}\t${filename2}`;
36+
const changes: Map<string, string> = parseGitLsTree(output);
37+
38+
assert.equal(changes.size, 2, 'Expect there to be exactly 2 changes');
39+
assert.equal(changes.get(filename1), hash1, `Expect the hash to be ${hash1}`);
40+
assert.equal(changes.get(filename2), hash2, `Expect the hash to be ${hash2}`);
41+
done();
42+
});
43+
44+
it('throws with malformed input', (done) => {
45+
assert.throws(parseGitLsTree.bind(undefined, 'some super malformed input'));
46+
done();
47+
});
48+
});
49+
1550
describe('getPackageDeps', () => {
1651

1752
it('can parse commited file', (done) => {

‎libraries/package-deps-hash/tsconfig.json‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,8 @@
77
"moduleResolution": "node",
88
"types": [
99
"node",
10-
"mocha"
10+
"mocha",
11+
"es6-collections"
1112
]
1213
}
1314
}

0 commit comments

Comments
 (0)