kaven-utils
Version:
Utils for Node.js.
88 lines (87 loc) • 3.19 kB
JavaScript
/********************************************************************
* @author: Kaven
* @email: kaven@wuwenkai.com
* @website: http://blog.kaven.xyz
* @file: [Kaven-Utils] /src/KavenUtility.Archive.ts
* @create: 2020-07-29 13:57:23.481
* @modify: 2024-11-01 14:38:14.464
* @version: 5.4.5
* @times: 54
* @lines: 104
* @copyright: Copyright © 2020-2024 Kaven. All Rights Reserved.
* @description: [description]
* @license: [license]
********************************************************************/
import { CombinePath, Strings_DoubleQuotes, Strings_Empty, Strings_WhiteSpace, SurroundBy } from "kaven-basic";
import { isAbsolute } from "node:path";
import { Execute } from "./KavenUtility.ChildProcess.js";
import { DeleteFile, IsDirectory, IsPathExistSync } from "./KavenUtility.FileSystem.js";
/**
* This function calls the 7z binary, it should be available in your PATH.
* @since 5.3.0
* @version 2023-12-11
* @example
* Create7zArchive("./dist/", "dist.7z")
* Create7zArchive("./dist/*", "dist.7z")
*/
export async function Create7zArchive(input, outputFile, options) {
const sourceList = typeof input === "string" ? [input] : input;
const parameters = {};
const parameterList = [];
if (options) {
if (options.compressionLevel !== undefined) {
parameters["-mx"] = options.compressionLevel.toString();
}
if (options.password !== undefined) {
parameters["-p"] = options.password;
}
if (!options.notRecurseSubdirectories) {
parameters["-r"] = Strings_Empty;
}
if (options.parameters) {
for (const key of Object.keys(options.parameters)) {
parameters[key] = options.parameters[key];
}
}
for (const key of Object.keys(parameters)) {
parameterList.push(`${key}${parameters[key]}`);
}
}
const inputList = [];
for (let item of sourceList) {
if (!item.endsWith("*") && isAbsolute(item) && await IsDirectory(item)) {
item = CombinePath(item, "*");
}
item = SurroundBy(item, Strings_DoubleQuotes);
inputList.push(item);
}
if (IsPathExistSync(outputFile)) {
if (options?.overwriteFile) {
await DeleteFile(outputFile);
}
else {
throw new Error(`File ${outputFile} already exists`);
}
}
const command = `7z a ${parameterList.join(Strings_WhiteSpace)} "${outputFile}" ${inputList.join(Strings_WhiteSpace)}`;
await Execute(command, {
trace: options?.trace,
});
return outputFile;
}
/**
* This function calls the 7z binary, it should be available in your PATH.
* @since 5.3.0
* @version 2023-12-11
* @example
* CreateZipArchive("./dist/", "dist.zip")
* CreateZipArchive("./dist/*", "dist.zip")
*/
export async function CreateZipArchive(inputFiles, outputFile, options) {
options ??= {};
if (!options.parameters) {
options.parameters = {};
}
options.parameters["-t"] = "zip";
return await Create7zArchive(inputFiles, outputFile, options);
}