-
-
Notifications
You must be signed in to change notification settings - Fork 27
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Utilities: optimized memory and loading time
- Loading branch information
Showing
16 changed files
with
727 additions
and
595 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,66 @@ | ||
/** | ||
* This file contains the copyDirectory function. | ||
* | ||
* @file copyDirectory.ts | ||
* @author Luca Liguori | ||
* @date 2025-02-16 | ||
* @version 1.0.0 | ||
* | ||
* Copyright 2025, 2026, 2027 Luca Liguori. | ||
* | ||
* Licensed under the Apache License, Version 2.0 (the "License"); | ||
* you may not use this file except in compliance with the License. | ||
* You may obtain a copy of the License at | ||
* | ||
* http://www.apache.org/licenses/LICENSE-2.0 | ||
* | ||
* Unless required by applicable law or agreed to in writing, software | ||
* distributed under the License is distributed on an "AS IS" BASIS, | ||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
* See the License for the specific language governing permissions and | ||
* limitations under the License. * | ||
*/ | ||
|
||
// AnsiLogger module | ||
import { AnsiLogger, LogLevel, TimestampFormat } from '../logger/export.js'; | ||
|
||
/** | ||
* Copies a directory and all its subdirectories and files to a new location. | ||
* | ||
* @param {string} srcDir - The path to the source directory. | ||
* @param {string} destDir - The path to the destination directory. | ||
* @returns {Promise<boolean>} - A promise that resolves when the copy operation is complete or fails for error. | ||
* @throws {Error} - Throws an error if the copy operation fails. | ||
*/ | ||
export async function copyDirectory(srcDir: string, destDir: string): Promise<boolean> { | ||
const log = new AnsiLogger({ logName: 'Archive', logTimestampFormat: TimestampFormat.TIME_MILLIS, logLevel: LogLevel.INFO }); | ||
|
||
const fs = await import('node:fs').then((mod) => mod.promises); | ||
const path = await import('node:path'); | ||
|
||
log.debug(`copyDirectory: copying directory from ${srcDir} to ${destDir}`); | ||
try { | ||
// Create destination directory if it doesn't exist | ||
await fs.mkdir(destDir, { recursive: true }); | ||
|
||
// Read contents of the source directory | ||
const entries = await fs.readdir(srcDir, { withFileTypes: true }); | ||
|
||
for (const entry of entries) { | ||
const srcPath = path.join(srcDir, entry.name); | ||
const destPath = path.join(destDir, entry.name); | ||
|
||
if (entry.isDirectory()) { | ||
// Recursive call if entry is a directory | ||
await copyDirectory(srcPath, destPath); | ||
} else if (entry.isFile()) { | ||
// Copy file if entry is a file | ||
await fs.copyFile(srcPath, destPath); | ||
} | ||
} | ||
return true; | ||
} catch (error) { | ||
log.error(`copyDirectory error copying from ${srcDir} to ${destDir}: ${error instanceof Error ? error.message : error}`); | ||
return false; | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,119 @@ | ||
/** | ||
* This file contains the createZip function. | ||
* | ||
* @file createZip.ts | ||
* @author Luca Liguori | ||
* @date 2025-02-16 | ||
* @version 1.0.0 | ||
* | ||
* Copyright 2025, 2026, 2027 Luca Liguori. | ||
* | ||
* Licensed under the Apache License, Version 2.0 (the "License"); | ||
* you may not use this file except in compliance with the License. | ||
* You may obtain a copy of the License at | ||
* | ||
* http://www.apache.org/licenses/LICENSE-2.0 | ||
* | ||
* Unless required by applicable law or agreed to in writing, software | ||
* distributed under the License is distributed on an "AS IS" BASIS, | ||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
* See the License for the specific language governing permissions and | ||
* limitations under the License. * | ||
*/ | ||
|
||
// Archiver module import types | ||
import type { ArchiverError, EntryData } from 'archiver'; | ||
|
||
// AnsiLogger module | ||
import { AnsiLogger, LogLevel, TimestampFormat } from '../logger/export.js'; | ||
|
||
/** | ||
* Creates a ZIP archive from the specified source pattern or directory and writes it to the specified output path. | ||
* | ||
* @param {string} outputPath - The path where the output ZIP file will be written. | ||
* @param {string[]} sourcePaths - The source pattern or directory to be zipped (use path.join for sourcePath). | ||
* @returns {Promise<number>} - A promise that resolves to the total number of bytes written to the ZIP file. | ||
* | ||
* @remarks | ||
* This function uses the `archiver` library to create a ZIP archive. It sets the compression level to 9 (maximum compression). | ||
* The function ensures that the output file is properly closed after the archiving process is complete. | ||
* It logs the progress and the total number of bytes written to the console. | ||
* | ||
* This function uses the `glob` library to match files based on the source pattern (internally converted in posix). | ||
*/ | ||
export async function createZip(outputPath: string, ...sourcePaths: string[]): Promise<number> { | ||
const log = new AnsiLogger({ logName: 'Archive', logTimestampFormat: TimestampFormat.TIME_MILLIS, logLevel: LogLevel.INFO }); | ||
|
||
const { default: archiver } = await import('archiver'); | ||
const { glob } = await import('glob'); | ||
const { createWriteStream, statSync } = await import('node:fs'); | ||
const path = await import('node:path'); | ||
|
||
log.debug(`creating archive ${outputPath} from ${sourcePaths.join(', ')} ...`); | ||
|
||
return new Promise((resolve, reject) => { | ||
const output = createWriteStream(outputPath); | ||
const archive = archiver('zip', { | ||
zlib: { level: 9 }, // Set compression level | ||
}); | ||
|
||
output.on('close', () => { | ||
log.debug(`archive ${outputPath} closed with ${archive.pointer()} total bytes`); | ||
resolve(archive.pointer()); | ||
}); | ||
|
||
output.on('end', () => { | ||
log.debug(`archive ${outputPath} data has been drained ${archive.pointer()} total bytes`); | ||
}); | ||
|
||
archive.on('error', (error: ArchiverError) => { | ||
log.error(`archive error: ${error.message}`); | ||
reject(error); | ||
}); | ||
|
||
archive.on('warning', (error: ArchiverError) => { | ||
if (error.code === 'ENOENT') { | ||
log.warn(`archive warning: ${error.message}`); | ||
} else { | ||
log.error(`archive warning: ${error.message}`); | ||
reject(error); | ||
} | ||
}); | ||
|
||
archive.on('entry', (entry: EntryData) => { | ||
log.debug(`- archive entry: ${entry.name}`); | ||
}); | ||
|
||
archive.pipe(output); | ||
|
||
for (const sourcePath of sourcePaths) { | ||
// Check if the sourcePath is a file or directory | ||
let stats; | ||
try { | ||
stats = statSync(sourcePath); | ||
} catch (error) { | ||
if (sourcePath.includes('*')) { | ||
const files = glob.sync(sourcePath.replace(/\\/g, '/')); | ||
log.debug(`adding files matching glob pattern: ${sourcePath}`); | ||
for (const file of files) { | ||
log.debug(`- glob file: ${file}`); | ||
archive.file(file, { name: file }); | ||
} | ||
} else { | ||
log.error(`no files or directory found for pattern ${sourcePath}: ${error}`); | ||
} | ||
continue; | ||
} | ||
if (stats.isFile()) { | ||
log.debug(`adding file: ${sourcePath}`); | ||
archive.file(sourcePath, { name: path.basename(sourcePath) }); | ||
} else if (stats.isDirectory()) { | ||
log.debug(`adding directory: ${sourcePath}`); | ||
archive.directory(sourcePath, path.basename(sourcePath)); | ||
} | ||
} | ||
// Finalize the archive (i.e., we are done appending files but streams have to finish yet) | ||
log.debug(`finalizing archive ${outputPath}...`); | ||
archive.finalize().catch(reject); | ||
}); | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,70 @@ | ||
/** | ||
* This file contains the deepCopy function. | ||
* | ||
* @file deepCopy.ts | ||
* @author Luca Liguori | ||
* @date 2025-02-16 | ||
* @version 1.0.0 | ||
* | ||
* Copyright 2025, 2026, 2027 Luca Liguori. | ||
* | ||
* Licensed under the Apache License, Version 2.0 (the "License"); | ||
* you may not use this file except in compliance with the License. | ||
* You may obtain a copy of the License at | ||
* | ||
* http://www.apache.org/licenses/LICENSE-2.0 | ||
* | ||
* Unless required by applicable law or agreed to in writing, software | ||
* distributed under the License is distributed on an "AS IS" BASIS, | ||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
* See the License for the specific language governing permissions and | ||
* limitations under the License. * | ||
*/ | ||
|
||
/** | ||
* Creates a deep copy of the given value. | ||
* | ||
* @template T - The type of the value being copied. | ||
* @param {T} value - The value to be copied. | ||
* @returns {T} - The deep copy of the value. | ||
*/ | ||
export function deepCopy<T>(value: T): T { | ||
if (typeof value !== 'object' || value === null) { | ||
// Primitive value (string, number, boolean, bigint, undefined, symbol) or null | ||
return value; | ||
} else if (Array.isArray(value)) { | ||
// Array: Recursively copy each element | ||
// eslint-disable-next-line @typescript-eslint/no-explicit-any | ||
return value.map((item) => deepCopy(item)) as any; | ||
} else if (value instanceof Date) { | ||
// Date objects | ||
// eslint-disable-next-line @typescript-eslint/no-explicit-any | ||
return new Date(value.getTime()) as any; | ||
} else if (value instanceof Map) { | ||
// Maps | ||
const mapCopy = new Map(); | ||
value.forEach((val, key) => { | ||
mapCopy.set(key, deepCopy(val)); | ||
}); | ||
// eslint-disable-next-line @typescript-eslint/no-explicit-any | ||
return mapCopy as any; | ||
} else if (value instanceof Set) { | ||
// Sets | ||
const setCopy = new Set(); | ||
value.forEach((item) => { | ||
setCopy.add(deepCopy(item)); | ||
}); | ||
// eslint-disable-next-line @typescript-eslint/no-explicit-any | ||
return setCopy as any; | ||
} else { | ||
// Objects: Create a copy with the same prototype as the original | ||
const proto = Object.getPrototypeOf(value); | ||
const copy = Object.create(proto); | ||
for (const key in value) { | ||
if (Object.prototype.hasOwnProperty.call(value, key)) { | ||
copy[key] = deepCopy(value[key]); | ||
} | ||
} | ||
return copy as T; | ||
} | ||
} |
Oops, something went wrong.