UNPKG

1.94 kBJavaScriptView Raw
1"use strict";
2
3const {
4 createHash
5} = require(`crypto`);
6
7const {
8 basename
9} = require(`path`);
10
11const {
12 execSync
13} = require(`child_process`);
14
15const gitUp = require(`git-up`);
16
17const 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
30const getRepoMetadata = url => {
31 try {
32 // This throws for invalid urls
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) {// ignore
49 }
50
51 return null;
52};
53
54const getRepositoryIdFromPath = () => basename(process.cwd());
55
56const getGitRemoteWithGit = () => {
57 try {
58 // we may live multiple levels in git repo
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) {// ignore
72 }
73
74 return null;
75};
76
77const 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) {// ignore
90 }
91 }
92
93 return null;
94};
95
96const hash = str => createHash(`sha256`).update(str).digest(`hex`);
97
98module.exports = {
99 getRepositoryId,
100 getRepoMetadata
101};
\No newline at end of file