@jin7942/ray
Version:
Lightweight CI/CD deployment tool powered by Docker and Git
142 lines (141 loc) • 4.65 kB
JavaScript
;
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.ensureDirectoryExists = ensureDirectoryExists;
exports.appendToFile = appendToFile;
exports.trimLogsIfTooLarge = trimLogsIfTooLarge;
exports.readFile = readFile;
exports.exists = exists;
exports.removeDirectory = removeDirectory;
/**
* A collection of file system utility functions used by RAY
* - Directory creation
* - Log writing with auto-trim
* - File existence checks
* - UTF-8 file reading
*/
const promises_1 = __importDefault(require("fs/promises"));
const path_1 = __importDefault(require("path"));
const global_1 = require("../config/global");
/**
* Ensure that a directory exists, create it recursively if it doesn't.
*
* @param dirPath - Absolute or relative path to the directory.
*/
async function ensureDirectoryExists(dirPath) {
try {
await promises_1.default.mkdir(dirPath, { recursive: true });
}
catch (err) {
console.warn('[fsHelper] Failed to create directory:', err);
}
}
/**
* Append a log message to a file.
* - Automatically trims old log files if total log size exceeds threshold.
*
* @param dir - Directory path to save logs.
* @param filename - File name (e.g., 2025-04-05.log).
* @param content - Log message to write.
*/
async function appendToFile(dir, filename, content) {
await ensureDirectoryExists(dir);
const fullPath = path_1.default.join(dir, filename);
try {
await promises_1.default.appendFile(fullPath, content + '\n', 'utf-8');
}
catch (err) {
console.warn('[fsHelper] Failed to write log:', err);
}
const { maxSize } = (0, global_1.getLogSettings)();
trimLogsIfTooLarge(dir, maxSize).catch((e) => console.warn('[fsHelper] Failed to trim logs:', e));
}
/**
* Get total size of all files in a directory (in bytes).
*
* @param dir - Directory path.
* @returns The total size in bytes.
*/
async function getDirectorySize(dir) {
try {
const files = await promises_1.default.readdir(dir);
let total = 0;
for (const file of files) {
const { size } = await promises_1.default.stat(path_1.default.join(dir, file));
total += size;
}
return total;
}
catch (err) {
console.warn('[fsHelper] Failed to calculate directory size:', err);
return 0;
}
}
/**
* Check total directory size and delete oldest files if limit exceeded.
*
* @param dir - Log directory.
* @param maxSizeBytes - Size threshold in bytes.
*/
async function trimLogsIfTooLarge(dir, maxSizeBytes) {
try {
const entries = await promises_1.default.readdir(dir);
const logFiles = await Promise.all(entries
.filter((f) => f.endsWith('.log'))
.map(async (file) => {
const stat = await promises_1.default.stat(path_1.default.join(dir, file));
return { name: file, time: stat.mtime.getTime(), size: stat.size };
}));
logFiles.sort((a, b) => a.time - b.time); // Sort oldest first
let totalSize = logFiles.reduce((sum, f) => sum + f.size, 0);
while (totalSize > maxSizeBytes && logFiles.length > 0) {
const toDelete = logFiles.shift();
if (!toDelete)
break;
await promises_1.default.unlink(path_1.default.join(dir, toDelete.name));
totalSize -= toDelete.size;
}
}
catch (err) {
console.warn('[fsHelper] Failed to trim logs:', err);
}
}
/**
* Reads a file as UTF-8 encoded text.
*
* @param filePath - The absolute or relative path to the file.
* @returns A promise that resolves to the file contents as a string.
*/
async function readFile(filePath) {
return await promises_1.default.readFile(filePath, 'utf-8');
}
/**
* Checks whether a file exists at the given path.
*
* @param filePath - The path to the file to check.
* @returns A promise that resolves to true if the file exists, false otherwise.
*/
async function exists(filePath) {
try {
await promises_1.default.access(filePath);
return true;
}
catch {
return false;
}
}
/**
* Remove directory from directory path
*
* @param dirPath - The path to remove target of diretory path
*/
async function removeDirectory(dirPath) {
try {
await promises_1.default.rm(dirPath, { recursive: true, force: true });
}
catch (err) {
console.warn(`[fsHelper] Failed to remove directory: ${dirPath}`, err);
}
}