DenReg/tar/src/mod.ts
Fabian Stamm 2e92ec337c
All checks were successful
continuous-integration/drone/push Build is passing
Add jsdoc annotations to public interface
2020-07-28 19:41:57 +02:00

90 lines
2.7 KiB
TypeScript

import { FS, Path } from "./deps.ts";
import { Tar, Untar } from "./tar.ts";
/**
* Uncompresses a tar file to a certain location
* @param {string} src Tar file to be uncompressed
* @param {string} dest The location to uncompress to
* @returns A promise that is resolved once the tar file finished uncompressing
*/
export async function uncompress(src: string, dest: string): Promise<void> {
const tarFile = await Deno.open(src, { read: true });
const untar = new Untar(tarFile);
for await (const entry of untar) {
if (entry.type === "directory") {
await FS.ensureDir(Path.join(dest, entry.fileName));
} else if (entry.type === "file") {
const path = Path.join(dest, entry.fileName);
await FS.ensureFile(path);
const file = await Deno.open(path, { write: true, create: true });
await Deno.copy(entry, file);
file.close();
} else {
//TODO: Error/Warning
}
}
tarFile.close();
}
export interface ICompressOptions {
/**
* Controls wether all files inside the tar should be prefixed with the foldername or not
*/
excludeSrc?: boolean;
}
/**
* Compress file or folder into a .tar file
* @param {string} src File or folder to compress
* @param {string} dest Path of the resulting .tar file
* @param {ICompressOptions} options Options to controll behavious
* @returns A promise that is resolved once the tar file finished compressing
*/
export async function compress(
src: string,
dest: string,
options?: ICompressOptions
): Promise<void> {
src = Path.resolve(src);
const tar = new Tar();
const stat = await Deno.lstat(src);
if (stat.isFile) {
tar.append(Path.basename(src), {
filePath: src,
});
} else {
let root = src;
if (!options?.excludeSrc) {
root = Path.dirname(src);
await tar.append(Path.basename(src), {
type: "directory",
reader: new Deno.Buffer(),
contentSize: 0,
});
}
const walker = FS.walk(src, { includeDirs: true, includeFiles: true });
for await (const file of walker) {
const relativePath = Path.relative(root, file.path);
if (file.isDirectory) {
await tar.append(relativePath, {
type: "directory",
reader: new Deno.Buffer(),
contentSize: 0,
});
} else {
await tar.append(relativePath, {
filePath: file.path,
type: "file",
});
}
}
}
const writer = await Deno.open(dest, { write: true, create: true });
await Deno.copy(tar.getReader(), writer);
writer.close();
}