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 | function _ln(options, source, dest) {
|
28 | if (!source || !dest) {
|
29 | common.error('Missing <source> and/or <dest>');
|
30 | }
|
31 |
|
32 | source = String(source);
|
33 | var sourcePath = path.normalize(source).replace(RegExp(path.sep + '$'), '');
|
34 | var isAbsolute = (path.resolve(source) === sourcePath);
|
35 | dest = path.resolve(process.cwd(), String(dest));
|
36 |
|
37 | if (fs.existsSync(dest)) {
|
38 | if (!options.force) {
|
39 | common.error('Destination file exists', { continue: true });
|
40 | }
|
41 |
|
42 | fs.unlinkSync(dest);
|
43 | }
|
44 |
|
45 | if (options.symlink) {
|
46 | var isWindows = process.platform === 'win32';
|
47 | var linkType = isWindows ? 'file' : null;
|
48 | var resolvedSourcePath = isAbsolute ? sourcePath : path.resolve(process.cwd(), path.dirname(dest), source);
|
49 | if (!fs.existsSync(resolvedSourcePath)) {
|
50 | common.error('Source file does not exist', { continue: true });
|
51 | } else if (isWindows && common.statFollowLinks(resolvedSourcePath).isDirectory()) {
|
52 | linkType = 'junction';
|
53 | }
|
54 |
|
55 | try {
|
56 | fs.symlinkSync(linkType === 'junction' ? resolvedSourcePath : source, dest, linkType);
|
57 | } catch (err) {
|
58 | common.error(err.message);
|
59 | }
|
60 | } else {
|
61 | if (!fs.existsSync(source)) {
|
62 | common.error('Source file does not exist', { continue: true });
|
63 | }
|
64 | try {
|
65 | fs.linkSync(source, dest);
|
66 | } catch (err) {
|
67 | common.error(err.message);
|
68 | }
|
69 | }
|
70 | return '';
|
71 | }
|
72 | module.exports = _ln;
|