@puls-atlas/cli
Version:
The Puls Atlas CLI tool for managing Atlas projects
77 lines • 2.27 kB
JavaScript
import fs from 'fs';
import path from 'path';
const ensureParentDirectory = (filePath, dependencies = {}) => {
const {
fsImpl = fs,
pathImpl = path
} = dependencies;
const directoryPath = pathImpl.dirname(filePath);
try {
if (!fsImpl.existsSync(directoryPath)) {
fsImpl.mkdirSync(directoryPath, {
recursive: true
});
}
} catch (error) {
throw new Error(`Failed to prepare directory for file: ${filePath}\nError: ${error.message}`);
}
};
const createJsonString = (data, options = {}) => {
const {
indent = 4,
trailingNewline = true
} = options;
const serializedJson = JSON.stringify(data, null, indent);
return trailingNewline ? `${serializedJson}\n` : serializedJson;
};
export const readJsonFile = (filePath, options = {}, dependencies = {}) => {
const {
allowMissing = false
} = options;
const {
fsImpl = fs
} = dependencies;
if (!fsImpl.existsSync(filePath)) {
if (allowMissing) {
return null;
}
throw new Error(`Required JSON file not found: ${filePath}`);
}
let fileContent = '';
try {
fileContent = fsImpl.readFileSync(filePath, 'utf-8');
} catch (error) {
throw new Error(`Failed to read JSON file: ${filePath}\nError: ${error.message}`);
}
try {
return JSON.parse(fileContent);
} catch (error) {
throw new Error(`Invalid JSON in file: ${filePath}\nError: ${error.message}`);
}
};
export const writeJsonFile = (filePath, data, options = {}, dependencies = {}) => {
const {
fsImpl = fs
} = dependencies;
ensureParentDirectory(filePath, dependencies);
try {
fsImpl.writeFileSync(filePath, createJsonString(data, options), 'utf-8');
} catch (error) {
throw new Error(`Failed to write JSON file: ${filePath}\nError: ${error.message}`);
}
};
export const writeTextFile = (filePath, text, options = {}, dependencies = {}) => {
const {
trailingNewline = false
} = options;
const {
fsImpl = fs
} = dependencies;
ensureParentDirectory(filePath, dependencies);
const content = trailingNewline ? `${text}\n` : text;
try {
fsImpl.writeFileSync(filePath, content, 'utf-8');
} catch (error) {
throw new Error(`Failed to write text file: ${filePath}\nError: ${error.message}`);
}
};