UNPKG

1.89 kBJavaScriptView Raw
1var fs = require('fs');
2var path = require('path');
3var common = require('./common');
4
5common.register('ln', _ln, {
6 cmdOptions: {
7 's': 'symlink',
8 'f': 'force',
9 },
10});
11
12//@
13//@ ### ln([options,] source, dest)
14//@
15//@ Available options:
16//@
17//@ + `-s`: symlink
18//@ + `-f`: force
19//@
20//@ Examples:
21//@
22//@ ```javascript
23//@ ln('file', 'newlink');
24//@ ln('-sf', 'file', 'existing');
25//@ ```
26//@
27//@ Links `source` to `dest`. Use `-f` to force the link, should `dest` already exist.
28function _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}
73module.exports = _ln;