@unibeautify/beautifier-sqlformat
Version:
sqlformat beautifier for Unibeautify
103 lines • 3.34 kB
JavaScript
Object.defineProperty(exports, "__esModule", { value: true });
const unibeautify_1 = require("unibeautify");
const readPkgUp = require("read-pkg-up");
const tmp = require("tmp");
const fs = require("fs");
const path = require("path");
const os = require("os");
const options_1 = require("./options");
const { pkg } = readPkgUp.sync({ cwd: __dirname });
exports.beautifier = {
name: "sqlformat",
package: pkg,
dependencies: [
{
type: unibeautify_1.DependencyType.Executable,
name: "sqlformat",
program: "sqlformat",
parseVersion: [/(\d+\.\d+\.\d+)/],
homepageUrl: "https://github.com/andialbrecht/sqlparse",
installationUrl: "https://github.com/andialbrecht/sqlparse",
bugsUrl: "https://github.com/andialbrecht/sqlparse/issues",
badges: [],
},
],
options: {
SQL: options_1.default,
},
beautify({ text, options, filePath, projectPath, dependencies, beautifierConfig, }) {
const sqlformat = dependencies.get("sqlformat");
const basePath = os.tmpdir();
const transformedOptions = transformOptionsToCli(options);
transformedOptions.push("--reindent");
return tmpFile({ postfix: ".sql" }).then(filePath => writeFile(filePath, text).then(() => sqlformat
.run({
args: transformedOptions.concat(relativizePaths(["-o", filePath, filePath], basePath)),
options: {
cwd: basePath,
},
})
.then(({ exitCode, stderr }) => {
if (exitCode) {
return Promise.reject(stderr);
}
return readFile(filePath);
})));
},
};
function transformOptionsToCli(options) {
return Object.keys(options).map(key => {
const value = options[key];
switch (typeof value) {
case "boolean":
return `--${key}`;
case "undefined":
return undefined;
default:
return `--${key}=${value}`;
}
});
}
function tmpFile(options) {
return new Promise((resolve, reject) => tmp.file(Object.assign({ prefix: "unibeautify-" }, options), (err, path, fd) => {
if (err) {
return reject(err);
}
return resolve(path);
}));
}
function writeFile(filePath, contents) {
return new Promise((resolve, reject) => {
fs.writeFile(filePath, contents, error => {
if (error) {
return reject(error);
}
return resolve();
});
});
}
function readFile(filePath) {
return new Promise((resolve, reject) => {
fs.readFile(filePath, (error, data) => {
if (error) {
return reject(error);
}
return resolve(data.toString());
});
});
}
function relativizePaths(args, basePath) {
return args.map(arg => {
const isTmpFile = typeof arg === "string" &&
!arg.includes(":") &&
path.isAbsolute(arg) &&
path.dirname(arg).startsWith(basePath);
if (isTmpFile) {
return path.relative(basePath, arg);
}
return arg;
});
}
exports.default = exports.beautifier;
//# sourceMappingURL=index.js.map
;