1 | const { createHash } = require(`crypto`)
|
2 | const { basename } = require(`path`)
|
3 | const { execSync } = require(`child_process`)
|
4 | const gitUp = require(`git-up`)
|
5 |
|
6 | const 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 |
|
16 | const getRepoMetadata = url => {
|
17 | try {
|
18 |
|
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 |
|
31 | }
|
32 | return null
|
33 | }
|
34 |
|
35 | const getRepositoryIdFromPath = () => basename(process.cwd())
|
36 |
|
37 | const getGitRemoteWithGit = () => {
|
38 | try {
|
39 |
|
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 |
|
53 | }
|
54 | return null
|
55 | }
|
56 |
|
57 | const 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 |
|
70 | }
|
71 | }
|
72 | return null
|
73 | }
|
74 |
|
75 | const hash = str =>
|
76 | createHash(`sha256`)
|
77 | .update(str)
|
78 | .digest(`hex`)
|
79 |
|
80 | module.exports = {
|
81 | getRepositoryId,
|
82 | getRepoMetadata,
|
83 | }
|