-
Notifications
You must be signed in to change notification settings - Fork 234
/
index.js
executable file
·197 lines (159 loc) · 4.64 KB
/
index.js
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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
#!/usr/bin/env node
const fs = require('fs');
const path = require('path');
const chalk = require('chalk');
const mri = require('mri');
const tar = require('tar');
const homeOrTmp = require('home-or-tmp');
const { checkDirIsEmpty, error, exec, fetch, log, mkdirp, tryRequire } = require('./utils.js');
const base = path.join(homeOrTmp, '.degit');
const args = mri(process.argv.slice(2), {
alias: {
f: 'force',
c: 'cache',
v: 'verbose'
}
});
const [src, dest = '.'] = args._;
if (args.help || !src) {
const help = fs.readFileSync(path.join(__dirname, 'help.md'), 'utf-8')
.replace(/^(\s*)#+ (.+)/gm, (m, s, _) => s + chalk.bold(_))
.replace(/_([^_]+)_/g, (m, _) => chalk.underline(_))
.replace(/`([^`]+)`/g, (m, _) => chalk.cyan(_));
process.stdout.write(`\n${help}\n`);
return;
}
const supported = new Set(['github', 'gitlab', 'bitbucket']);
degit(src, dest);
async function degit(src, dest) {
if (args.verbose) log(`cloning ${src} to ${dest}`);
checkDirIsEmpty(dest, args);
const repo = parse(src);
const dir = path.join(base, repo.site, repo.user, repo.name);
const cached = tryRequire(path.join(dir, 'map.json')) || {};
const hash = args.cache ?
getHashFromCache(cached) :
await getHash(repo, cached);
if (!hash) {
// TODO 'did you mean...?'
error(`could not find commit hash for ${repo.ref}`);
}
const file = `${dir}/${hash}.tar.gz`;
const url = (
repo.site === 'gitlab' ? `${repo.url}/repository/archive.tar.gz?ref=${hash}` :
repo.site === 'bitbucket' ? `${repo.url}/get/${hash}.tar.gz` :
`${repo.url}/archive/${hash}.tar.gz`
);
try {
if (!args.cache) await downloadIfNotExists(url, file);
} catch (err) {
error(`could not download ${chalk.bold(url)}`, err);
}
updateCache(dir, repo, hash, cached);
mkdirp(dest);
await untar(file, dest);
log(`cloned ${chalk.bold(`${repo.user}/${repo.name}#${repo.ref}`)}${dest !== '.' ? ` to ${chalk.bold(dest)}` : ''}`);
}
function parse(src) {
const match = /^(?:https:\/\/([^/]+)\/|git@([^/]+):|([^/]+):)?([^/\s]+)\/([^/\s#]+)(?:#(.+))?/.exec(src);
if (!match) error(`could not parse ${src}`);
const site = (match[1] || match[2] || match[3] || 'github').replace(/\.(com|org)$/, '');
if (!supported.has(site)) error(`degit supports GitHub, GitLab and BitBucket`);
const user = match[4];
const name = match[5].replace(/\.git$/, '');
const ref = match[6] || 'master';
const url = `https://${site}.${site === 'bitbucket' ? 'org' : 'com'}/${user}/${name}`;
return { site, user, name, ref, url };
}
async function getHash(repo, cached) {
try {
const refs = await fetchRefs(repo);
if (args.verbose) log(`fetched ${refs.length} ${refs.length === 1 ? 'ref' : 'refs'}`);
return selectRef(refs, repo.ref);
} catch (err) {
return getHashFromCache(repo, cached);
}
}
function getHashFromCache(repo, cached) {
if (repo.ref in cached) {
const hash = cached[repo.ref];
log(`using cached commit hash ${hash}`);
return hash;
}
}
async function fetchRefs(repo) {
const { stdout } = await exec(`git ls-remote ${repo.url}`);
return stdout.split('\n').filter(Boolean).map(row => {
const [hash, ref] = row.split('\t');
if (ref === 'HEAD') {
return {
type: 'HEAD',
hash
};
}
const match = /refs\/(\w+)\/(.+)/.exec(ref);
if (!match) error(`could not parse ${ref}`);
return {
type: (
match[1] === 'heads' ? 'branch' :
match[1] === 'refs' ? 'ref' :
match[1]
),
name: match[2],
hash
};
});
}
function updateCache(dir, repo, hash, cached) {
if (cached[repo.ref] === hash) return;
const oldHash = cached[repo.ref];
if (oldHash) {
let used = false;
for (const key in cached) {
if (cached[key] === hash) {
used = true;
break;
}
}
if (!used) {
// we no longer need this tar file
try {
fs.unlinkSync(path.join(dir, `${oldHash}.tar.gz`));
} catch (err) {
// ignore
}
}
}
cached[repo.ref] = hash;
fs.writeFileSync(path.join(dir, 'map.json'), JSON.stringify(cached, null, ' '));
}
function selectRef(refs, selector) {
for (const ref of refs) {
if (ref.name === selector) {
if (args.verbose) log(`found matching commit hash: ${ref.hash}`);
return ref.hash;
}
}
if (selector.length < 8) return null;
for (const ref of refs) {
if (ref.hash.startsWith(selector)) return ref.hash;
}
}
async function downloadIfNotExists(url, file) {
try {
fs.statSync(file);
if (args.verbose) log(`${file} already exists locally`);
} catch (err) {
mkdirp(path.dirname(file));
if (args.verbose) log(`downloading ${url} to ${file}`);
return await fetch(url, file);
}
}
async function untar(file, dest) {
if (args.verbose) log(`extracting ${file} to ${dest}`);
return tar.extract({
file,
strip: 1,
C: dest
});
}