@richardo2016/rcli
Version:
Richard's cli
88 lines (87 loc) • 2.83 kB
JavaScript
Object.defineProperty(exports, "__esModule", { value: true });
const fs = require("fs");
const path = require("path");
const readdir = require("@fibjs/fs-readdir-recursive");
const mkdirp = require("@fibjs/mkdirp");
function normalizeToAbsolute(filepath, basedir = '') {
if (path.isAbsolute(filepath))
return path.resolve(filepath);
if (!basedir || !path.isAbsolute(basedir))
throw `when filepath is not absolute path, absolute basedir is required!`;
return path.resolve(basedir, filepath);
}
exports.normalizeToAbsolute = normalizeToAbsolute;
function listFiles(dir, options = {}) {
const { alwaysListAll = false } = options || {};
if (!path.isAbsolute(dir))
throw `[listFiles]dir must be absolute path`;
if (!fs.exists(dir))
throw `[listFiles]NON_EXISTED`;
const stat = fs.stat(dir);
if (!stat.isDirectory() && !stat.isFile()) {
throw `[listFiles]INVALID_DIRECTROY`;
}
else if (stat.isFile()) {
if (alwaysListAll) {
dir = path.dirname(dir);
return listFiles(dir, options);
}
return {
basedir: path.dirname(dir),
files: [path.basename(dir)]
};
}
return {
basedir: dir,
files: readdir(dir)
};
}
exports.listFiles = listFiles;
function walkFileList(dir, callback) {
const { basedir = null, files = [] } = listFiles(dir);
return files.forEach((srcpath, idx) => {
const lidx = getExtensionIdx(srcpath);
const existed = fs.exists(srcpath);
callback(srcpath, {
basedir,
index: idx,
existed: existed,
stat: existed ? fs.stat(srcpath) : null,
filebase: lidx === null ? srcpath : srcpath.slice(0, lidx),
extension: getExtension(srcpath)
});
});
}
exports.walkFileList = walkFileList;
function getExtensionIdx(filepath) {
const lidx = filepath.lastIndexOf('.');
if (lidx === -1)
return null;
return lidx;
}
exports.getExtensionIdx = getExtensionIdx;
function getExtension(filepath) {
if (!filepath)
throw `filepath cannot be empty`;
const lidx = getExtensionIdx(filepath);
if (lidx === null)
return '';
return filepath.slice(lidx);
}
exports.getExtension = getExtension;
function ensureDirectoryExisted(dirname) {
if (!fs.exists(dirname))
return mkdirp(dirname);
if (!fs.stat(dirname).isDirectory())
throw `EXISTED_NON_DIRECTORY`;
}
exports.ensureDirectoryExisted = ensureDirectoryExisted;
function getDirname(filepath) {
if (!fs.exists(filepath))
mkdirp(filepath);
if (!fs.stat(filepath).isDirectory())
filepath = path.dirname(filepath);
filepath = path.resolve(filepath);
return filepath;
}
exports.getDirname = getDirname;