UNPKG

@sinclair/hammer

Version:

Build Tool for Browser and Node Applications

201 lines (194 loc) 8.29 kB
"use strict"; /*-------------------------------------------------------------------------- MIT License Copyright (c) Hammer 2022 Haydn Paterson (sinclair) <haydn.developer@gmail.com> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ---------------------------------------------------------------------------*/ Object.defineProperty(exports, "__esModule", { value: true }); exports.file = exports.File = exports.FileError = void 0; const error_1 = require("./error"); const fs = require("./fs"); const path = require("path"); const crypto = require("crypto"); class FileError extends error_1.SystemError { operation; reason; constructor(operation, reason) { super(`File.${operation}(...): ${reason}`); this.operation = operation; this.reason = reason; } } exports.FileError = FileError; class File { filePath; constructor(filePath) { this.filePath = filePath; } /** Appends this file with the given data. If the file does not exist it will be created. */ async append(data) { if (!(await this.checkExists(this.filePath))) { await this.createFolder(path.dirname(this.filePath)); await fs.writeFile(this.filePath, Buffer.alloc(0)); } await fs.appendFile(this.filePath, data); } /** Copies this file into the target folder. If the target folder does not exist it will be created. */ async copy(folderPath) { await this.assertExists('copyTo', this.filePath); await this.createFolder(folderPath); const targetPath = path.join(folderPath, path.basename(this.filePath)); await fs.copyFile(this.filePath, targetPath); } /** Creates an empty file if not exists. */ async create() { if (await this.checkExists(this.filePath)) return; await this.createFolder(path.dirname(this.filePath)); await fs.writeFile(this.filePath, Buffer.alloc(0)); } /** Deletes this file if it exists. Otherwise no action. */ async delete() { if (!(await this.checkExists(this.filePath))) return; await fs.unlink(this.filePath); } /** Replaces text content in this file that matches the given string or regular expression. */ async edit(pattern, replacement) { await this.assertExists('edit', this.filePath); const content = await fs.readFile(this.filePath, 'utf-8'); const search = typeof pattern === 'string' ? new RegExp(pattern, 'g') : pattern; const updated = content.replace(search, replacement); await fs.writeFile(this.filePath, updated); } /** Returns true if this file exists. */ async exists() { if (!(await this.checkExists(this.filePath))) return false; const stat = await fs.stat(this.filePath); return stat.isFile(); } /** Returns a hash for this file with the given algorithm (default is sha1, digest is hex) */ async hash(algorithm = 'sha1', digest = 'hex') { await this.assertExists('hash', this.filePath); let offset = 0; const fd = await fs.open(this.filePath, 'r'); const hash = crypto.createHash(algorithm); const buffer = Buffer.alloc(16384); while (true) { const { bytesRead } = await fs.read(fd, buffer, 0, buffer.length, offset); if (bytesRead === 0) break; offset = offset + bytesRead; hash.update(buffer); } await fs.close(fd); return hash.digest(digest); } /** Moves this file into the target folder. If the target folder does not exist it will be created. */ async move(folderPath) { await this.assertExists('moveTo', this.filePath); await this.createFolder(folderPath); const targetPath = path.join(folderPath, path.basename(this.filePath)); await fs.copyFile(this.filePath, targetPath); await fs.unlink(this.filePath); } /** Prepends this file with the given data. If the file does not exist it will be created. */ async prepend(data) { if (!(await this.checkExists(this.filePath))) { return await fs.writeFile(this.filePath, Buffer.from(data)); } const sources = [Buffer.from(data), await fs.readFile(this.filePath)]; const buffer = Buffer.concat(sources); await fs.writeFile(this.filePath, buffer); } /** Reads this file as a JSON object. Will throw if the content cannot be parsed. */ async json() { await this.assertExists('json', this.filePath); const content = await fs.readFile(this.filePath, 'utf-8'); try { return JSON.parse(content); } catch { } throw new FileError('json', `The file path '${this.filePath}' failed to parse as json.`); } /** Returns the absolute path of this file. */ path() { return path.resolve(this.filePath); } /** Reads the contents of this file. */ async read(...args) { await this.assertExists('read', this.filePath); const encoding = args.length === 0 ? 'binary' : args[0]; return await fs.readFile(this.filePath, encoding); } /** Renames this file to the given newname. */ async rename(newName) { await this.assertExists('rename', this.filePath); const targetPath = path.join(path.dirname(this.filePath), newName); await fs.rename(this.filePath, targetPath); } /** Returns the size of this file in bytes. */ async size() { await this.assertExists('size', this.filePath); const stat = await fs.stat(this.filePath); return stat.size; } /** Returns the stats object for this file. */ async stat() { await this.assertExists('stat', this.filePath); return await fs.stat(this.filePath); } /** Truncates the contents of this file. If the file does not exist, it is created. */ async truncate(length = 0) { if (!(await this.checkExists(this.filePath))) { await this.createFolder(path.dirname(this.filePath)); return await fs.writeFile(this.filePath, Buffer.alloc(length)); } return await fs.truncate(this.filePath, length); } /** Writes to this file. If the file does not exist, it is created. */ async write(data) { await this.createFolder(path.dirname(this.filePath)); return await fs.writeFile(this.filePath, data); } /** Asserts the given path exists. */ async assertExists(operation, systemPath) { if (await this.checkExists(systemPath)) return; throw new FileError(operation, `The file path '${systemPath}' does not exist.`); } /** Checks the given path exists. */ async checkExists(systemPath) { return await fs .access(systemPath) .then(() => true) .catch(() => false); } /** Creates a directory if not exists. */ async createFolder(folderPath) { if (await this.checkExists(folderPath)) return; await fs.mkdir(folderPath, { recursive: true }); } } exports.File = File; /** Returns an interface to interact with a file. */ function file(file) { return new File(path.resolve(file)); } exports.file = file;