-
Notifications
You must be signed in to change notification settings - Fork 391
/
Copy pathget-repo-data.ts
88 lines (76 loc) · 2.41 KB
/
get-repo-data.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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
import { dirname } from 'path'
import util from 'util'
import { findUp } from 'find-up'
import gitRepoInfo from 'git-repo-info'
import gitconfiglocal from 'gitconfiglocal'
import parseGithubUrl from 'parse-github-url'
import { log } from './command-helpers.js'
export interface RepoData {
name: string | null
owner: string | null
repo: string | null
url: string
branch: string
provider: string | null
httpsUrl: string
}
const getRepoData = async ({
remoteName,
workingDir,
}: {
remoteName?: string
workingDir: string
}): Promise<RepoData | { error: string }> => {
try {
const [gitConfig, gitDirectory] = await Promise.all([
util.promisify(gitconfiglocal)(workingDir),
findUp('.git', { cwd: workingDir, type: 'directory' }),
])
if (!gitDirectory || !gitConfig || !gitConfig.remote || Object.keys(gitConfig.remote).length === 0) {
throw new Error('No Git remote found')
}
const baseGitPath = dirname(gitDirectory)
if (workingDir !== baseGitPath) {
log(`Git directory located in ${baseGitPath}`)
}
if (!remoteName) {
const remotes = Object.keys(gitConfig.remote)
remoteName = remotes.find((remote) => remote === 'origin') || remotes[0]
}
if (
!Object.prototype.hasOwnProperty.call(gitConfig.remote, remoteName) ||
!gitConfig.remote[remoteName] ||
Object.keys(gitConfig.remote[remoteName]).length === 0
) {
throw new Error(
`The specified remote "${remoteName}" is not defined in Git repo. Please use --git-remote-name flag to specify a remote.`,
)
}
const { url } = gitConfig.remote[remoteName]
const parsedUrl = parseGithubUrl(url)
// TODO(serhalp): Validate more aggressively? We should probably require `owner`, `repo`, `host`?
if (parsedUrl == null) {
throw new Error(`The specified Git remote ${remoteName} is not a valid URL: ${url}`)
}
const { host, name, owner, repo } = parsedUrl
const { branch } = gitRepoInfo()
return {
name,
owner,
repo,
url,
branch,
provider: host != null ? PROVIDERS[host] ?? host : host,
httpsUrl: `https://${host}/${repo}`,
}
} catch (error) {
return {
error: error instanceof Error ? error.message : error?.toString() ?? 'Failed to get repo data',
}
}
}
const PROVIDERS: Record<string, string> = {
'github.com': 'github',
'gitlab.com': 'gitlab',
}
export default getRepoData