blob: c461324dc4acc59058bef3a7ada832af9d2ea5f7 [file] [log] [blame]
Primiano Tuccic8be6812021-02-09 18:08:49 +01001// Copyright (C) 2021 The Android Open Source Project
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15'use strict';
16
17// This script takes care of:
18// - The build process for the whole UI and the chrome extension.
19// - The HTTP dev-server with live-reload capabilities.
20// The reason why this is a hand-rolled script rather than a conventional build
21// system is keeping incremental build fast and maintaining the set of
22// dependencies contained.
23// The only way to keep incremental build fast (i.e. O(seconds) for the
24// edit-one-line -> reload html cycles) is to run both the TypeScript compiler
25// and the rollup bundler in --watch mode. Any other attempt, leads to O(10s)
26// incremental-build times.
27// This script allows mixing build tools that support --watch mode (tsc and
28// rollup) and auto-triggering-on-file-change rules via fs.watch().
29// When invoked without any argument (e.g., for production builds), this script
30// just runs all the build tasks serially. It doesn't to do any mtime-based
31// check, it always re-runs all the tasks.
32// When invoked with --watch, it mounts a pipeline of tasks based on fs.watch()
33// and runs them together with tsc --watch and rollup --watch.
34// The output directory structure is carefully crafted so that any change to UI
35// sources causes cascading triggers of the next steps.
36// The overall build graph looks as follows:
37// +----------------+ +-----------------------------+
38// | protos/*.proto |----->| pbjs out/tsc/gen/protos.js |--+
39// +----------------+ +-----------------------------+ |
40// +-----------------------------+ |
41// | pbts out/tsc/gen/protos.d.ts|<-+
42// +-----------------------------+
43// |
44// V +-------------------------+
45// +---------+ +-----+ | out/tsc/frontend/*.js |
46// | ui/*.ts |------------->| tsc |-> +-------------------------+ +--------+
47// +---------+ +-----+ | out/tsc/controller/*.js |-->| rollup |
48// ^ +-------------------------+ +--------+
49// +------------+ | out/tsc/engine/*.js | |
50// +-----------+ |*.wasm.js | +-------------------------+ |
51// |ninja *.cc |->|*.wasm.d.ts | |
52// +-----------+ |*.wasm |-----------------+ |
53// +------------+ | |
54// V V
55// +-----------+ +------+ +------------------------------------------------+
56// | ui/*.scss |->| scss |--->| Final out/dist/ dir |
57// +-----------+ +------+ +------------------------------------------------+
58// +----------------------+ | +----------+ +---------+ +--------------------+|
59// | src/assets/*.png | | | assets/ | |*.wasm.js| | frontend_bundle.js ||
60// +----------------------+ | | *.css | |*.wasm | +--------------------+|
61// | buildtools/typefaces |-->| | *.png | +---------+ |controller_bundle.js||
62// +----------------------+ | | *.woff2 | +--------------------+|
63// | buildtools/legacy_tv | | | tv.html | | engine_bundle.js ||
64// +----------------------+ | +----------+ +--------------------+|
65// +------------------------------------------------+
66
67const argparse = require('argparse');
68const child_process = require('child_process');
69const fs = require('fs');
70const http = require('http');
71const path = require('path');
72const pjoin = path.join;
73
74const ROOT_DIR = path.dirname(__dirname); // The repo root.
75const VERSION_SCRIPT = pjoin(ROOT_DIR, 'tools/write_version_header.py');
76
77const cfg = {
78 watch: false,
79 verbose: false,
80 debug: false,
81 startHttpServer: false,
82 wasmModules: ['trace_processor', 'trace_to_text'],
83 testConfigs: ['jest.unit.config.js'],
84
85 // The fields below will be changed by main() after cmdline parsing.
86 // Directory structure:
87 // out/xxx/ -> outDir : Root build dir, for both ninja/wasm and UI.
88 // ui/ -> outUiDir : UI dir. All outputs from this script.
89 // tsc/ -> outTscDir : Transpiled .ts -> .js.
90 // gen/ -> outGenDir : Auto-generated .ts/.js (e.g. protos).
91 // dist/ -> outDistDir : Final artifacts (JS bundles, assets).
92 // chrome_extension/ : Chrome extension.
93 outDir: pjoin(ROOT_DIR, 'out/ui'),
94 outUiDir: '',
95 outTscDir: '',
96 outGenDir: '',
97 outDistRootDir: '',
98 outDistDir: '',
99 outExtDir: '',
100};
101
102const RULES = [
103 {r: /ui\/src\/assets\/(index.html)/, f: copyIntoDistRoot},
104 {r: /ui\/src\/assets\/((.*)[.]png)/, f: copyAssets},
105 {r: /buildtools\/typefaces\/(.+[.]woff2)/, f: copyAssets},
106 {r: /buildtools\/catapult_trace_viewer\/(.+(js|html))/, f: copyAssets},
107 {r: /ui\/src\/assets\/.+[.]scss/, f: compileScss},
108 {r: /ui\/src\/assets\/.+[.]scss/, f: compileScss},
109 {r: /ui\/src\/chrome_extension\/.*/, f: copyExtensionAssets},
110 {r: /.*\/dist\/(?!service_worker).*/, f: genServiceWorkerDistHashes},
111 {r: /.*\/dist\/.*/, f: notifyLiveServer},
112];
113
114let tasks = [];
115let tasksTot = 0, tasksRan = 0;
116let serverStarted = false;
117let httpWatches = [];
118let tStart = Date.now();
119let subprocesses = [];
120
121function main() {
122 const parser = new argparse.ArgumentParser();
123 parser.addArgument('--out', {help: 'Output directory'});
124 parser.addArgument(['--watch', '-w'], {action: 'storeTrue'});
125 parser.addArgument(['--serve', '-s'], {action: 'storeTrue'});
126 parser.addArgument(['--verbose', '-v'], {action: 'storeTrue'});
127 parser.addArgument(['--no-build', '-n'], {action: 'storeTrue'});
128 parser.addArgument(['--no-wasm', '-W'], {action: 'storeTrue'});
129 parser.addArgument(['--run-tests', '-t'], {action: 'storeTrue'});
130 parser.addArgument(['--debug', '-d'], {action: 'storeTrue'});
131
132 const args = parser.parseArgs();
133 const clean = !args.no_build;
134 cfg.outDir = path.resolve(ensureDir(args.out || cfg.outDir));
135 cfg.outUiDir = ensureDir(pjoin(cfg.outDir, 'ui'), clean);
136 cfg.outExtDir = ensureDir(pjoin(cfg.outUiDir, 'chrome_extension'));
137 cfg.outDistRootDir = ensureDir(pjoin(cfg.outUiDir, 'dist'));
138 // TODO(primiano): for now distDir == distRootDir. In next CLs distDir will
139 // become dist/v1.2.3/.
140 cfg.outDistDir = cfg.outDistRootDir;
141 cfg.outTscDir = ensureDir(pjoin(cfg.outUiDir, 'tsc'));
142 cfg.outGenDir = ensureDir(pjoin(cfg.outUiDir, 'tsc/gen'));
143 cfg.watch = !!args.watch;
144 cfg.verbose = !!args.verbose;
145 cfg.debug = !!args.debug;
146 cfg.startHttpServer = args.serve;
147
148 process.on('SIGINT', () => {
149 console.log('\nSIGINT received. Killing all child processes and exiting');
150 for (const proc of subprocesses) {
151 if (proc) proc.kill('SIGINT');
152 }
153 process.exit(130); // 130 -> Same behavior of bash when killed by SIGINT.
154 });
155
156 // Check that deps are current before starting.
157 const installBuildDeps = pjoin(ROOT_DIR, 'tools/install-build-deps');
158 const depsArgs = ['--check-only', pjoin(cfg.outDir, '.check_deps'), '--ui'];
159 exec(installBuildDeps, depsArgs);
160
161 console.log('Entering', cfg.outDir);
162 process.chdir(cfg.outDir);
163
164 updateSymilnks(); // Links //ui/out -> //out/xxx/ui/
165
166 // Enqueue empty task. This is needed only for --no-build --serve. The HTTP
167 // server is started when the task queue reaches quiescence, but it takes at
168 // least one task for that.
169 addTask(() => {});
170
171 if (!args.no_build) {
172 buildWasm(args.no_wasm);
173 scanDir('ui/src/assets');
174 scanDir('ui/src/chrome_extension');
175 scanDir('buildtools/typefaces');
176 scanDir('buildtools/catapult_trace_viewer');
177 compileProtos();
178 genVersion();
179 transpileTsProject('ui');
180 bundleJs('rollup.config.js');
181
182 // ServiceWorker.
183 genServiceWorkerDistHashes();
184 transpileTsProject('ui/src/service_worker');
185 bundleJs('rollup-serviceworker.config.js');
186
187 // Watches the /dist. When changed:
188 // - Notifies the HTTP live reload clients.
189 // - Regenerates the ServiceWorker file map.
190 scanDir(cfg.outDistRootDir);
191 }
192
193 if (args.run_tests) {
194 runTests();
195 }
196}
197
198// -----------
199// Build rules
200// -----------
201
202function runTests() {
203 const args =
204 ['--rootDir', cfg.outTscDir, '--verbose', '--runInBand', '--forceExit'];
205 for (const cfgFile of cfg.testConfigs) {
206 args.push('--projects', pjoin(ROOT_DIR, 'ui/config', cfgFile));
207 }
208 if (cfg.watch) {
209 args.push('--watchAll');
210 addTask(execNode, ['jest', args, {async: true}]);
211 } else {
212 addTask(execNode, ['jest', args]);
213 }
214}
215
216function copyIntoDistRoot(src, dst) {
217 addTask(cp, [src, pjoin(cfg.outDistRootDir, dst)]);
218}
219
220function copyAssets(src, dst) {
221 addTask(cp, [src, pjoin(cfg.outDistDir, 'assets', dst)]);
222}
223
224function compileScss() {
225 const src = pjoin(ROOT_DIR, 'ui/src/assets/perfetto.scss');
226 const dst = pjoin(cfg.outDistDir, 'perfetto.css');
227 // In watch mode, don't exit(1) if scss fails. It can easily happen by
228 // having a typo in the css. It will still print an errror.
229 const noErrCheck = !!cfg.watch;
230 addTask(execNode, ['node-sass', ['--quiet', src, dst], {noErrCheck}]);
231}
232
233function compileProtos() {
234 const dstJs = pjoin(cfg.outGenDir, 'protos.js');
235 const dstTs = pjoin(cfg.outGenDir, 'protos.d.ts');
236 const inputs = [
237 'protos/perfetto/trace_processor/trace_processor.proto',
238 'protos/perfetto/common/trace_stats.proto',
239 'protos/perfetto/common/tracing_service_capabilities.proto',
240 'protos/perfetto/config/perfetto_config.proto',
241 'protos/perfetto/ipc/consumer_port.proto',
242 'protos/perfetto/ipc/wire_protocol.proto',
243 'protos/perfetto/metrics/metrics.proto',
244 ];
245 const pbjsArgs = [
246 '--force-number',
247 '-t',
248 'static-module',
249 '-w',
250 'commonjs',
251 '-p',
252 ROOT_DIR,
253 '-o',
254 dstJs
255 ].concat(inputs);
256 addTask(execNode, ['pbjs', pbjsArgs]);
257 const pbtsArgs = ['-p', ROOT_DIR, '-o', dstTs, dstJs];
258 addTask(execNode, ['pbts', pbtsArgs]);
259}
260
261// Generates a .ts source that defines the VERSION and SCM_REVISION constants.
262function genVersion() {
263 const cmd = 'python3';
264 const args =
265 [VERSION_SCRIPT, '--ts_out', pjoin(cfg.outGenDir, 'perfetto_version.ts')]
266 addTask(exec, [cmd, args]);
267}
268
269function updateSymilnks() {
270 mklink(cfg.outUiDir, pjoin(ROOT_DIR, 'ui/out'));
271 mklink(
272 pjoin(ROOT_DIR, 'ui/node_modules'), pjoin(cfg.outTscDir, 'node_modules'))
273}
274
275// Invokes ninja for building the {trace_processor, trace_to_text} Wasm modules.
276// It copies the .wasm directly into the out/dist/ dir, and the .js/.ts into
277// out/tsc/, so the typescript compiler and the bundler can pick them up.
278function buildWasm(skipWasmBuild) {
279 if (!skipWasmBuild) {
280 const gnArgs = ['gen', `--args=is_debug=${cfg.debug}`, cfg.outDir];
281 addTask(exec, [pjoin(ROOT_DIR, 'tools/gn'), gnArgs]);
282
283 const ninjaArgs = ['-C', cfg.outDir]
284 ninjaArgs.push(...cfg.wasmModules.map(x => `${x}_wasm`));
285 addTask(exec, [pjoin(ROOT_DIR, 'tools/ninja'), ninjaArgs]);
286 }
287
288 const wasmOutDir = pjoin(cfg.outDir, 'wasm');
289 for (const wasmMod of cfg.wasmModules) {
290 // The .wasm file goes directly into the dist dir (also .map in debug)
291 for (const ext of ['.wasm'].concat(cfg.debug ? ['.wasm.map'] : [])) {
292 const src = `${wasmOutDir}/${wasmMod}${ext}`;
293 addTask(cp, [src, pjoin(cfg.outDistDir, wasmMod + ext)]);
294 }
295 // The .js / .ts go into intermediates, they will be bundled by rollup.
296 for (const ext of ['.js', '.d.ts']) {
297 const fname = `${wasmMod}${ext}`;
298 addTask(cp, [pjoin(wasmOutDir, fname), pjoin(cfg.outGenDir, fname)]);
299 }
300 }
301}
302
303// This transpiles all the sources (frontend, controller, engine, extension) in
304// one go. The only project that has a dedicated invocation is service_worker.
305function transpileTsProject(project) {
306 const args = [
307 '--project',
308 pjoin(ROOT_DIR, project),
309 '--outDir',
310 cfg.outTscDir,
311 ];
312 if (cfg.watch) {
313 args.push('--watch', '--preserveWatchOutput');
314 addTask(execNode, ['tsc', args, {async: true}]);
315 } else {
316 addTask(execNode, ['tsc', args]);
317 }
318}
319
320// Creates the three {frontend, controller, engine}_bundle.js in one invocation.
321function bundleJs(cfgName) {
322 const rcfg = pjoin(ROOT_DIR, 'ui/config', cfgName)
323 const args = ['-c', rcfg, '--no-indent'];
324 args.push(...(cfg.verbose ? [] : ['--silent']));
325 if (cfg.watch) {
326 // --waitForBundleInput is so that we can run tsc --watch and rollup --watch
327 // together, without having to wait that tsc completes the first build.
328 args.push('--watch', '--waitForBundleInput', '--no-watch.clearScreen');
329 addTask(execNode, ['rollup', args, {async: true}]);
330 } else {
331 addTask(execNode, ['rollup', args]);
332 }
333}
334
335// Generates a map of {"dist_file_name" -> "sha256-01234"} used by the SW.
336function genServiceWorkerDistHashes() {
337 function write_ui_dist_file_map() {
338 const distFiles = [];
339 const skipRegex = /(service_worker\.js)|(\.map$)/;
340 walk(cfg.outDistDir, f => distFiles.push(f), skipRegex);
341 const dst = pjoin(cfg.outGenDir, 'dist_file_map.ts');
342 const cmd = 'python3';
343 const args = [
344 pjoin(ROOT_DIR, 'gn/standalone/write_ui_dist_file_map.py'),
345 '--out',
346 dst,
347 '--strip',
348 cfg.outDistDir,
349 ].concat(distFiles);
350 exec(cmd, args);
351 }
352 addTask(write_ui_dist_file_map, []);
353}
354
355function startServer() {
356 const port = 10000;
357 console.log(`Starting HTTP server on http://localhost:${port}`)
358 http.createServer(function(req, res) {
359 console.debug(req.method, req.url);
360 let uri = req.url.split('?', 1)[0];
361 if (uri.endsWith('/')) {
362 uri += 'index.html';
363 }
364
365 if (uri === '/live_reload') {
366 // Implements the Server-Side-Events protocol.
367 const head = {
368 'Content-Type': 'text/event-stream',
369 'Connection': 'keep-alive',
370 'Cache-Control': 'no-cache'
371 };
372 res.writeHead(200, head);
373 const arrayIdx = httpWatches.length;
374 // We never remove from the array, the delete leaves an undefined item
375 // around. It makes keeping track of the index easier at the cost of a
376 // small leak.
377 httpWatches.push(res);
378 req.on('close', () => delete httpWatches[arrayIdx]);
379 return;
380 }
381
382 const absPath = path.normalize(path.join(cfg.outDistRootDir, uri));
383 fs.readFile(absPath, function(err, data) {
384 if (err) {
385 res.writeHead(404);
386 res.end(JSON.stringify(err));
387 return;
388 }
389
390 const mimeMap = {
391 'html': 'text/html',
392 'css': 'text/css',
393 'js': 'application/javascript',
394 'wasm': 'application/wasm',
395 };
396 const ext = uri.split('.').pop();
397 const cType = mimeMap[ext] || 'octect/stream';
398 const head = {
399 'Content-Type': cType,
400 'Content-Length': data.length,
401 'Last-Modified': fs.statSync(absPath).mtime.toUTCString(),
402 'Cache-Control': 'no-cache',
403 };
404 res.writeHead(200, head);
405 res.end(data);
406 });
407 })
408 .listen(port);
409}
410
411// Called whenever a change in the out/dist directory is detected. It sends a
412// Server-Side-Event to the live_reload.ts script.
413function notifyLiveServer(changedFile) {
414 for (const cli of httpWatches) {
415 if (cli === undefined) continue;
416 cli.write(
417 'data: ' + path.relative(cfg.outDistRootDir, changedFile) + '\n\n');
418 }
419}
420
421function copyExtensionAssets() {
422 addTask(cp, [
423 pjoin(ROOT_DIR, 'ui/src/assets/logo-128.png'),
424 pjoin(cfg.outExtDir, 'logo-128.png')
425 ]);
426 addTask(cp, [
427 pjoin(ROOT_DIR, 'ui/src/chrome_extension/manifest.json'),
428 pjoin(cfg.outExtDir, 'manifest.json')
429 ]);
430}
431
432// -----------------------
433// Task chaining functions
434// -----------------------
435
436function addTask(func, args) {
437 const task = new Task(func, args);
438 for (const t of tasks) {
439 if (t.identity === task.identity) {
440 return;
441 }
442 }
443 tasks.push(task);
444 setTimeout(runTasks, 0);
445}
446
447function runTasks() {
448 const snapTasks = tasks.splice(0); // snap = std::move(tasks).
449 tasksTot += snapTasks.length;
450 for (const task of snapTasks) {
451 const DIM = '\u001b[2m';
452 const BRT = '\u001b[37m';
453 const RST = '\u001b[0m';
454 const ms = (new Date(Date.now() - tStart)).toISOString().slice(17, -1);
455 const ts = `[${DIM}${ms}${RST}]`;
456 const descr = task.description.substr(0, 80);
457 console.log(`${ts} ${BRT}${++tasksRan}/${tasksTot}${RST}\t${descr}`);
458 task.func.apply(/*this=*/ undefined, task.args);
459 }
460 // Start the web server once reaching quiescence.
461 if (tasks.length === 0 && !serverStarted && cfg.startHttpServer) {
462 serverStarted = true;
463 startServer();
464 }
465}
466
467// Executes all the RULES that match the given |absPath|.
468function scanFile(absPath) {
469 console.assert(fs.existsSync(absPath));
470 console.assert(path.isAbsolute(absPath));
471 const normPath = path.relative(ROOT_DIR, absPath);
472 for (const rule of RULES) {
473 const match = rule.r.exec(normPath);
474 if (!match || match[0] !== normPath) continue;
475 const captureGroup = match.length > 1 ? match[1] : undefined;
476 rule.f(absPath, captureGroup);
477 }
478}
479
480// Walks the passed |dir| recursively and, for each file, invokes the matching
481// RULES. If --watch is used, it also installs a fs.watch() and re-triggers the
482// matching RULES on each file change.
483function scanDir(dir, regex) {
484 const filterFn = regex ? absPath => regex.test(absPath) : () => true;
485 const absDir = path.isAbsolute(dir) ? dir : pjoin(ROOT_DIR, dir);
486 // Add a fs watch if in watch mode.
487 if (cfg.watch) {
488 fs.watch(absDir, {recursive: true}, (_eventType, fileName) => {
489 const filePath = pjoin(absDir, fileName);
490 if (!filterFn(filePath)) return;
491 if (cfg.verbose) {
492 console.log('File change detected', _eventType, filePath);
493 }
494 if (fs.existsSync(filePath)) {
495 scanFile(filePath, filterFn);
496 }
497 });
498 }
499 walk(absDir, f => {
500 if (filterFn(f)) scanFile(f);
501 });
502}
503
504function exec(cmd, args, opts) {
505 opts = opts || {};
506 opts.stdout = opts.stdout || 'inherit';
507 if (cfg.verbose) console.log(`${cmd} ${args.join(' ')}\n`);
508 const spwOpts = {cwd: cfg.outDir, stdio: ['ignore', opts.stdout, 'inherit']};
509 const checkExitCode = (code, signal) => {
510 if (signal === 'SIGINT' || signal === 'SIGTERM') return;
511 if (code !== 0 && !opts.noErrCheck) {
512 console.error(`${cmd} ${args.join(' ')} failed with code ${code}`);
513 process.exit(1);
514 }
515 };
516 if (opts.async) {
517 const proc = child_process.spawn(cmd, args, spwOpts);
518 const procIndex = subprocesses.length;
519 subprocesses.push(proc);
520 return new Promise((resolve, _reject) => {
521 proc.on('exit', (code, signal) => {
522 delete subprocesses[procIndex];
523 checkExitCode(code, signal);
524 resolve();
525 });
526 });
527 } else {
528 const spawnRes = child_process.spawnSync(cmd, args, spwOpts);
529 checkExitCode(spawnRes.status, spawnRes.signal);
530 return spawnRes;
531 }
532}
533
534function execNode(module, args, opts) {
535 const modPath = pjoin(ROOT_DIR, 'ui/node_modules/.bin', module);
536 const nodeBin = pjoin(ROOT_DIR, 'tools/node');
537 args = [modPath].concat(args || []);
538 const argsJson = JSON.stringify(args);
539 return exec(nodeBin, args, opts);
540}
541
542// ------------------------------------------
543// File system & subprocess utility functions
544// ------------------------------------------
545
546class Task {
547 constructor(func, args) {
548 this.func = func;
549 this.args = args || [];
550 // |identity| is used to dedupe identical tasks in the queue.
551 this.identity = JSON.stringify([this.func.name, this.args]);
552 }
553
554 get description() {
555 const ret = this.func.name.startsWith('exec') ? [] : [this.func.name];
556 const flattenedArgs = [].concat.apply([], this.args);
557 for (const arg of flattenedArgs) {
558 const argStr = `${arg}`;
559 if (argStr.startsWith('/')) {
560 ret.push(path.relative(cfg.outDir, arg));
561 } else {
562 ret.push(argStr);
563 }
564 }
565 return ret.join(' ');
566 }
567}
568
569function walk(dir, callback, skipRegex) {
570 for (const child of fs.readdirSync(dir)) {
571 const childPath = pjoin(dir, child);
572 const stat = fs.lstatSync(childPath);
573 if (skipRegex !== undefined && skipRegex.test(child)) continue;
574 if (stat.isDirectory()) {
575 walk(childPath, callback, skipRegex);
576 } else if (!stat.isSymbolicLink()) {
577 callback(childPath);
578 }
579 }
580}
581
582function ensureDir(dirPath, clean) {
583 const exists = fs.existsSync(dirPath);
584 if (exists && clean) {
585 console.log('rm', dirPath);
586 fs.rmSync(dirPath, {recursive: true});
587 }
588 if (!exists || clean) fs.mkdirSync(dirPath, {recursive: true});
589 return dirPath;
590}
591
592function cp(src, dst) {
593 ensureDir(path.dirname(dst));
594 if (cfg.verbose) {
595 console.log(
596 'cp', path.relative(ROOT_DIR, src), '->', path.relative(ROOT_DIR, dst));
597 }
598 fs.copyFileSync(src, dst);
599}
600
601function mklink(src, dst) {
602 // If the symlink already points to the right place don't touch it. This is
603 // to avoid changing the mtime of the ui/ dir when unnecessary.
604 if (fs.existsSync(dst)) {
605 if (fs.lstatSync(dst).isSymbolicLink() && fs.readlinkSync(dst) === src) {
606 return;
607 } else {
608 fs.unlinkSync(dst);
609 }
610 }
611 fs.symlinkSync(src, dst);
612}
613
614main();