-
Notifications
You must be signed in to change notification settings - Fork 59
/
Copy pathgit.ts
64 lines (52 loc) · 2.06 KB
/
git.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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
import {URL} from 'url'
import * as simpleGit from 'simple-git'
import {gitRemote} from '../../helpers/git/get-git-data'
import {CommitInfo} from './interfaces'
// Returns a configured SimpleGit.
export const newSimpleGit = async (): Promise<simpleGit.SimpleGit> => {
const options = {
baseDir: process.cwd(),
binary: 'git',
maxConcurrentProcesses: 1,
}
// Attempt to set the baseDir to the root of the repository so the 'git ls-files' command
// returns the tracked files paths relative to the root of the repository.
const git = simpleGit.simpleGit(options)
const root = await git.revparse('--show-toplevel')
options.baseDir = root
return simpleGit.simpleGit(options)
}
// StripCredentials removes credentials from a remote HTTP url.
export const stripCredentials = (remote: string) => {
try {
const url = new URL(remote)
url.username = ''
url.password = ''
return url.toString()
} catch {
return remote
}
}
// Returns the hash of the current repository.
const gitHash = async (git: simpleGit.SimpleGit): Promise<string> => git.revparse('HEAD')
// Returns the tracked files of the current repository.
export const gitTrackedFiles = async (git: simpleGit.SimpleGit): Promise<string[]> => {
const files = await git.raw('ls-files')
return files.split(/\r\n|\r|\n/).filter((s) => s !== '')
}
// Returns the current hash, remote URL and tracked files paths.
export const getCommitInfo = async (git: simpleGit.SimpleGit, repositoryURL?: string): Promise<CommitInfo> => {
// Invoke git commands to retrieve the remote, hash and tracked files.
// We're using Promise.all instead of Promive.allSettled since we want to fail early if
// any of the promises fails.
let remote: string
let hash: string
let trackedFiles: string[]
if (repositoryURL) {
;[hash, trackedFiles] = await Promise.all([gitHash(git), gitTrackedFiles(git)])
remote = repositoryURL
} else {
;[remote, hash, trackedFiles] = await Promise.all([gitRemote(git), gitHash(git), gitTrackedFiles(git)])
}
return new CommitInfo(hash, remote, trackedFiles)
}