1 | 'use strict'
|
---|
2 |
|
---|
3 | const u = require('universalify').fromCallback
|
---|
4 | const path = require('path')
|
---|
5 | const fs = require('graceful-fs')
|
---|
6 | const mkdir = require('../mkdirs')
|
---|
7 | const pathExists = require('../path-exists').pathExists
|
---|
8 |
|
---|
9 | function createLink (srcpath, dstpath, callback) {
|
---|
10 | function makeLink (srcpath, dstpath) {
|
---|
11 | fs.link(srcpath, dstpath, err => {
|
---|
12 | if (err) return callback(err)
|
---|
13 | callback(null)
|
---|
14 | })
|
---|
15 | }
|
---|
16 |
|
---|
17 | pathExists(dstpath, (err, destinationExists) => {
|
---|
18 | if (err) return callback(err)
|
---|
19 | if (destinationExists) return callback(null)
|
---|
20 | fs.lstat(srcpath, (err) => {
|
---|
21 | if (err) {
|
---|
22 | err.message = err.message.replace('lstat', 'ensureLink')
|
---|
23 | return callback(err)
|
---|
24 | }
|
---|
25 |
|
---|
26 | const dir = path.dirname(dstpath)
|
---|
27 | pathExists(dir, (err, dirExists) => {
|
---|
28 | if (err) return callback(err)
|
---|
29 | if (dirExists) return makeLink(srcpath, dstpath)
|
---|
30 | mkdir.mkdirs(dir, err => {
|
---|
31 | if (err) return callback(err)
|
---|
32 | makeLink(srcpath, dstpath)
|
---|
33 | })
|
---|
34 | })
|
---|
35 | })
|
---|
36 | })
|
---|
37 | }
|
---|
38 |
|
---|
39 | function createLinkSync (srcpath, dstpath) {
|
---|
40 | const destinationExists = fs.existsSync(dstpath)
|
---|
41 | if (destinationExists) return undefined
|
---|
42 |
|
---|
43 | try {
|
---|
44 | fs.lstatSync(srcpath)
|
---|
45 | } catch (err) {
|
---|
46 | err.message = err.message.replace('lstat', 'ensureLink')
|
---|
47 | throw err
|
---|
48 | }
|
---|
49 |
|
---|
50 | const dir = path.dirname(dstpath)
|
---|
51 | const dirExists = fs.existsSync(dir)
|
---|
52 | if (dirExists) return fs.linkSync(srcpath, dstpath)
|
---|
53 | mkdir.mkdirsSync(dir)
|
---|
54 |
|
---|
55 | return fs.linkSync(srcpath, dstpath)
|
---|
56 | }
|
---|
57 |
|
---|
58 | module.exports = {
|
---|
59 | createLink: u(createLink),
|
---|
60 | createLinkSync
|
---|
61 | }
|
---|