1 | "use strict";
|
2 |
|
3 | const {
|
4 | createHash
|
5 | } = require(`crypto`);
|
6 |
|
7 | const {
|
8 | basename
|
9 | } = require(`path`);
|
10 |
|
11 | const {
|
12 | execSync
|
13 | } = require(`child_process`);
|
14 |
|
15 | const gitUp = require(`git-up`);
|
16 |
|
17 | const getRepositoryId = () => {
|
18 | const gitRepo = getGitRemoteWithGit() || getRepositoryFromNetlifyEnv();
|
19 |
|
20 | if (gitRepo) {
|
21 | return gitRepo;
|
22 | } else {
|
23 | const repo = getRepositoryIdFromPath();
|
24 | return {
|
25 | repositoryId: `pwd:${hash(repo)}`
|
26 | };
|
27 | }
|
28 | };
|
29 |
|
30 | const getRepoMetadata = url => {
|
31 | try {
|
32 |
|
33 | const {
|
34 | resource: provider,
|
35 | pathname
|
36 | } = gitUp(url);
|
37 | const res = {
|
38 | provider: hash(provider)
|
39 | };
|
40 | const userAndRepo = pathname.split(`/`);
|
41 |
|
42 | if (userAndRepo.length == 3) {
|
43 | res.owner = hash(userAndRepo[1]);
|
44 | res.name = hash(userAndRepo[2].replace(`.git`, ``));
|
45 | }
|
46 |
|
47 | return res;
|
48 | } catch (e) {
|
49 | }
|
50 |
|
51 | return null;
|
52 | };
|
53 |
|
54 | const getRepositoryIdFromPath = () => basename(process.cwd());
|
55 |
|
56 | const getGitRemoteWithGit = () => {
|
57 | try {
|
58 |
|
59 | const originBuffer = execSync(`git config --local --get remote.origin.url`, {
|
60 | timeout: 1000,
|
61 | stdio: `pipe`
|
62 | });
|
63 | const repo = String(originBuffer).trim();
|
64 |
|
65 | if (repo) {
|
66 | return {
|
67 | repositoryId: `git:${hash(repo)}`,
|
68 | repositoryData: getRepoMetadata(repo)
|
69 | };
|
70 | }
|
71 | } catch (e) {
|
72 | }
|
73 |
|
74 | return null;
|
75 | };
|
76 |
|
77 | const getRepositoryFromNetlifyEnv = () => {
|
78 | if (process.env.NETLIFY) {
|
79 | try {
|
80 | const url = process.env.REPOSITORY_URL;
|
81 | const repoPart = url.split(`@`)[1];
|
82 |
|
83 | if (repoPart) {
|
84 | return {
|
85 | repositoryId: `git:${hash(repoPart)}`,
|
86 | repositoryData: getRepoMetadata(url)
|
87 | };
|
88 | }
|
89 | } catch (e) {
|
90 | }
|
91 | }
|
92 |
|
93 | return null;
|
94 | };
|
95 |
|
96 | const hash = str => createHash(`sha256`).update(str).digest(`hex`);
|
97 |
|
98 | module.exports = {
|
99 | getRepositoryId,
|
100 | getRepoMetadata
|
101 | }; |
\ | No newline at end of file |