-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathlink.ts
207 lines (172 loc) · 5.93 KB
/
link.ts
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
import chalk from 'chalk';
import chokidar, { FSWatcher } from 'chokidar';
import execa, { ExecaChildProcess } from 'execa';
import fsExtra from 'fs-extra';
import ora from 'ora';
import path from 'path';
import { mergeDeepRight } from 'ramda';
import { cleanups } from './cleanup';
import { Package, resolvePackage } from './package';
import { Project, resolveProject } from './project';
import { markAsLinked } from './state';
const { bold, cyan, yellow } = chalk;
export async function link(packagePaths: string[], cwd: string) {
let firstInstallation = true;
let currentInstallation: Installation | null = null;
console.clear();
const project = resolveProject(cwd);
cleanups.add(() => fsExtra.remove(project.cachePath));
const packages = packagePaths.map(resolvePackage);
const syncer = createSyncer(packages, project);
await ensureDependencyOn(packages, project);
const specsToWatch = packages.map(pkg => pkg.spec.path);
chokidar.watch(specsToWatch).on('change', installAndSync);
installAndSync();
async function installAndSync() {
if (currentInstallation == null) {
syncer.stop();
if (firstInstallation === false) console.clear();
firstInstallation = false;
currentInstallation = installPackages(packages, project);
const result = await currentInstallation.result;
if (result === 'success') {
syncer.start();
}
currentInstallation = null;
} else {
await currentInstallation.cancel();
currentInstallation = null;
installAndSync();
}
}
}
async function ensureDependencyOn(packages: Package[], project: Project) {
const spinner = ora({ text: cyan('Checking project dependencies') }).start();
try {
await Promise.all(
packages.map(({ name }) =>
execa('yarn', ['why', name], { cwd: project.root }).then(({ stderr }) => {
if (stderr != null && stderr !== '') {
throw Error(
yellow(`${bold(name)} is not a project's dependency!\n`) +
`Please add this package as dependency and run ${bold('yarn install')}.`
);
}
})
)
);
} catch (e) {
spinner.fail(e.message);
process.exit(1);
}
spinner.succeed();
}
function installPackages(packages: Package[], project: Project): Installation {
let childProcess: ExecaChildProcess;
const spinner = ora({ text: cyan('Installing transitive dependencies') }).start();
return {
result: run(),
cancel: async () => {
childProcess.cancel();
await childProcess.catch(() => null);
}
};
async function run(): Promise<InstallationResult> {
const originalProjectSpec = project.spec.get();
const cleanup = () => project.spec.set(originalProjectSpec);
cleanups.add(cleanup);
try {
const resolutions = copyPackagesToCache(packages, project);
const updatedProjectSpec = mergeDeepRight(originalProjectSpec, { resolutions });
project.spec.set(updatedProjectSpec);
childProcess = execa('yarn', ['install', '--force', '--pure-lockfile', '--non-interactive']);
await childProcess;
cleanups.delete(cleanup);
cleanup();
spinner.succeed();
return 'success';
} catch (e) {
cleanups.delete(cleanup);
cleanup();
if (e.isCanceled) {
spinner.fail('Installation aborted due to change in package manifest.');
return 'canceled';
}
spinner.fail('Installation failed with the following error:');
console.error(e.message);
console.log(
yellow.inverse(
"Process will try to reinstall transitive dependencies on next change in linked package's manifest."
)
);
return 'error';
}
}
}
interface Installation {
cancel(): Promise<void>;
readonly result: Promise<InstallationResult>;
}
type InstallationResult = 'success' | 'canceled' | 'error';
function createSyncer(packages: Package[], project: Project) {
let watchers: FSWatcher[] = [];
return {
start() {
if (watchers.length > 0) return;
watchers = packages.map(pkg =>
chokidar
.watch(pkg.root, { ignored: toWatchIgnoredPaths(pkg) })
.on('all', (event, eventPath) => {
if (eventPath === pkg.root) return;
const relativeEventPath = path.relative(pkg.root, eventPath);
const target = `${project.root}/node_modules/${pkg.name}/${relativeEventPath}`;
switch (event) {
case 'add':
case 'change':
fsExtra.copy(eventPath, target).catch(console.error);
return;
case 'addDir':
fsExtra.ensureDir(target).catch(console.error);
return;
case 'unlink':
case 'unlinkDir':
fsExtra.remove(target).catch(console.error);
return;
default:
throw Error('Unexpected FS event!');
}
})
);
markAsLinked(packages, project);
console.info('🚧 Keeping packages in sync...');
},
stop() {
watchers.forEach(watcher => watcher.close());
watchers = [];
markAsLinked([], project);
}
};
}
function toWatchIgnoredPaths(pkg: Package) {
// TODO: read .npmignore or .gitignore
// TODO: read "files" property in package's spec
// TODO: make sure you restart watchers when .ignore files change
return [pkg.spec.path, '**/.git/**', '**/node_modules/**'];
}
function copyPackagesToCache(
packages: Package[],
project: Project
): { [packageName: string]: string } {
fsExtra.removeSync(project.cachePath);
const resolutions = packages.reduce(
(result, pkg) => ({ ...result, [pkg.name]: `${project.cachePath}/${pkg.name}` }),
{}
);
// todo: copy only non-ignored files & package.json
packages.forEach(pkg => {
fsExtra.copySync(pkg.root, resolutions[pkg.name], {
filter: (src, des) => !src.includes('/node_modules') && !src.includes('/.git')
});
});
return resolutions;
}