1 | var fs = require('fs');
|
2 | var path = require('path');
|
3 | var common = require('./common');
|
4 |
|
5 | common.register('ln', _ln, {
|
6 | cmdOptions: {
|
7 | 's': 'symlink',
|
8 | 'f': 'force',
|
9 | },
|
10 | });
|
11 |
|
12 |
|
13 |
|
14 |
|
15 |
|
16 |
|
17 |
|
18 |
|
19 |
|
20 |
|
21 |
|
22 |
|
23 |
|
24 |
|
25 |
|
26 |
|
27 |
|
28 | function _ln(options, source, dest) {
|
29 | if (!source || !dest) {
|
30 | common.error('Missing <source> and/or <dest>');
|
31 | }
|
32 |
|
33 | source = String(source);
|
34 | var sourcePath = path.normalize(source).replace(RegExp(path.sep + '$'), '');
|
35 | var isAbsolute = (path.resolve(source) === sourcePath);
|
36 | dest = path.resolve(process.cwd(), String(dest));
|
37 |
|
38 | if (fs.existsSync(dest)) {
|
39 | if (!options.force) {
|
40 | common.error('Destination file exists', { continue: true });
|
41 | }
|
42 |
|
43 | fs.unlinkSync(dest);
|
44 | }
|
45 |
|
46 | if (options.symlink) {
|
47 | var isWindows = process.platform === 'win32';
|
48 | var linkType = isWindows ? 'file' : null;
|
49 | var resolvedSourcePath = isAbsolute ? sourcePath : path.resolve(process.cwd(), path.dirname(dest), source);
|
50 | if (!fs.existsSync(resolvedSourcePath)) {
|
51 | common.error('Source file does not exist', { continue: true });
|
52 | } else if (isWindows && common.statFollowLinks(resolvedSourcePath).isDirectory()) {
|
53 | linkType = 'junction';
|
54 | }
|
55 |
|
56 | try {
|
57 | fs.symlinkSync(linkType === 'junction' ? resolvedSourcePath : source, dest, linkType);
|
58 | } catch (err) {
|
59 | common.error(err.message);
|
60 | }
|
61 | } else {
|
62 | if (!fs.existsSync(source)) {
|
63 | common.error('Source file does not exist', { continue: true });
|
64 | }
|
65 | try {
|
66 | fs.linkSync(source, dest);
|
67 | } catch (err) {
|
68 | common.error(err.message);
|
69 | }
|
70 | }
|
71 | return '';
|
72 | }
|
73 | module.exports = _ln;
|