UNPKG

1.88 kBJavaScriptView Raw
1const { createHash } = require(`crypto`)
2const { basename } = require(`path`)
3const { execSync } = require(`child_process`)
4const gitUp = require(`git-up`)
5
6const getRepositoryId = () => {
7 const gitRepo = getGitRemoteWithGit() || getRepositoryFromNetlifyEnv()
8 if (gitRepo) {
9 return gitRepo
10 } else {
11 const repo = getRepositoryIdFromPath()
12 return { repositoryId: `pwd:${hash(repo)}` }
13 }
14}
15
16const getRepoMetadata = url => {
17 try {
18 // This throws for invalid urls
19 const { resource: provider, pathname } = gitUp(url)
20 const res = { provider: hash(provider) }
21
22 const userAndRepo = pathname.split(`/`)
23 if (userAndRepo.length == 3) {
24 res.owner = hash(userAndRepo[1])
25 res.name = hash(userAndRepo[2].replace(`.git`, ``))
26 }
27
28 return res
29 } catch (e) {
30 // ignore
31 }
32 return null
33}
34
35const getRepositoryIdFromPath = () => basename(process.cwd())
36
37const getGitRemoteWithGit = () => {
38 try {
39 // we may live multiple levels in git repo
40 const originBuffer = execSync(
41 `git config --local --get remote.origin.url`,
42 { timeout: 1000, stdio: `pipe` }
43 )
44 const repo = String(originBuffer).trim()
45 if (repo) {
46 return {
47 repositoryId: `git:${hash(repo)}`,
48 repositoryData: getRepoMetadata(repo),
49 }
50 }
51 } catch (e) {
52 // ignore
53 }
54 return null
55}
56
57const getRepositoryFromNetlifyEnv = () => {
58 if (process.env.NETLIFY) {
59 try {
60 const url = process.env.REPOSITORY_URL
61 const repoPart = url.split(`@`)[1]
62 if (repoPart) {
63 return {
64 repositoryId: `git:${hash(repoPart)}`,
65 repositoryData: getRepoMetadata(url),
66 }
67 }
68 } catch (e) {
69 // ignore
70 }
71 }
72 return null
73}
74
75const hash = str =>
76 createHash(`sha256`)
77 .update(str)
78 .digest(`hex`)
79
80module.exports = {
81 getRepositoryId,
82 getRepoMetadata,
83}