UNPKG

1.87 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//@ Available options:
15//@
16//@ + `-s`: symlink
17//@ + `-f`: force
18//@
19//@ Examples:
20//@
21//@ ```javascript
22//@ ln('file', 'newlink');
23//@ ln('-sf', 'file', 'existing');
24//@ ```
25//@
26//@ Links source to dest. Use -f to force the link, should dest already exist.
27function _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}
72module.exports = _ln;