link.js 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. 'use strict'
  2. const u = require('universalify').fromPromise
  3. const path = require('path')
  4. const fs = require('../fs')
  5. const mkdir = require('../mkdirs')
  6. const { pathExists } = require('../path-exists')
  7. const { areIdentical } = require('../util/stat')
  8. async function createLink (srcpath, dstpath) {
  9. let dstStat
  10. try {
  11. dstStat = await fs.lstat(dstpath)
  12. } catch {
  13. // ignore error
  14. }
  15. let srcStat
  16. try {
  17. srcStat = await fs.lstat(srcpath)
  18. } catch (err) {
  19. err.message = err.message.replace('lstat', 'ensureLink')
  20. throw err
  21. }
  22. if (dstStat && areIdentical(srcStat, dstStat)) return
  23. const dir = path.dirname(dstpath)
  24. const dirExists = await pathExists(dir)
  25. if (!dirExists) {
  26. await mkdir.mkdirs(dir)
  27. }
  28. await fs.link(srcpath, dstpath)
  29. }
  30. function createLinkSync (srcpath, dstpath) {
  31. let dstStat
  32. try {
  33. dstStat = fs.lstatSync(dstpath)
  34. } catch {}
  35. try {
  36. const srcStat = fs.lstatSync(srcpath)
  37. if (dstStat && areIdentical(srcStat, dstStat)) return
  38. } catch (err) {
  39. err.message = err.message.replace('lstat', 'ensureLink')
  40. throw err
  41. }
  42. const dir = path.dirname(dstpath)
  43. const dirExists = fs.existsSync(dir)
  44. if (dirExists) return fs.linkSync(srcpath, dstpath)
  45. mkdir.mkdirsSync(dir)
  46. return fs.linkSync(srcpath, dstpath)
  47. }
  48. module.exports = {
  49. createLink: u(createLink),
  50. createLinkSync
  51. }