-
Notifications
You must be signed in to change notification settings - Fork 2.7k
/
Copy pathgit-fetcher.js
265 lines (222 loc) · 8.22 KB
/
git-fetcher.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
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
/* @flow */
import {SecurityError, MessageError} from '../errors.js';
import type {FetchedOverride} from '../types.js';
import BaseFetcher from './base-fetcher.js';
import Git from '../util/git.js';
import * as fsUtil from '../util/fs.js';
import * as constants from '../constants.js';
import * as crypto from '../util/crypto.js';
import {install} from '../cli/commands/install.js';
import Lockfile from '../lockfile';
import Config from '../config.js';
import {packTarball} from '../cli/commands/pack.js';
const tarFs = require('tar-fs');
const url = require('url');
const path = require('path');
const fs = require('fs');
const invariant = require('invariant');
const PACKED_FLAG = '1';
export default class GitFetcher extends BaseFetcher {
async setupMirrorFromCache(): Promise<?string> {
const tarballMirrorPath = this.getTarballMirrorPath();
const tarballCachePath = this.getTarballCachePath();
if (tarballMirrorPath == null) {
return;
}
if (!await fsUtil.exists(tarballMirrorPath) && (await fsUtil.exists(tarballCachePath))) {
// The tarball doesn't exists in the offline cache but does in the cache; we import it to the mirror
await fsUtil.mkdirp(path.dirname(tarballMirrorPath));
await fsUtil.copy(tarballCachePath, tarballMirrorPath, this.reporter);
}
}
getTarballMirrorPath({withCommit = true}: {withCommit: boolean} = {}): ?string {
const {pathname} = url.parse(this.reference);
if (pathname == null) {
return null;
}
const hash = this.hash;
let packageFilename = withCommit && hash ? `${path.basename(pathname)}-${hash}` : `${path.basename(pathname)}`;
if (packageFilename.startsWith(':')) {
packageFilename = packageFilename.substr(1);
}
return this.config.getOfflineMirrorPath(packageFilename);
}
getTarballCachePath(): string {
return path.join(this.dest, constants.TARBALL_FILENAME);
}
*getLocalPaths(override: ?string): Generator<?string, void, void> {
if (override) {
yield path.resolve(this.config.cwd, override);
}
yield this.getTarballMirrorPath();
yield this.getTarballMirrorPath({
withCommit: false,
});
yield this.getTarballCachePath();
}
async fetchFromLocal(override: ?string): Promise<FetchedOverride> {
const {stream, triedPaths} = await fsUtil.readFirstAvailableStream(this.getLocalPaths(override));
return new Promise((resolve, reject) => {
if (!stream) {
reject(new MessageError(this.reporter.lang('tarballNotInNetworkOrCache', this.reference, triedPaths)));
return;
}
invariant(stream, 'cachedStream should be available at this point');
// $FlowFixMe - This is available https://nodejs.org/api/fs.html#fs_readstream_path
const tarballPath = stream.path;
const untarStream = this._createUntarStream(this.dest);
const hashStream = new crypto.HashStream();
stream
.pipe(hashStream)
.pipe(untarStream)
.on('finish', () => {
const expectHash = this.hash;
invariant(expectHash, 'Commit hash required');
const actualHash = hashStream.getHash();
// This condition is disabled because "expectHash" actually is the commit hash
// This is a design issue that we'll need to fix (https://github.com/yarnpkg/yarn/pull/3449)
if (true || !expectHash || expectHash === actualHash) {
resolve({
hash: expectHash,
});
} else {
reject(
new SecurityError(
this.config.reporter.lang(
'fetchBadHashWithPath',
this.packageName,
this.remote.reference,
expectHash,
actualHash,
),
),
);
}
})
.on('error', function(err) {
reject(new MessageError(this.reporter.lang('fetchErrorCorrupt', err.message, tarballPath)));
});
});
}
async hasPrepareScript(git: Git): Promise<boolean> {
const manifestFile = await git.getFile('package.json');
if (manifestFile) {
const scripts = JSON.parse(manifestFile).scripts;
const hasPrepareScript = Boolean(scripts && scripts.prepare);
return hasPrepareScript;
}
return false;
}
async fetchFromExternal(): Promise<FetchedOverride> {
const hash = this.hash;
invariant(hash, 'Commit hash required');
const gitUrl = Git.npmUrlToGitUrl(this.reference);
const git = new Git(this.config, gitUrl, hash);
await git.init();
if (await this.hasPrepareScript(git)) {
await this.fetchFromInstallAndPack(git);
} else {
await this.fetchFromGitArchive(git);
}
return {
hash,
};
}
async fetchFromInstallAndPack(git: Git): Promise<void> {
const prepareDirectory = this.config.getTemp(`${crypto.hash(git.gitUrl.repository)}.${git.hash}.prepare`);
await fsUtil.unlink(prepareDirectory);
await git.clone(prepareDirectory);
const [prepareConfig, prepareLockFile] = await Promise.all([
Config.create(
{
binLinks: true,
cwd: prepareDirectory,
disablePrepublish: true,
},
this.reporter,
),
Lockfile.fromDirectory(prepareDirectory, this.reporter),
]);
await install(prepareConfig, this.reporter, {}, prepareLockFile);
const tarballMirrorPath = this.getTarballMirrorPath();
const tarballCachePath = this.getTarballCachePath();
if (tarballMirrorPath) {
await this._packToTarball(prepareConfig, tarballMirrorPath);
}
if (tarballCachePath) {
await this._packToTarball(prepareConfig, tarballCachePath);
}
await this._packToDirectory(prepareConfig, this.dest);
await fsUtil.unlink(prepareDirectory);
}
async _packToTarball(config: Config, path: string): Promise<void> {
const tarballStream = await this._createTarballStream(config);
await new Promise((resolve, reject) => {
const writeStream = fs.createWriteStream(path);
tarballStream.on('error', reject);
writeStream.on('error', reject);
writeStream.on('end', resolve);
writeStream.on('open', () => {
tarballStream.pipe(writeStream);
});
writeStream.once('finish', resolve);
});
}
async _packToDirectory(config: Config, dest: string): Promise<void> {
const tarballStream = await this._createTarballStream(config);
await new Promise((resolve, reject) => {
const untarStream = this._createUntarStream(dest);
tarballStream.on('error', reject);
untarStream.on('error', reject);
untarStream.on('end', resolve);
untarStream.once('finish', resolve);
tarballStream.pipe(untarStream);
});
}
_createTarballStream(config: Config): Promise<stream$Duplex> {
let savedPackedHeader = false;
return packTarball(config, {
mapHeader(header: Object): Object {
if (!savedPackedHeader) {
savedPackedHeader = true;
header.pax = header.pax || {};
// add a custom data on the first header
// in order to distinguish a tar from "git archive" and a tar from "pack" command
header.pax.packed = PACKED_FLAG;
}
return header;
},
});
}
_createUntarStream(dest: string): stream$Writable {
const PREFIX = 'package/';
let isPackedTarball = undefined;
return tarFs.extract(dest, {
dmode: 0o555, // all dirs should be readable
fmode: 0o444, // all files should be readable
chown: false, // don't chown. just leave as it is
map: header => {
if (isPackedTarball === undefined) {
isPackedTarball = header.pax && header.pax.packed === PACKED_FLAG;
}
if (isPackedTarball) {
header.name = header.name.substr(PREFIX.length);
}
},
});
}
async fetchFromGitArchive(git: Git): Promise<void> {
await git.clone(this.dest);
const tarballMirrorPath = this.getTarballMirrorPath();
const tarballCachePath = this.getTarballCachePath();
if (tarballMirrorPath) {
await git.archive(tarballMirrorPath);
}
if (tarballCachePath) {
await git.archive(tarballCachePath);
}
}
_fetch(): Promise<FetchedOverride> {
return this.fetchFromLocal().catch(err => this.fetchFromExternal());
}
}