"use strict";

var _forEachInstanceProperty = require("@babel/runtime-corejs3/core-js-stable/instance/for-each");

var _Object$defineProperty = require("@babel/runtime-corejs3/core-js-stable/object/define-property");

var _interopRequireDefault = require("@babel/runtime-corejs3/helpers/interopRequireDefault");

_Object$defineProperty(exports, "__esModule", {
  value: true
});

exports.unlinkLinks = exports.linkLinks = void 0;

var _fs = require("fs");

var _os = _interopRequireDefault(require("os"));

var _path = require("path");

var _lodash = require("lodash");

var _rimraf = _interopRequireDefault(require("rimraf"));

/*
Slimmed down version of linklocal package that can be used with workspaces (doesn't require a package.json to work)
 */
// Use junctions on Windows
const symlinkType = _os.default.platform() === 'win32' ? 'junction' : 'dir';

const exists = (filepath, done) => {
  (0, _fs.lstat)(filepath, (err, stat) => {
    if (err) {
      if (err.code !== 'ENOENT') return done(err);
      return done(null, false);
    }

    done(null, !!stat);
  });
};

const isSymbolicLink = (filepath, done) => {
  exists(filepath, (err, doesExist) => {
    if (err) return done(err);
    if (!doesExist) return done(null, false);
    (0, _fs.lstat)(filepath, (err, stat) => {
      if (err) return done(err);
      return done(null, stat.isSymbolicLink());
    });
  });
};

const unlinkLinks = (links, done) => {
  let counter = 1;
  (0, _forEachInstanceProperty(_lodash))(links, link => {
    isSymbolicLink(link.from, (err, isSymlink) => {
      if (err) throw new Error(err);
      const remove = isSymlink ? _fs.unlink : _rimraf.default;
      return remove(link.from, err => {
        if (err) return done('Error removing ' + link.from + ':\n' + err.message);
        if (counter === links.length) done();
        counter++;
      });
    });
  });
};

exports.unlinkLinks = unlinkLinks;

const linkLinks = (links, done) => {
  unlinkLinks(links, err => {
    let counter = 1;
    (0, _forEachInstanceProperty(_lodash))(links, link => {
      if (symlinkType !== 'junction') {
        link.to = (0, _path.relative)((0, _path.dirname)(link.from), link.to);
      }

      (0, _fs.symlink)(link.to, link.from, symlinkType, err => {
        if (err) return done('Error linking ' + link.from + ' to ' + link.to + ':\n' + err.message);
        if (counter === links.length) done(null, links);
        counter++;
      });
    });
  });
};

exports.linkLinks = linkLinks;