-
Notifications
You must be signed in to change notification settings - Fork 6.8k
/
Copy pathgit-client.ts
51 lines (41 loc) · 1.95 KB
/
git-client.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
import {spawnSync} from 'child_process';
/**
* Class that can be used to execute Git commands within a given project directory.
*
* Relying on the working directory of the current process is not good because it's not
* guaranteed that the working directory is always the target project directory.
*/
export class GitClient {
constructor(public projectDir: string, public remoteGitUrl: string) {}
/** Gets the currently checked out branch for the project directory. */
getCurrentBranch() {
return spawnSync('git', ['symbolic-ref', '--short', 'HEAD'], {cwd: this.projectDir})
.stdout.toString().trim();
}
/** Gets the commit SHA for the specified remote repository branch. */
getRemoteCommitSha(branchName: string): string {
return spawnSync('git', ['ls-remote', this.remoteGitUrl, '-h', `refs/heads/${branchName}`],
{cwd: this.projectDir}).stdout.toString().split('\t')[0].trim();
}
/** Gets the latest commit SHA for the specified git reference. */
getLocalCommitSha(refName: string) {
return spawnSync('git', ['rev-parse', refName], {cwd: this.projectDir})
.stdout.toString().trim();
}
/** Gets whether the current Git repository has uncommitted changes. */
hasUncommittedChanges(): boolean {
return spawnSync('git', ['diff-index', '--quiet', 'HEAD'], {cwd: this.projectDir}).status !== 0;
}
/** Creates a new branch which is based on the previous active branch. */
checkoutNewBranch(branchName: string): boolean {
return spawnSync('git', ['checkout', '-b', branchName], {cwd: this.projectDir}).status === 0;
}
/** Stages all changes by running `git add -A`. */
stageAllChanges(): boolean {
return spawnSync('git', ['add', '-A'], {cwd: this.projectDir}).status === 0;
}
/** Creates a new commit within the current branch with the given commit message. */
createNewCommit(message: string): boolean {
return spawnSync('git', ['commit', '-m', message], {cwd: this.projectDir}).status === 0;
}
}