symlink.js 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. 'use strict'
  2. const u = require('universalify').fromPromise
  3. const path = require('path')
  4. const fs = require('../fs')
  5. const { mkdirs, mkdirsSync } = require('../mkdirs')
  6. const { symlinkPaths, symlinkPathsSync } = require('./symlink-paths')
  7. const { symlinkType, symlinkTypeSync } = require('./symlink-type')
  8. const { pathExists } = require('../path-exists')
  9. const { areIdentical } = require('../util/stat')
  10. async function createSymlink (srcpath, dstpath, type) {
  11. let stats
  12. try {
  13. stats = await fs.lstat(dstpath)
  14. } catch { }
  15. if (stats && stats.isSymbolicLink()) {
  16. const [srcStat, dstStat] = await Promise.all([
  17. fs.stat(srcpath),
  18. fs.stat(dstpath)
  19. ])
  20. if (areIdentical(srcStat, dstStat)) return
  21. }
  22. const relative = await symlinkPaths(srcpath, dstpath)
  23. srcpath = relative.toDst
  24. const toType = await symlinkType(relative.toCwd, type)
  25. const dir = path.dirname(dstpath)
  26. if (!(await pathExists(dir))) {
  27. await mkdirs(dir)
  28. }
  29. return fs.symlink(srcpath, dstpath, toType)
  30. }
  31. function createSymlinkSync (srcpath, dstpath, type) {
  32. let stats
  33. try {
  34. stats = fs.lstatSync(dstpath)
  35. } catch { }
  36. if (stats && stats.isSymbolicLink()) {
  37. const srcStat = fs.statSync(srcpath)
  38. const dstStat = fs.statSync(dstpath)
  39. if (areIdentical(srcStat, dstStat)) return
  40. }
  41. const relative = symlinkPathsSync(srcpath, dstpath)
  42. srcpath = relative.toDst
  43. type = symlinkTypeSync(relative.toCwd, type)
  44. const dir = path.dirname(dstpath)
  45. const exists = fs.existsSync(dir)
  46. if (exists) return fs.symlinkSync(srcpath, dstpath, type)
  47. mkdirsSync(dir)
  48. return fs.symlinkSync(srcpath, dstpath, type)
  49. }
  50. module.exports = {
  51. createSymlink: u(createSymlink),
  52. createSymlinkSync
  53. }