1 | 'use strict'
|
---|
2 |
|
---|
3 | const u = require('universalify').fromCallback
|
---|
4 | const path = require('path')
|
---|
5 | const fs = require('graceful-fs')
|
---|
6 | const _mkdirs = require('../mkdirs')
|
---|
7 | const mkdirs = _mkdirs.mkdirs
|
---|
8 | const mkdirsSync = _mkdirs.mkdirsSync
|
---|
9 |
|
---|
10 | const _symlinkPaths = require('./symlink-paths')
|
---|
11 | const symlinkPaths = _symlinkPaths.symlinkPaths
|
---|
12 | const symlinkPathsSync = _symlinkPaths.symlinkPathsSync
|
---|
13 |
|
---|
14 | const _symlinkType = require('./symlink-type')
|
---|
15 | const symlinkType = _symlinkType.symlinkType
|
---|
16 | const symlinkTypeSync = _symlinkType.symlinkTypeSync
|
---|
17 |
|
---|
18 | const pathExists = require('../path-exists').pathExists
|
---|
19 |
|
---|
20 | function createSymlink (srcpath, dstpath, type, callback) {
|
---|
21 | callback = (typeof type === 'function') ? type : callback
|
---|
22 | type = (typeof type === 'function') ? false : type
|
---|
23 |
|
---|
24 | pathExists(dstpath, (err, destinationExists) => {
|
---|
25 | if (err) return callback(err)
|
---|
26 | if (destinationExists) return callback(null)
|
---|
27 | symlinkPaths(srcpath, dstpath, (err, relative) => {
|
---|
28 | if (err) return callback(err)
|
---|
29 | srcpath = relative.toDst
|
---|
30 | symlinkType(relative.toCwd, type, (err, type) => {
|
---|
31 | if (err) return callback(err)
|
---|
32 | const dir = path.dirname(dstpath)
|
---|
33 | pathExists(dir, (err, dirExists) => {
|
---|
34 | if (err) return callback(err)
|
---|
35 | if (dirExists) return fs.symlink(srcpath, dstpath, type, callback)
|
---|
36 | mkdirs(dir, err => {
|
---|
37 | if (err) return callback(err)
|
---|
38 | fs.symlink(srcpath, dstpath, type, callback)
|
---|
39 | })
|
---|
40 | })
|
---|
41 | })
|
---|
42 | })
|
---|
43 | })
|
---|
44 | }
|
---|
45 |
|
---|
46 | function createSymlinkSync (srcpath, dstpath, type) {
|
---|
47 | const destinationExists = fs.existsSync(dstpath)
|
---|
48 | if (destinationExists) return undefined
|
---|
49 |
|
---|
50 | const relative = symlinkPathsSync(srcpath, dstpath)
|
---|
51 | srcpath = relative.toDst
|
---|
52 | type = symlinkTypeSync(relative.toCwd, type)
|
---|
53 | const dir = path.dirname(dstpath)
|
---|
54 | const exists = fs.existsSync(dir)
|
---|
55 | if (exists) return fs.symlinkSync(srcpath, dstpath, type)
|
---|
56 | mkdirsSync(dir)
|
---|
57 | return fs.symlinkSync(srcpath, dstpath, type)
|
---|
58 | }
|
---|
59 |
|
---|
60 | module.exports = {
|
---|
61 | createSymlink: u(createSymlink),
|
---|
62 | createSymlinkSync
|
---|
63 | }
|
---|