@knapsack/app
Version:
Build Design Systems on top of knapsack, by Basalt
323 lines (263 loc) • 7.84 kB
JavaScript
;
var _interopRequireWildcard = require("@babel/runtime/helpers/interopRequireWildcard");
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.writeJson = writeJson;
exports.readJson = readJson;
exports.readJsonSync = readJsonSync;
exports.writeYaml = writeYaml;
exports.readYaml = readYaml;
exports.readYamlSync = readYamlSync;
exports.isRemoteUrl = isRemoteUrl;
exports.getPkg = getPkg;
exports.fileExists = fileExists;
exports.dirExists = dirExists;
exports.fileExistsOrExit = fileExistsOrExit;
exports.dirExistsOrExit = dirExistsOrExit;
exports.getGitBranch = getGitBranch;
exports.resolvePath = resolvePath;
exports.qsParse = qsParse;
exports.qsStringify = qsStringify;
exports.base64ToString = base64ToString;
exports.stringToBase64 = stringToBase64;
exports.formatCode = formatCode;
var _fsExtra = _interopRequireDefault(require("fs-extra"));
var _os = _interopRequireDefault(require("os"));
var _qs = _interopRequireDefault(require("qs"));
var _jsYaml = _interopRequireDefault(require("js-yaml"));
var _resolve = _interopRequireDefault(require("resolve"));
var _child_process = require("child_process");
var _prettier = _interopRequireDefault(require("prettier"));
var _path = require("path");
var log = _interopRequireWildcard(require("../cli/log"));
/**
* Copyright (C) 2018 Basalt
This file is part of Knapsack.
Knapsack is free software; you can redistribute it and/or modify it
under the terms of the GNU General Public License as published by the Free
Software Foundation; either version 2 of the License, or (at your option)
any later version.
Knapsack is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
more details.
You should have received a copy of the GNU General Public License along
with Knapsack; if not, see <https://www.gnu.org/licenses>.
*/
/**
* @param fileName - path to where JSON file should be written
* @param object - data to turn to JSON
*/
function writeJson(fileName, object) {
return _fsExtra.default.writeFile(fileName, JSON.stringify(object, null, 2) + _os.default.EOL);
}
/**
* @param fileName - path to where JSON file should be read
*/
function readJson(fileName) {
return _fsExtra.default.readFile(fileName, 'utf8').then(file => JSON.parse(file));
}
function readJsonSync(fileName) {
return JSON.parse(_fsExtra.default.readFileSync(fileName, 'utf8'));
}
function writeYaml(fileName, object) {
return _fsExtra.default.writeFile(fileName, _jsYaml.default.safeDump(object, {
noRefs: true
}));
}
function readYaml(fileName) {
return _fsExtra.default.readFile(fileName, 'utf8').then(file => _jsYaml.default.safeLoad(file, {
filename: fileName
}));
}
function readYamlSync(fileName) {
return _jsYaml.default.safeLoad(_fsExtra.default.readFileSync(fileName, 'utf8'), {
filename: fileName
});
}
function isRemoteUrl(url) {
return url.startsWith('http') || url.startsWith('//');
}
/**
* Get a NPM package's package.json as object
*/
function getPkg(pkg) {
const pkgPath = require.resolve(`${pkg}/package.json`);
return readJsonSync(pkgPath);
}
function fileExists(filePath) {
try {
return _fsExtra.default.statSync(filePath).isFile();
} catch (err) {
return false;
}
}
function dirExists(dirPath) {
try {
return _fsExtra.default.statSync(dirPath).isDirectory();
} catch (err) {
return false;
}
}
function fileExistsOrExit(filePath, msg) {
if (fileExists(filePath)) return;
log.error(msg || `This file does not exist! ${filePath}`);
process.exit(1);
}
function dirExistsOrExit(dirPath, msg) {
if (dirExists(dirPath)) return;
log.error(msg || `This folder does not exist! ${dirPath}`);
process.exit(1);
}
function getGitBranch() {
try {
const branch = (0, _child_process.execSync)('git symbolic-ref --short HEAD', {
encoding: 'utf8'
});
return branch === null || branch === void 0 ? void 0 : branch.trim();
} catch (err) {
console.error(`Uh oh! error thrown in getGitBranch: ${err.message}`);
return '';
}
}
function resolvePath({
path,
resolveFromDirs = []
}) {
var _result;
if ((0, _path.isAbsolute)(path)) {
return {
originalPath: path,
absolutePath: path,
exists: fileExists(path),
relativePathFromCwd: (0, _path.relative)(process.cwd(), path),
type: 'absolute'
};
}
let absolutePath;
try {
absolutePath = _resolve.default.sync(path, {
basedir: process.cwd()
});
if (absolutePath) {
return {
originalPath: path,
exists: true,
absolutePath,
relativePathFromCwd: (0, _path.relative)(process.cwd(), absolutePath),
type: 'package'
};
}
} catch (e) {// oh well
}
let result;
resolveFromDirs.forEach(base => {
const x = (0, _path.join)(process.cwd(), (0, _path.join)(base, path));
if (fileExists(x)) {
result = {
exists: true,
absolutePath: x,
originalPath: path,
relativePathFromCwd: (0, _path.relative)(process.cwd(), x),
type: 'relative'
};
}
});
if ((_result = result) === null || _result === void 0 ? void 0 : _result.exists) return result;
return {
exists: false,
originalPath: path,
type: 'unknown'
};
}
/**
* Parse QueryString, decode non-strings
* Changes strings like `'true'` to `true` among others like numbers
* @see qsStringify
*/
function qsParse(querystring) {
return _qs.default.parse(querystring, {
// This custom decoder is for turning values like `foo: "true"` into `foo: true`, along with Integers, null, and undefined.
// https://github.com/ljharb/qs/issues/91#issuecomment-437926409
decoder(str) {
const strWithoutPlus = str.replace(/\+/g, ' ');
if (/^(\d+|\d*\.\d+)$/.test(str)) {
return parseFloat(str);
}
const keywords = {
true: true,
false: false,
null: null,
undefined
};
if (str in keywords) {
return keywords[str];
} // utf8
try {
return decodeURIComponent(strWithoutPlus);
} catch (e) {
return strWithoutPlus;
}
}
});
}
/**
* Turn object of data into query string
* @see qsParse
*/
function qsStringify(data) {
return _qs.default.stringify(data);
}
function base64ToString(b64) {
return Buffer.from(b64, 'base64').toString();
}
function stringToBase64(string) {
return Buffer.from(string).toString('base64');
}
/**
* Format code with Prettier
* If it can't format, it just returns original code
* @link https://prettier.io/docs/en/options.html#parser
*/
function formatCode({
code,
language
}) {
if (!code) return code;
try {
const format = parser => _prettier.default.format(code === null || code === void 0 ? void 0 : code.trim(), {
trailingComma: 'all',
singleQuote: true,
semi: true,
parser,
htmlWhitespaceSensitivity: 'ignore'
});
switch (language) {
case 'html':
return format('html');
case 'react':
case 'js':
case 'jsx':
return format('babel');
case 'ts':
case 'tsx':
case 'react-typescript':
return format('typescript');
case 'json':
return format('json');
case 'yml':
case 'yaml':
return format('yaml');
case 'md':
case 'markdown':
return format('markdown');
default:
return code === null || code === void 0 ? void 0 : code.trim();
}
} catch (error) {
console.error(error);
return code;
}
}