tinify-client
Version:
A CLI to compress your images not only intelligently but also to the EXTREME!
74 lines (73 loc) • 2.75 kB
JavaScript
;
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.setKey = void 0;
const fs_1 = __importDefault(require("fs"));
const util_1 = require("util");
const child_process_1 = require("child_process");
const colorize_1 = require("../utils/colorize");
const constants_1 = require("../constants");
const { promises } = fs_1.default;
const exec = util_1.promisify(child_process_1.exec);
const access = promises.access;
let verbose = false;
exports.setKey = async (options) => {
verbose = options.verbose;
const key = options._[1];
if (!key) {
console.error(colorize_1.chalk.red(`\`key\` not provided.`), colorize_1.chalk.yellow(`Example: $ ${constants_1.USAGE_SET_KEY}`));
console.log();
return false;
}
const existing = await exists(constants_1.configFile);
if (!existing) {
const content = `// https://github.com/legend80s/tinify-client\n\nmodule.exports = { key: '${key}' }\n`;
try {
await promises.writeFile(constants_1.configFile, content);
}
catch (error) {
console.error(colorize_1.chalk.red(error));
return false;
}
console.log();
console.info(colorize_1.chalk.yellow(constants_1.configFile + ' not found 🤔. A new one created with content ✍️:'));
console.log();
console.log(colorize_1.chalk.green(colorize_1.chalk.italic(content)));
console.log('✨ Key set successfully.');
console.log();
return true;
}
const config = require(constants_1.configFile);
config.key = key;
const content = `// https://github.com/legend80s/tinify-client\n\nmodule.exports = ${JSON.stringify(config, null, 2)}\n`;
console.info(`✍️ Writing to existing config file ${constants_1.configFile}:`);
try {
await promises.writeFile(constants_1.configFile, content);
}
catch (error) {
console.error(colorize_1.chalk.red(error));
return false;
}
console.log();
console.info(colorize_1.chalk.green(colorize_1.chalk.italic(content)));
console.log('✨ Key updated successfully.');
console.log();
return true;
};
async function exists(files) {
// console.log('files:', files);
for (const file of Array.isArray(files) ? files : [files]) {
try {
await access(file, fs_1.default.constants.W_OK);
// console.log('file:', file);
return file;
}
catch (error) {
// do nothing
verbose && console.log(`file: ${file} not exist`);
}
}
return '';
}