"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.polish = polish;
exports.jsonFileFunctions = void 0;

var _mergeWith = _interopRequireDefault(require("lodash/mergeWith"));

var _jsonStableStringify = _interopRequireDefault(require("json-stable-stringify"));

var _getPrettier = require("../util/get-prettier");

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function mergeWithArrayReplacement(source, target) {
  // Replace arrays rather than merging them
  if (Array.isArray(target) && Array.isArray(source)) {
    return target;
  }
}

function merge(source, target) {
  // Default object merge behavior is covered by lodash's
  // merge function. Properties will be merged deeply,
  // newer arrays will replace existing ones
  return (0, _mergeWith.default)({}, source !== null && source !== void 0 ? source : {}, target, mergeWithArrayReplacement);
}

function polish(source, filePath, context) {
  // Sort json properties
  //
  // The spaces argument of 1 is added to ensure that prettier does not
  // output the whole object one a single line
  let sortedContent = (0, _jsonStableStringify.default)(source, {
    space: 1
  }); // Always put name and version on top for json files

  if (typeof source.name !== "undefined" || typeof source.version !== "undefined") {
    const {
      name,
      version,
      ...props
    } = JSON.parse(sortedContent);
    const jsonContent = {
      name,
      version,
      ...props
    }; // The spaces argument of 1 is added to ensure that prettier does not
    // output the whole object one a single line

    sortedContent = JSON.stringify(jsonContent, null, 1);
  }

  const prettier = (0, _getPrettier.getPrettier)(context); // Check whether prettier can already infer the parser
  // from the current file path

  const fileInfo = prettier.getFileInfo.sync(filePath);
  let filePathForPrettier = filePath;

  if (!fileInfo.inferredParser) {
    // Add .json extension since prettier was not
    // able to infer the parser automatically
    filePathForPrettier = `${filePath}.json`;
  } // Format with prettier


  return prettier.format(sortedContent, {
    filepath: filePathForPrettier
  });
}

const jsonFileFunctions = {
  merge,
  polish
};
exports.jsonFileFunctions = jsonFileFunctions;