@controlplane/cli
Version:
Control Plane Corporation CLI
212 lines • 6.86 kB
JavaScript
Object.defineProperty(exports, "__esModule", { value: true });
exports.isRelativePath = exports.stripPathShortcuts = exports.stripLeadingSlash = exports.posixPath = exports.isFileYamlOrJson = exports.accumulateFiles = exports.readFileInputsOption = exports.copyDirectorySync = exports.findAndReadFileInDir = exports.getRootDir = exports.loadAllObject = exports.loadObject = exports.readBinaryFile = exports.readTextFile = void 0;
const fs = require("fs");
const getStdin = require("get-stdin-with-tty");
const path = require("path");
const objects_1 = require("./objects");
async function readTextFile(filePath) {
let bodyAsString;
if (filePath == '-') {
bodyAsString = await getStdin();
}
else {
bodyAsString = fs.readFileSync(filePath, 'utf-8');
}
return bodyAsString;
}
exports.readTextFile = readTextFile;
async function readBinaryFile(filePath) {
let bodyAsBuffer;
if (filePath == '-') {
if (process.stdin.isTTY) {
// treat binary as text
const s = await getStdin();
bodyAsBuffer = Buffer.from(s, 'utf-8');
}
else {
bodyAsBuffer = await getStdin.buffer();
}
}
else {
bodyAsBuffer = fs.readFileSync(filePath);
}
return bodyAsBuffer;
}
exports.readBinaryFile = readBinaryFile;
function loadObject(content, filename) {
if (filename == '-') {
filename = '<stdin>';
}
return require('js-yaml').safeLoad(content, {
json: true,
filename: filename,
});
}
exports.loadObject = loadObject;
function loadAllObject(content, filename) {
if (filename == '-') {
filename = '<stdin>';
}
let documents = [];
require('js-yaml').loadAll(content, (doc) => {
if (doc === null) {
return;
}
if (Array.isArray(doc)) {
documents = [...documents, ...doc];
return;
}
documents.push(doc);
}, {
json: true,
filename: filename,
});
return documents;
}
exports.loadAllObject = loadAllObject;
function getUserHome() {
return process.env[process.platform == 'win32' ? 'USERPROFILE' : 'HOME'];
}
function getRootDir() {
let root;
const overrideHome = process.env['CPLN_HOME'];
if (overrideHome) {
root = overrideHome;
}
else {
const xdgConfig = process.env['XDG_CONFIG_HOME'];
if (xdgConfig) {
root = path.join(xdgConfig, 'cpln');
}
else {
const userHome = getUserHome();
if (!userHome)
throw new Error('Could not find home directory in env');
root = path.join(userHome, '/.config/cpln');
}
}
return root;
}
exports.getRootDir = getRootDir;
async function findAndReadFileInDir(dir, fileNames) {
// Get the file path
const pathStats = fs.statSync(dir);
// Ensuring path provided is a directory
if (!pathStats.isDirectory()) {
throw Error('No directory given');
}
// Finding 'docker-compose' file in directory
let filePath = null;
const filesInDir = fs.readdirSync(dir);
for (const fileName of fileNames) {
if (filesInDir.includes(fileName)) {
// Capture the file found
filePath = path.join(dir, fileName);
// Exit the loop once at least one file is found
break;
}
}
// No docker-compose file in directory
if (!filePath) {
throw Error(`ERROR: Could not find any file matching specified names; ${fileNames.join()}`);
}
return await readTextFile(filePath);
}
exports.findAndReadFileInDir = findAndReadFileInDir;
function copyDirectorySync(src, dest) {
fs.mkdirSync(dest, { recursive: true });
let entries = fs.readdirSync(src, { withFileTypes: true });
for (let entry of entries) {
let srcPath = path.join(src, entry.name);
let destPath = path.join(dest, entry.name);
entry.isDirectory() ? copyDirectorySync(srcPath, destPath) : fs.copyFileSync(srcPath, destPath);
}
}
exports.copyDirectorySync = copyDirectorySync;
function readFileInputsOption(fileInputs) {
const _filePaths = (0, objects_1.toArray)(fileInputs).map((f) => {
if (f === '.') {
return process.cwd();
}
return f;
});
const filePaths = [];
for (let path of _filePaths) {
// Handle stdin
const exists = fs.existsSync(path);
if (!exists) {
filePaths.push(path);
continue;
}
// Check if the provided path is a directory or a file
const stat = fs.statSync(path);
if (!stat.isDirectory()) {
filePaths.push(path);
continue;
}
// Visit each directory and accumulate files
filePaths.push(...accumulateFiles(path));
}
return filePaths;
}
exports.readFileInputsOption = readFileInputsOption;
function accumulateFiles(filePath) {
let filesList = [];
// Read the contents of the directory
const items = fs.readdirSync(filePath);
for (const item of items) {
const fullPath = path.join(filePath, item);
// Check if the item is a directory or a file
const stats = fs.statSync(fullPath);
if (stats.isDirectory()) {
// Recursively accumulate files from the subdirectory
filesList = filesList.concat(accumulateFiles(fullPath));
}
else if (isFileYamlOrJson(fullPath)) {
// If it's a YAML or JSON file, add it to the list
filesList.push(fullPath);
}
}
return filesList;
}
exports.accumulateFiles = accumulateFiles;
function isFileYamlOrJson(file) {
return file.endsWith('.yaml') || file.endsWith('.yml') || file.endsWith('.json');
}
exports.isFileYamlOrJson = isFileYamlOrJson;
function posixPath(path) {
return path.replace(/\\/g, '/');
}
exports.posixPath = posixPath;
function stripLeadingSlash(file) {
// Using a regular expression to remove leading slashes
return file.replace(/^[/\\]+/, '');
}
exports.stripLeadingSlash = stripLeadingSlash;
function stripPathShortcuts(path) {
let newPath = path;
let trimmed = newPath;
// Remove leading "../" segments
while (trimmed.startsWith('../')) {
newPath = trimmed.slice(3);
trimmed = newPath;
}
// Trim leftover ".", ".."
if (newPath === '.' || newPath === '..') {
newPath = '';
}
return newPath;
}
exports.stripPathShortcuts = stripPathShortcuts;
function isRelativePath(base, target) {
try {
const relative = path.relative(base, target);
return relative === '.' || relative === stripPathShortcuts(relative);
}
catch (error) {
return false;
}
}
exports.isRelativePath = isRelativePath;
//# sourceMappingURL=io.js.map
;