@onereach/get-version-data
Version:
CLI tool to get version data for deploy
97 lines (80 loc) • 2.35 kB
JavaScript
;
/**
* Check if a file exists
* @param {string} file The file to check
* @returns {Promise<boolean>}
*/
async function checkFileExists (file) {
const fs = require('fs');
const path = require('path');
try {
const filePath = path.resolve(process.cwd(), file);
await fs.promises.access(filePath, fs.constants.F_OK)
return true
} catch (error) {
return false
}
}
async function readYaml (file) {
const yaml = require('yaml');
const fs = require('fs');
const path = require('path');
const filePath = path.resolve(process.cwd(), file);
const fileContent = await fs.promises.readFile(filePath, 'utf8');
return yaml.parse(fileContent);
}
async function readJson (file) {
const fs = require('fs');
const path = require('path');
const filePath = path.resolve(process.cwd(), file);
const fileContent = await fs.promises.readFile(filePath, 'utf8');
return JSON.parse(fileContent);
}
/**
* Get the lock file type and path
* @param {string} lockfilePath The path to the lock file
* @returns {{type: string, lockFilePath: string, subDir: string}} The lock file type and path
*/
async function getLockFile (lockfilePath) {
const path = require('path');
let lockFileDir = lockfilePath;
let maxDepth = 5
const result = {
type: null,
lockFile: null,
subDir: null,
}
do {
const pnpmLockFile = path.resolve(lockFileDir, 'pnpm-lock.yaml');
const yarnLockFile = path.resolve(lockFileDir, 'yarn.lock');
const npmLockFile = path.resolve(lockFileDir, 'package-lock.json');
const [isPnpm, isYarn, isNpm] = await Promise.all([
checkFileExists(pnpmLockFile),
checkFileExists(yarnLockFile),
checkFileExists(npmLockFile),
]);
if (isPnpm) {
result.type = 'pnpm';
result.lockFile = pnpmLockFile;
} else if (isYarn) {
result.type = 'yarn';
result.lockFile = yarnLockFile;
} else if (isNpm) {
result.type = 'npm';
result.lockFile = npmLockFile;
}
if (!result.lockFile) {
lockFileDir = path.resolve(lockFileDir, '..');
maxDepth -= 1;
}
} while (!result.lockFile && maxDepth > 0);
if (!result.lockFile) return;
result.subDir = path.relative(lockFileDir, lockfilePath);
return result;
}
module.exports = {
checkFileExists,
readYaml,
readJson,
getLockFile,
}