diff --git a/build-tests/api-extractor-test-05/dist/tsdoc-metadata.json b/build-tests/api-extractor-test-05/dist/tsdoc-metadata.json index ccb284c3209..b8d504d3f76 100644 --- a/build-tests/api-extractor-test-05/dist/tsdoc-metadata.json +++ b/build-tests/api-extractor-test-05/dist/tsdoc-metadata.json @@ -5,7 +5,7 @@ "toolPackages": [ { "packageName": "@microsoft/api-extractor", - "packageVersion": "7.58.11" + "packageVersion": "7.60.1" } ] } diff --git a/common/changes/@microsoft/rush/deploy-tarballs_2026-11-25.json b/common/changes/@microsoft/rush/deploy-tarballs_2026-11-25.json new file mode 100644 index 00000000000..2a6f5662ec7 --- /dev/null +++ b/common/changes/@microsoft/rush/deploy-tarballs_2026-11-25.json @@ -0,0 +1,10 @@ +{ + "changes": [ + { + "packageName": "@microsoft/rush", + "comment": "Add support for `.tar`, `.tar.gz`, and `.tgz` archives to `rush deploy --create-archive`.", + "type": "minor" + } + ], + "packageName": "@microsoft/rush" +} diff --git a/common/changes/@rushstack/package-extractor/deploy-tarballs_2026-11-25.json b/common/changes/@rushstack/package-extractor/deploy-tarballs_2026-11-25.json new file mode 100644 index 00000000000..68158770839 --- /dev/null +++ b/common/changes/@rushstack/package-extractor/deploy-tarballs_2026-11-25.json @@ -0,0 +1,15 @@ +{ + "changes": [ + { + "packageName": "@rushstack/package-extractor", + "comment": "Support `.tar`, `.tar.gz`, and `.tgz` deployment archives using native tar, staging archive-only assets in a temporary folder.", + "type": "minor" + }, + { + "packageName": "@rushstack/package-extractor", + "comment": "Expose shared, memoized native tar discovery and execution for use by Rush build caching.", + "type": "minor" + } + ], + "packageName": "@rushstack/package-extractor" +} diff --git a/common/config/subspaces/default/pnpm-lock.yaml b/common/config/subspaces/default/pnpm-lock.yaml index 2ba67bda337..e195106916e 100644 --- a/common/config/subspaces/default/pnpm-lock.yaml +++ b/common/config/subspaces/default/pnpm-lock.yaml @@ -4094,6 +4094,9 @@ importers: local-node-rig: specifier: workspace:* version: link:../../rigs/local-node-rig + tar: + specifier: ~7.5.6 + version: 7.5.13 webpack: specifier: ~5.105.2 version: 5.105.4 diff --git a/common/reviews/api/package-extractor.api.md b/common/reviews/api/package-extractor.api.md index 1b0cfb0139c..a39cb16fb63 100644 --- a/common/reviews/api/package-extractor.api.md +++ b/common/reviews/api/package-extractor.api.md @@ -7,6 +7,17 @@ import { IPackageJson } from '@rushstack/node-core-library'; import { ITerminal } from '@rushstack/terminal'; +// @beta (undocumented) +export interface ICreateArchiveOptions extends ITarOptionsBase { + abortSignal?: AbortSignal; + // (undocumented) + archivePath: string; + baseFolderPath: string; + gzip?: boolean; + // (undocumented) + paths: string[]; +} + // @public export interface IExtractorDependencyConfiguration { dependencyName: string; @@ -25,6 +36,7 @@ export interface IExtractorMetadataJson { // @public export interface IExtractorOptions { + archiveTempFolder?: string; createArchiveFilePath?: string; createArchiveOnly?: boolean; dependencyConfigurations?: IExtractorDependencyConfiguration[]; @@ -76,6 +88,20 @@ export interface IProjectInfoJson { projectName: string; } +// @beta (undocumented) +export interface ITarOptionsBase { + // (undocumented) + logFilePath: string; +} + +// @beta (undocumented) +export interface IUntarOptions extends ITarOptionsBase { + // (undocumented) + archivePath: string; + // (undocumented) + outputFolderPath: string; +} + // @public export type LinkCreationMode = 'default' | 'script' | 'none'; @@ -86,6 +112,16 @@ export class PackageExtractor { static getPackageIncludedFilesAsync(packageRootPath: string): Promise; } +// @beta +export class TarExecutable { + // (undocumented) + tryCreateArchiveAsync(options: ICreateArchiveOptions): Promise; + // (undocumented) + static tryInitializeAsync(terminal: ITerminal, tarBinaryPath?: string): Promise; + // (undocumented) + tryUntarAsync(options: IUntarOptions): Promise; +} + // (No @packageDocumentation comment for this package) ``` diff --git a/libraries/package-extractor/README.md b/libraries/package-extractor/README.md index 6bdf6b3af4a..b30e6f749c4 100644 --- a/libraries/package-extractor/README.md +++ b/libraries/package-extractor/README.md @@ -2,6 +2,18 @@ A library used for creating an isolated copy of a package and, optionally, bundling it into an archive. +The `createArchiveFilePath` option supports ZIP (`.zip`), tar (`.tar`), and gzip-compressed +tar (`.tar.gz` or `.tgz`) archives, including when `createArchiveOnly` is enabled. +Tar archives require the native `tar` executable on PATH. Archive-only tar deployments +stage assets in a unique timestamp-based folder under `archiveTempFolder` (default: +`common/temp` under the source root), then remove that folder after success or failure. +ZIP archives continue +to use JavaScript; archive-only ZIP deployments stage only generated files and read existing +source files directly. Materialized deployments archive their target files without staging. +Generated assets are written once by the asset handler; the archive manager accepts only file paths. + +`TarExecutable` shares memoized native discovery and execution with Rush's build cache. + ## Links - [CHANGELOG.md]( diff --git a/libraries/package-extractor/package.json b/libraries/package-extractor/package.json index 9e7e116df2d..d6568b89609 100644 --- a/libraries/package-extractor/package.json +++ b/libraries/package-extractor/package.json @@ -55,6 +55,7 @@ "semver": "~7.7.4" }, "devDependencies": { + "tar": "~7.5.6", "local-node-rig": "workspace:*", "@rushstack/heft-webpack5-plugin": "workspace:*", "@rushstack/heft": "workspace:*", diff --git a/libraries/package-extractor/src/ArchiveManager.ts b/libraries/package-extractor/src/ArchiveManager.ts index 69a7d1360c2..78130751dcf 100644 --- a/libraries/package-extractor/src/ArchiveManager.ts +++ b/libraries/package-extractor/src/ArchiveManager.ts @@ -1,9 +1,17 @@ // Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the MIT license. // See LICENSE in the project root for license information. +import path from 'node:path'; + import JSZip from 'jszip'; -import { FileSystem, type FileSystemStats, Path } from '@rushstack/node-core-library'; +import { Async, FileSystem, type FileSystemStats, Path } from '@rushstack/node-core-library'; +import type { ITerminal } from '@rushstack/terminal'; + +import { TarExecutable } from './TarExecutable'; +import { MAX_CONCURRENCY } from './scripts/createLinks/utilities/constants'; + +export type ArchiveFormat = 'zip' | 'tar' | 'tgz'; // 755 are default permissions to allow read/write/execute for owner and read/execute for group and others. const DEFAULT_FILE_PERMISSIONS: number = 0o755; @@ -14,51 +22,110 @@ const DEFAULT_FILE_PERMISSIONS: number = 0o755; const SYMBOLIC_LINK_PERMISSIONS: number = 0o120000 | DEFAULT_FILE_PERMISSIONS; export interface IAddToArchiveOptions { - filePath?: string; - fileData?: Buffer | string; + filePath: string; archivePath: string; stats?: FileSystemStats; } +export interface ICreateArchiveOptions { + terminal: ITerminal; + sourceFolder: string; +} + export class ArchiveManager { - #zip: JSZip = new JSZip(); + readonly #archiveFormat: ArchiveFormat; + readonly #entries: Map = new Map(); + #tarExecutablePromise: Promise | undefined; - public async addToArchiveAsync(options: IAddToArchiveOptions): Promise { - const { filePath, fileData, archivePath } = options; - - let data: Buffer | string; - let permissions: number; - if (filePath) { - const stats: FileSystemStats = options.stats ?? (await FileSystem.getLinkStatisticsAsync(filePath)); - if (stats.isSymbolicLink()) { - data = await FileSystem.readLinkAsync(filePath); - permissions = SYMBOLIC_LINK_PERMISSIONS; - } else if (stats.isDirectory()) { - throw new Error('Directories cannot be added to the archive'); - } else { - data = await FileSystem.readFileToBufferAsync(filePath); - permissions = stats.mode; - } - } else if (fileData) { - data = fileData; - permissions = DEFAULT_FILE_PERMISSIONS; + public constructor(archiveFormat: ArchiveFormat) { + this.#archiveFormat = archiveFormat; + } + + public static getArchiveFormat(archiveFilePath: string): ArchiveFormat { + if (archiveFilePath.endsWith('.zip')) { + return 'zip'; + } else if (archiveFilePath.endsWith('.tar')) { + return 'tar'; + } else if (archiveFilePath.endsWith('.tar.gz') || archiveFilePath.endsWith('.tgz')) { + return 'tgz'; } else { - throw new Error('Either filePath or fileData must be provided'); + throw new Error('Supported archive file extensions: .zip, .tar, .tar.gz, .tgz.'); } + } - // Replace backslashes for Unix compat + public async addToArchiveAsync(options: IAddToArchiveOptions): Promise { + const { archivePath } = options; const addPath: string = Path.convertToSlashes(archivePath); - this.#zip.file(addPath, data, { - unixPermissions: permissions, - dir: false - }); + if (path.isAbsolute(addPath) || addPath.split('/').includes('..')) { + throw new Error('Archive entries must be relative paths within the archive'); + } + + this.#entries.set(addPath, options); } - public async createArchiveAsync(archiveFilePath: string): Promise { - const zipContent: Buffer = await this.#zip.generateAsync({ - type: 'nodebuffer', - platform: 'UNIX' - }); - await FileSystem.writeFileAsync(archiveFilePath, zipContent); + public async createArchiveAsync(archiveFilePath: string, options?: ICreateArchiveOptions): Promise { + if (this.#archiveFormat === 'zip') { + const zip: JSZip = new JSZip(); + const entries: { archivePath: string; data: Buffer | string; permissions: number }[] = + await Async.mapAsync( + this.#entries, + async ([archivePath, { filePath, stats: providedStats }]) => { + let data: Buffer | string; + let permissions: number; + const stats: FileSystemStats = + providedStats ?? (await FileSystem.getLinkStatisticsAsync(filePath)); + if (stats.isSymbolicLink()) { + data = await FileSystem.readLinkAsync(filePath); + permissions = SYMBOLIC_LINK_PERMISSIONS; + } else if (stats.isDirectory()) { + throw new Error('Directories cannot be added to the archive'); + } else { + data = await FileSystem.readFileToBufferAsync(filePath); + permissions = stats.mode; + } + + return { archivePath, data, permissions }; + }, + { concurrency: MAX_CONCURRENCY } + ); + for (const { archivePath, data, permissions } of entries) { + zip.file(archivePath, data, { + unixPermissions: permissions, + dir: false + }); + } + + const zipContent: Buffer = await zip.generateAsync({ + type: 'nodebuffer', + platform: 'UNIX' + }); + await FileSystem.writeFileAsync(archiveFilePath, zipContent); + } else { + if (!options) { + throw new Error('Native tar creation requires terminal and source folder options'); + } + + const { terminal, sourceFolder } = options; + const tarExecutable: TarExecutable | undefined = await (this.#tarExecutablePromise ??= + TarExecutable.tryInitializeAsync(terminal)); + if (!tarExecutable) { + throw new Error('Native tar is required to create tar archives. Ensure "tar" is on PATH.'); + } + + const logFilePath: string = `${archiveFilePath}.log`; + const exitCode: number = await tarExecutable.tryCreateArchiveAsync({ + archivePath: archiveFilePath, + paths: [...this.#entries.keys()], + baseFolderPath: sourceFolder, + logFilePath, + gzip: this.#archiveFormat === 'tgz' + }); + if (exitCode !== 0) { + await FileSystem.deleteFileAsync(archiveFilePath); + throw new Error(`Native tar exited with code ${exitCode}. See "${logFilePath}" for details.`); + } else { + await FileSystem.deleteFileAsync(logFilePath); + } + } } } diff --git a/libraries/package-extractor/src/AssetHandler.ts b/libraries/package-extractor/src/AssetHandler.ts index cf064774d3d..714e2d7ed7a 100644 --- a/libraries/package-extractor/src/AssetHandler.ts +++ b/libraries/package-extractor/src/AssetHandler.ts @@ -4,7 +4,13 @@ import path from 'node:path'; import fs from 'node:fs'; -import { Async, FileSystem, Path, type FileSystemStats } from '@rushstack/node-core-library'; +import { + Async, + FileSystem, + Path, + type FileSystemStats, + type PosixModeBits +} from '@rushstack/node-core-library'; import type { ITerminal } from '@rushstack/terminal'; import { ArchiveManager } from './ArchiveManager'; @@ -12,6 +18,8 @@ import type { IExtractorOptions, LinkCreationMode } from './PackageExtractor'; import type { ILinkInfo, SymlinkAnalyzer } from './SymlinkAnalyzer'; import { remapSourcePathForTargetFolder } from './Utils'; +let _archiveTempFolderCounter: number = 0; + export interface IIncludeAssetOptions { sourceFilePath?: string; sourceFileStats?: FileSystemStats; @@ -52,6 +60,8 @@ export class AssetHandler { readonly #symlinkAnalyzer: SymlinkAnalyzer; readonly #archiveManager: ArchiveManager | undefined; readonly #archiveFilePath: string | undefined; + readonly #archiveTempFolder: string; + readonly #stageArchiveAssets: boolean; readonly #linkCreationMode: LinkCreationMode; readonly #includedAssetPaths: Set = new Set(); #isFinalized: boolean = false; @@ -64,18 +74,25 @@ export class AssetHandler { linkCreation, symlinkAnalyzer, createArchiveFilePath, - createArchiveOnly = false + createArchiveOnly = false, + archiveTempFolder } = options; this.#terminal = terminal; this.#sourceRootFolder = sourceRootFolder; this.#targetRootFolder = targetRootFolder; + // Disambiguate deployments started in the same millisecond or in different processes. + this.#archiveTempFolder = path.resolve( + archiveTempFolder ?? `${sourceRootFolder}/common/temp`, + `deploy-archive-${Date.now()}-${process.pid}-${_archiveTempFolderCounter++}` + ); + this.#stageArchiveAssets = + createArchiveOnly && + !!createArchiveFilePath && + ArchiveManager.getArchiveFormat(createArchiveFilePath) !== 'zip'; this.#symlinkAnalyzer = symlinkAnalyzer; if (createArchiveFilePath) { - if (path.extname(createArchiveFilePath) !== '.zip') { - throw new Error('Only archives with the .zip file extension are currently supported.'); - } this.#archiveFilePath = path.resolve(targetRootFolder, createArchiveFilePath); - this.#archiveManager = new ArchiveManager(); + this.#archiveManager = new ArchiveManager(ArchiveManager.getArchiveFormat(this.#archiveFilePath)); } if (createArchiveOnly && !this.#archiveManager) { throw new Error('createArchiveOnly cannot be true if createArchiveFilePath is not provided'); @@ -94,13 +111,13 @@ export class AssetHandler { if (this.#isFinalized) { throw new Error('includeAssetAsync() cannot be called after finalizeAsync()'); } - if (!sourceFilePath && !sourceFileContent) { + if (!sourceFilePath && sourceFileContent === undefined) { if (!Path.isUnder(targetFilePath, this.#targetRootFolder)) { throw new Error('The existing asset path must be under the target root folder'); } sourceFilePath = targetFilePath; } - if (sourceFilePath && sourceFileContent) { + if (sourceFilePath && sourceFileContent !== undefined) { throw new Error('Either sourceFilePath or sourceFileContent must be provided, but not both'); } if (this.#includedAssetPaths.has(targetFilePath)) { @@ -110,41 +127,45 @@ export class AssetHandler { throw new Error(`The asset at path "${targetFilePath}" has already been included`); } - if (!this.#createArchiveOnly) { + const targetRelativeFilePath: string = path.relative(this.#targetRootFolder, targetFilePath); + if (path.isAbsolute(targetRelativeFilePath) || /^\.\.(?:[\\/]|$)/.test(targetRelativeFilePath)) { + throw new Error('The asset path must be under the target root folder'); + } + + const writePath: string = this.#createArchiveOnly + ? path.resolve(this.#archiveTempFolder, targetRelativeFilePath) + : targetFilePath; + if (!this.#createArchiveOnly || this.#stageArchiveAssets || sourceFileContent !== undefined) { // Ignore when the source file is the same as the target file, as it's a no-op - if (sourceFilePath && sourceFilePath !== targetFilePath) { + if (sourceFilePath && sourceFilePath !== writePath) { // Use the fs.copyFile API instead of FileSystem.copyFileAsync() since copyFileAsync performs // a needless stat() call to determine if it's a file or folder, and we already know it's a file. try { - await fs.promises.copyFile(sourceFilePath, targetFilePath, fs.constants.COPYFILE_EXCL); + await fs.promises.copyFile(sourceFilePath, writePath, fs.constants.COPYFILE_EXCL); } catch (e: unknown) { if (!FileSystem.isNotExistError(e as Error)) { throw e; } // The parent folder may not exist, so ensure it exists before trying to copy again - await FileSystem.ensureFolderAsync(path.dirname(targetFilePath)); - await fs.promises.copyFile(sourceFilePath, targetFilePath, fs.constants.COPYFILE_EXCL); + await FileSystem.ensureFolderAsync(path.dirname(writePath)); + await fs.promises.copyFile(sourceFilePath, writePath, fs.constants.COPYFILE_EXCL); } - } else if (sourceFileContent) { - await FileSystem.writeFileAsync(targetFilePath, sourceFileContent, { + } else if (sourceFileContent !== undefined) { + await FileSystem.writeFileAsync(writePath, sourceFileContent, { ensureFolderExists: true }); + if (this.#createArchiveOnly) { + await FileSystem.changePosixModeBitsAsync(writePath, 0o755 as PosixModeBits); + } } } if (this.#archiveManager) { - const targetRelativeFilePath: string = path.relative(this.#targetRootFolder, targetFilePath); - if (sourceFilePath) { - await this.#archiveManager.addToArchiveAsync({ - filePath: sourceFilePath, - archivePath: targetRelativeFilePath - }); - } else if (sourceFileContent) { - await this.#archiveManager.addToArchiveAsync({ - fileData: sourceFileContent, - archivePath: targetRelativeFilePath - }); - } + await this.#archiveManager.addToArchiveAsync({ + filePath: + this.#createArchiveOnly && !this.#stageArchiveAssets && sourceFilePath ? sourceFilePath : writePath, + archivePath: targetRelativeFilePath + }); } this.#includedAssetPaths.add(targetFilePath); @@ -154,6 +175,12 @@ export class AssetHandler { return [...this.#includedAssetPaths]; } + public async cleanupAsync(): Promise { + if (this.#createArchiveOnly) { + await FileSystem.deleteFolderAsync(this.#archiveTempFolder); + } + } + public async finalizeAsync(options?: IFinalizeOptions): Promise { const { onAfterExtractSymlinksAsync } = options ?? {}; @@ -161,22 +188,33 @@ export class AssetHandler { throw new Error('finalizeAsync() has already been called'); } - if (this.#linkCreationMode === 'default') { - this.#terminal.writeLine('Creating symlinks'); - const linksToCopy: ILinkInfo[] = this.#symlinkAnalyzer.reportSymlinks(); - await Async.forEachAsync(linksToCopy, async (linkToCopy: ILinkInfo) => { - await this.#extractSymlinkAsync(linkToCopy); - }); - } + try { + if (this.#linkCreationMode === 'default') { + this.#terminal.writeLine('Creating symlinks'); + const linksToCopy: ILinkInfo[] = this.#symlinkAnalyzer.reportSymlinks(); + await Async.forEachAsync(linksToCopy, async (linkToCopy: ILinkInfo) => { + await this.#extractSymlinkAsync(linkToCopy); + }); + } - await onAfterExtractSymlinksAsync?.(); + await onAfterExtractSymlinksAsync?.(); - if (this.#archiveManager && this.#archiveFilePath) { - this.#terminal.writeLine(`Creating archive at "${this.#archiveFilePath}"`); - await this.#archiveManager.createArchiveAsync(this.#archiveFilePath); - } + if (this.#archiveManager && this.#archiveFilePath) { + if (this.#stageArchiveAssets) { + await FileSystem.ensureFolderAsync(this.#archiveTempFolder); + } - this.#isFinalized = true; + this.#terminal.writeLine(`Creating archive at "${this.#archiveFilePath}"`); + await this.#archiveManager.createArchiveAsync(this.#archiveFilePath, { + terminal: this.#terminal, + sourceFolder: this.#createArchiveOnly ? this.#archiveTempFolder : this.#targetRootFolder + }); + } + + this.#isFinalized = true; + } finally { + await this.cleanupAsync(); + } } /** diff --git a/libraries/package-extractor/src/PackageExtractor.ts b/libraries/package-extractor/src/PackageExtractor.ts index e60df7b46ae..56a8aa6059a 100644 --- a/libraries/package-extractor/src/PackageExtractor.ts +++ b/libraries/package-extractor/src/PackageExtractor.ts @@ -233,10 +233,17 @@ export interface IExtractorOptions { overwriteExisting: boolean; /** - * The desired path to be used when archiving the target folder. Supported file extensions: .zip. + * The desired path to be used when archiving the target folder. + * Supported file extensions: .zip, .tar, .tar.gz, .tgz. */ createArchiveFilePath?: string; + /** + * The parent folder for temporary archive-only assets. Defaults to "common/temp" under + * {@link IExtractorOptions.sourceRootFolder}. Staging folders are removed after archive creation. + */ + archiveTempFolder?: string; + /** * Whether to skip copying files to the extraction target directory, and only create an extraction * archive. This is only supported when {@link IExtractorOptions.linkCreation} is 'script' or 'none'. @@ -413,22 +420,26 @@ export class PackageExtractor { existingDependencyConfigurations.push(dependencyConfiguration); } - await this.#performExtractionAsync(options, state); - await state.assetHandler.finalizeAsync({ - onAfterExtractSymlinksAsync: async () => { - // We need the symlinks to be created before attempting to create the bin links, since it requires - // the node_modules folder to be realized. While we're here, we may as well perform some specific - // link creation tasks and write the extractor-metadata.json file before the asset handler finalizes. - if (linkCreation === 'default') { - await this.#makeBinLinksAsync(options, state); - } else if (linkCreation === 'script') { - await this.#writeCreateLinksScriptAsync(options, state); - } + try { + await this.#performExtractionAsync(options, state); + await state.assetHandler.finalizeAsync({ + onAfterExtractSymlinksAsync: async () => { + // We need the symlinks to be created before attempting to create the bin links, since it requires + // the node_modules folder to be realized. While we're here, we may as well perform some specific + // link creation tasks and write the extractor-metadata.json file before the asset handler finalizes. + if (linkCreation === 'default') { + await this.#makeBinLinksAsync(options, state); + } else if (linkCreation === 'script') { + await this.#writeCreateLinksScriptAsync(options, state); + } - terminal.writeLine('Creating extractor-metadata.json'); - await this.#writeExtractorMetadataAsync(options, state); - } - }); + terminal.writeLine('Creating extractor-metadata.json'); + await this.#writeExtractorMetadataAsync(options, state); + } + }); + } finally { + await state.assetHandler.cleanupAsync(); + } } async #performExtractionAsync(options: IExtractorOptions, state: IExtractorState): Promise { diff --git a/libraries/rush-lib/src/utilities/TarExecutable.ts b/libraries/package-extractor/src/TarExecutable.ts similarity index 73% rename from libraries/rush-lib/src/utilities/TarExecutable.ts rename to libraries/package-extractor/src/TarExecutable.ts index cfad7649f2f..712dcd865f1 100644 --- a/libraries/rush-lib/src/utilities/TarExecutable.ts +++ b/libraries/package-extractor/src/TarExecutable.ts @@ -8,32 +8,41 @@ import events from 'node:events'; import { Executable, FileSystem, FileWriter } from '@rushstack/node-core-library'; import type { ITerminal } from '@rushstack/terminal'; -import type { RushConfigurationProject } from '../api/RushConfigurationProject'; -import { EnvironmentConfiguration } from '../api/EnvironmentConfiguration'; -import { IS_WINDOWS } from './executionUtilities'; +const initializations: Map> = new Map(); +/** + * @beta + */ export interface ITarOptionsBase { logFilePath: string; } +/** + * @beta + */ export interface IUntarOptions extends ITarOptionsBase { archivePath: string; outputFolderPath: string; } +/** + * @beta + */ export interface ICreateArchiveOptions extends ITarOptionsBase { archivePath: string; paths: string[]; - project: RushConfigurationProject; - /** - * The folder that `paths` are relative to, and that the archive's members are named from. Defaults to the - * project folder. - */ - baseFolderPath?: string; + /** The folder that `paths` are relative to. */ + baseFolderPath: string; + /** Whether to compress the archive with gzip. Defaults to true. */ + gzip?: boolean; /** When aborted, kills the tar process, which then exits with a nonzero code. */ abortSignal?: AbortSignal; } +/** + * Shared native tar discovery and execution for deployment and build caching. + * @beta + */ export class TarExecutable { #tarExecutablePath: string; @@ -41,17 +50,28 @@ export class TarExecutable { this.#tarExecutablePath = tarExecutablePath; } - public static async tryInitializeAsync(terminal: ITerminal): Promise { - terminal.writeVerboseLine('Trying to find "tar" binary'); - const tarExecutablePath: string | undefined = - EnvironmentConfiguration.tarBinaryPath || (await _tryFindTarExecutablePathAsync()); - if (!tarExecutablePath) { - terminal.writeVerboseLine('"tar" was not found on the PATH'); - return undefined; - } else { - terminal.writeVerboseLine(`Using "tar" binary: ${tarExecutablePath}`); - return new TarExecutable(tarExecutablePath); + public static async tryInitializeAsync( + terminal: ITerminal, + tarBinaryPath?: string + ): Promise { + let initialization: Promise | undefined = initializations.get(tarBinaryPath); + if (!initialization) { + initialization = (async () => { + terminal.writeVerboseLine('Trying to find "tar" binary'); + const tarExecutablePath: string | undefined = + tarBinaryPath || (await _tryFindTarExecutablePathAsync()); + if (!tarExecutablePath) { + terminal.writeVerboseLine('"tar" was not found on the PATH'); + return undefined; + } else { + terminal.writeVerboseLine(`Using "tar" binary: ${tarExecutablePath}`); + return new TarExecutable(tarExecutablePath); + } + })(); + initializations.set(tarBinaryPath, initialization); } + + return await initialization; } /** @@ -59,6 +79,7 @@ export class TarExecutable { * The "tar" exit code */ public async tryUntarAsync(options: IUntarOptions): Promise { + const { archivePath, outputFolderPath, logFilePath } = options; return await this.#spawnTarWithLoggingAsync( // These parameters are chosen for compatibility with the very primitive bsdtar 3.3.2 shipped with Windows 10. [ @@ -68,10 +89,10 @@ export class TarExecutable { '-m', // [Windows bsdtar 3.3.2] -f Location of archive (default \\.\tape0) '-f', - options.archivePath + archivePath ], - options.outputFolderPath, - options.logFilePath + outputFolderPath, + logFilePath ); } @@ -79,10 +100,10 @@ export class TarExecutable { * @returns * The "tar" exit code */ - public async tryCreateArchiveFromProjectPathsAsync(options: ICreateArchiveOptions): Promise { - const { project, archivePath, paths, logFilePath, baseFolderPath, abortSignal } = options; + public async tryCreateArchiveAsync(options: ICreateArchiveOptions): Promise { + const { archivePath, paths, logFilePath, baseFolderPath, abortSignal, gzip = true } = options; - const tarInput: string = paths.join('\n'); + const tarInput: string = paths.length > 0 ? `${paths.join('\0')}\0` : ''; // On Windows, tar.exe will report a "Failed to clean up compressor" error if the target folder // does not exist (GitHub #2622) @@ -97,13 +118,15 @@ export class TarExecutable { '-f', archivePath, // [Windows bsdtar 3.3.2] -z, -j, -J, --lzma Compress archive with gzip/bzip2/xz/lzma - '-z', + ...(gzip ? ['-z'] : []), + // NUL-delimited lists preserve whitespace and treat leading dashes as filenames. + '--null', // [GNU tar 1.33] -T, --files-from=FILE get names to extract or create from FILE // // Windows bsdtar does not document this parameter, but seems to accept it. '--files-from=-' ], - baseFolderPath ?? project.projectFolder, + baseFolderPath, logFilePath, tarInput, abortSignal @@ -173,10 +196,15 @@ export class TarExecutable { childProcess.stderr!.on('data', (chunk) => fileWriter.write(`[stderr] ${chunk}`)); if (input !== undefined) { - if (abortSignal) { - // A tar process that was killed may have closed its end of the pipe already; its exit code reports that. - childProcess.stdin!.on('error', () => undefined); - } + childProcess.stdin!.on('error', (error: NodeJS.ErrnoException) => { + // An incompatible or aborted tar may exit before reading the file list. + if (error.code === 'EPIPE' || error.code === 'EOF') { + fileWriter.write(`[stdin] ${error.message}\n`); + } else { + childProcess.emit('error', error); + } + }); + childProcess.stdin!.write(input, 'utf-8'); childProcess.stdin!.end(); } @@ -203,7 +231,7 @@ export class TarExecutable { } async function _tryFindTarExecutablePathAsync(): Promise { - if (IS_WINDOWS) { + if (process.platform === 'win32') { // If we're running on Windows, first try to use the OOB tar executable. If // we're running in the Git Bash, the tar executable on the PATH doesn't handle // Windows file paths correctly. diff --git a/libraries/package-extractor/src/index.ts b/libraries/package-extractor/src/index.ts index 564800a2f3c..de9077fdd83 100644 --- a/libraries/package-extractor/src/index.ts +++ b/libraries/package-extractor/src/index.ts @@ -13,3 +13,10 @@ export { } from './PackageExtractor'; export type { ILinkInfo } from './SymlinkAnalyzer'; + +export { + TarExecutable, + type ITarOptionsBase, + type IUntarOptions, + type ICreateArchiveOptions +} from './TarExecutable'; diff --git a/libraries/package-extractor/src/test/ArchiveManager.test.ts b/libraries/package-extractor/src/test/ArchiveManager.test.ts new file mode 100644 index 00000000000..aefd2530c77 --- /dev/null +++ b/libraries/package-extractor/src/test/ArchiveManager.test.ts @@ -0,0 +1,506 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the MIT license. +// See LICENSE in the project root for license information. + +import path from 'node:path'; + +import JSZip from 'jszip'; +import * as tar from 'tar'; +import { Async, FileSystem, Path } from '@rushstack/node-core-library'; +import { Terminal, StringBufferTerminalProvider } from '@rushstack/terminal'; + +import { ArchiveManager } from '../ArchiveManager'; +import { AssetHandler } from '../AssetHandler'; +import { SymlinkAnalyzer } from '../SymlinkAnalyzer'; +import { TarExecutable } from '../TarExecutable'; + +interface ITarEntry { + type: string; + mode?: number; + linkpath?: string; + data: Buffer; +} + +async function readTarAsync(archivePath: string): Promise> { + const entries: Map = new Map(); + await tar.list({ + file: archivePath, + onReadEntry: (entry) => { + const chunks: Buffer[] = []; + entry.on('data', (chunk: Buffer) => chunks.push(chunk)); + entry.on('end', () => { + const { path: entryPath, type, mode, linkpath } = entry; + entries.set(entryPath, { type, mode, linkpath, data: Buffer.concat(chunks) }); + }); + } + }); + + return entries; +} + +describe(ArchiveManager.name, () => { + const testFolder: string = path.resolve(`${__dirname}/../../test-output/archives`); + const sourceFolder: string = `${__dirname}/../../src/test/fixtures/archive`; + const sourceFile: string = `${sourceFolder}/input.txt`; + const tempFolder: string = `${testFolder}/common/temp`; + let fileContent: Buffer; + let generatedContent: string; + const terminal: Terminal = new Terminal(new StringBufferTerminalProvider()); + + function createHandler(archiveFilePath: string, createArchiveOnly: boolean = true): AssetHandler { + return new AssetHandler({ + terminal, + mainProjectName: 'test', + projectConfigurations: [], + sourceRootFolder: sourceFolder, + targetRootFolder: path.dirname(archiveFilePath), + overwriteExisting: false, + linkCreation: 'none', + symlinkAnalyzer: new SymlinkAnalyzer(), + createArchiveFilePath: archiveFilePath, + archiveTempFolder: tempFolder, + createArchiveOnly + }); + } + + beforeAll(async () => { + await FileSystem.ensureEmptyFolderAsync(testFolder); + await FileSystem.ensureFolderAsync(tempFolder); + fileContent = await FileSystem.readFileToBufferAsync(sourceFile); + generatedContent = await FileSystem.readFileAsync(`${sourceFolder}/generated.txt`); + }); + + afterEach(() => { + jest.restoreAllMocks(); + }); + + it.each(['.tar', '.tar.gz', '.tgz'])('creates %s archives with and without copying assets', async (ext) => { + for (const createArchiveOnly of [false, true]) { + const targetRootFolder: string = `${testFolder}/${ext.slice(1)}-${createArchiveOnly}`; + await FileSystem.ensureFolderAsync(targetRootFolder); + const archiveFilePath: string = `${targetRootFolder}/deploy${ext}`; + const targetFilePath: string = `${targetRootFolder}/nested/input.txt`; + const handler: AssetHandler = new AssetHandler({ + terminal, + mainProjectName: 'test', + projectConfigurations: [], + sourceRootFolder: sourceFolder, + targetRootFolder, + overwriteExisting: false, + linkCreation: 'none', + symlinkAnalyzer: new SymlinkAnalyzer(), + createArchiveFilePath: archiveFilePath, + archiveTempFolder: tempFolder, + createArchiveOnly + }); + + await handler.includeAssetAsync({ sourceFilePath: sourceFile, targetFilePath }); + await handler.includeAssetAsync({ + sourceFileContent: generatedContent, + targetFilePath: `${targetRootFolder}/generated.txt` + }); + await handler.finalizeAsync(); + + const entries: Map = await readTarAsync(archiveFilePath); + const archiveContent: Buffer = await FileSystem.readFileToBufferAsync(archiveFilePath); + if (ext === '.tar') { + expect(archiveContent.subarray(257, 262).toString()).toBe('ustar'); + } else { + expect(archiveContent.subarray(0, 2)).toEqual(Buffer.from([0x1f, 0x8b])); + } + + expect([...entries.keys()].sort()).toEqual(['generated.txt', 'nested/input.txt']); + expect(entries.get('nested/input.txt')?.data).toEqual(fileContent); + expect(entries.get('nested/input.txt')).toMatchObject({ + type: 'File' + }); + if (process.platform !== 'win32') { + expect(entries.get('nested/input.txt')?.mode).toBe( + // eslint-disable-next-line no-bitwise + (await FileSystem.getStatisticsAsync(sourceFile)).mode & 0o7777 + ); + } + + expect(entries.get('generated.txt')?.data.toString()).toBe(generatedContent); + expect(await FileSystem.existsAsync(targetFilePath)).toBe(!createArchiveOnly); + if (createArchiveOnly) { + expect(await FileSystem.readFolderItemNamesAsync(targetRootFolder)).toEqual([`deploy${ext}`]); + } + + expect(await FileSystem.readFolderItemNamesAsync(tempFolder)).toEqual([]); + } + }); + + it.each(['.tar', '.tar.gz', '.tgz'])('preserves symbolic links in %s archives', async (ext) => { + const linksFolder: string = `${testFolder}/links-${ext.slice(1)}`; + const linkPath: string = `${linksFolder}/nested/link`; + const linkTargetPath: string = `${linksFolder}/linked-folder`; + await FileSystem.ensureFolderAsync(`${linksFolder}/nested`); + await FileSystem.ensureFolderAsync(linkTargetPath); + await FileSystem.createSymbolicLinkFolderAsync({ newLinkPath: linkPath, linkTargetPath }); + const archiveFilePath: string = `${testFolder}/links${ext}`; + const manager: ArchiveManager = new ArchiveManager(ArchiveManager.getArchiveFormat(archiveFilePath)); + await manager.addToArchiveAsync({ filePath: linkPath, archivePath: 'nested\\link' }); + await manager.createArchiveAsync(archiveFilePath, { terminal, sourceFolder: linksFolder }); + + const entries: Map = await readTarAsync(archiveFilePath); + expect(entries.get('nested/link')).toMatchObject({ + type: 'SymbolicLink', + linkpath: expect.stringContaining('linked-folder'), + data: Buffer.alloc(0) + }); + }); + + it('continues to create ZIP archives', async () => { + const archiveFilePath: string = `${testFolder}/deploy.zip`; + const manager: ArchiveManager = new ArchiveManager(ArchiveManager.getArchiveFormat(archiveFilePath)); + await manager.addToArchiveAsync({ filePath: sourceFile, archivePath: 'nested\\input.txt' }); + await manager.addToArchiveAsync({ + filePath: `${sourceFolder}/generated.txt`, + archivePath: 'generated.txt' + }); + await manager.createArchiveAsync(archiveFilePath); + + const zip: JSZip = await JSZip.loadAsync(await FileSystem.readFileToBufferAsync(archiveFilePath)); + expect(await zip.file('nested/input.txt')?.async('nodebuffer')).toEqual(fileContent); + expect(await zip.file('generated.txt')?.async('string')).toBe(generatedContent); + }); + + it('reads ZIP assets in parallel while preserving entry order', async () => { + const archiveFilePath: string = `${testFolder}/parallel.zip`; + const manager: ArchiveManager = new ArchiveManager('zip'); + const stats = await FileSystem.getStatisticsAsync(sourceFile); + for (const archivePath of ['first.txt', 'second.txt']) { + await manager.addToArchiveAsync({ filePath: sourceFile, archivePath, stats }); + } + + const readSpy = jest + .spyOn(FileSystem, 'readFileToBufferAsync') + .mockImplementationOnce(async () => { + await Async.sleepAsync(0); + expect(readSpy).toHaveBeenCalledTimes(2); + return fileContent; + }) + .mockResolvedValueOnce(Buffer.from(generatedContent)); + await manager.createArchiveAsync(archiveFilePath); + + const zip: JSZip = await JSZip.loadAsync(await FileSystem.readFileToBufferAsync(archiveFilePath)); + expect(Object.keys(zip.files)).toEqual(['first.txt', 'second.txt']); + expect(await zip.file('first.txt')?.async('nodebuffer')).toEqual(fileContent); + expect(await zip.file('second.txt')?.async('string')).toBe(generatedContent); + }); + + it.each(['.zip', '.tar', '.tgz'])('writes generated %s assets only once per deployment', async (ext) => { + for (const createArchiveOnly of [false, true]) { + const targetRootFolder: string = `${testFolder}/single-write-${ext.slice(1)}-${createArchiveOnly}`; + await FileSystem.ensureFolderAsync(targetRootFolder); + const archiveFilePath: string = `${targetRootFolder}/deploy${ext}`; + const targetFilePath: string = `${targetRootFolder}/generated.txt`; + const handler: AssetHandler = createHandler(archiveFilePath, createArchiveOnly); + const writeSpy = jest.spyOn(FileSystem, 'writeFileAsync'); + const addSpy = jest.spyOn(ArchiveManager.prototype, 'addToArchiveAsync'); + await handler.includeAssetAsync({ sourceFileContent: generatedContent, targetFilePath }); + await handler.includeAssetAsync({ + sourceFileContent: '', + targetFilePath: `${targetRootFolder}/empty.txt` + }); + await handler.finalizeAsync(); + + const writes = writeSpy.mock.calls.filter(([, content]) => content === generatedContent); + expect(writes).toHaveLength(1); + const [[writtenPath]] = writes; + expect(addSpy).toHaveBeenCalledWith({ + filePath: writtenPath, + archivePath: 'generated.txt' + }); + if (createArchiveOnly) { + expect(Path.convertToSlashes(writtenPath)).toContain(`${Path.convertToSlashes(tempFolder)}/`); + expect(await FileSystem.existsAsync(targetFilePath)).toBe(false); + } else { + expect(writtenPath).toBe(targetFilePath); + } + + if (ext === '.zip') { + const zip: JSZip = await JSZip.loadAsync(await FileSystem.readFileToBufferAsync(archiveFilePath)); + expect(await zip.file('generated.txt')?.async('string')).toBe(generatedContent); + expect(await zip.file('empty.txt')?.async('string')).toBe(''); + } else { + const entries: Map = await readTarAsync(archiveFilePath); + expect(entries.get('generated.txt')?.data.toString()).toBe(generatedContent); + expect(entries.get('empty.txt')?.data.length).toBe(0); + } + + expect(await FileSystem.readFolderItemNamesAsync(tempFolder)).toEqual([]); + jest.restoreAllMocks(); + } + }); + + it('archives the materialized target rather than the original source in ZIP deployments', async () => { + const targetRootFolder: string = `${testFolder}/zip-target`; + await FileSystem.ensureFolderAsync(targetRootFolder); + const archiveFilePath: string = `${targetRootFolder}/deploy.zip`; + const targetFilePath: string = `${targetRootFolder}/input.txt`; + const handler: AssetHandler = createHandler(archiveFilePath, false); + await handler.includeAssetAsync({ sourceFilePath: sourceFile, targetFilePath }); + await FileSystem.writeFileAsync(targetFilePath, 'updated target'); + await handler.finalizeAsync(); + const zip: JSZip = await JSZip.loadAsync(await FileSystem.readFileToBufferAsync(archiveFilePath)); + expect(await zip.file('input.txt')?.async('string')).toBe('updated target'); + }); + + it('preserves executable permissions when staging archive-only assets', async () => { + const archiveFilePath: string = `${testFolder}/permissions.tar`; + const executablePath: string = `${sourceFolder}/executable.sh`; + const handler: AssetHandler = createHandler(archiveFilePath); + await handler.includeAssetAsync({ + sourceFilePath: executablePath, + targetFilePath: `${testFolder}/executable.sh` + }); + await handler.finalizeAsync(); + const entry: ITarEntry | undefined = (await readTarAsync(archiveFilePath)).get('executable.sh'); + expect(entry?.data).toEqual(await FileSystem.readFileToBufferAsync(executablePath)); + if (process.platform !== 'win32') { + expect(entry?.mode).toBe( + // eslint-disable-next-line no-bitwise + (await FileSystem.getStatisticsAsync(executablePath)).mode & 0o7777 + ); + } + }); + + it('uses native tar without staging materialized files', async () => { + const nativeTar: TarExecutable | undefined = await TarExecutable.tryInitializeAsync(terminal); + if (!nativeTar) { + throw new Error('Native tar is required for the native-tar test'); + } + + jest.spyOn(TarExecutable, 'tryInitializeAsync').mockResolvedValue(nativeTar); + const createSpy = jest.spyOn(nativeTar, 'tryCreateArchiveAsync'); + const archiveFilePath: string = `${testFolder}/native.tar`; + const manager: ArchiveManager = new ArchiveManager(ArchiveManager.getArchiveFormat(archiveFilePath)); + await manager.addToArchiveAsync({ filePath: sourceFile, archivePath: 'input.txt' }); + await manager.createArchiveAsync(archiveFilePath, { terminal, sourceFolder }); + expect(createSpy).toHaveBeenCalledWith( + expect.objectContaining({ baseFolderPath: sourceFolder, paths: ['input.txt'], gzip: false }) + ); + expect((await readTarAsync(archiveFilePath)).get('input.txt')?.data).toEqual(fileContent); + expect(await FileSystem.existsAsync(`${archiveFilePath}.log`)).toBe(false); + expect(await FileSystem.readFolderItemNamesAsync(tempFolder)).toEqual([]); + }); + + it.each(['available', 'unavailable'])( + 'memoizes %s native tar initialization for an archive manager', + async (availability) => { + const nativeTar: TarExecutable | undefined = await TarExecutable.tryInitializeAsync(terminal); + if (!nativeTar) { + throw new Error('Native tar is required for the initialization test'); + } + + const initializeSpy = jest + .spyOn(TarExecutable, 'tryInitializeAsync') + .mockResolvedValue(availability === 'available' ? nativeTar : undefined); + const manager: ArchiveManager = new ArchiveManager('tar'); + await manager.addToArchiveAsync({ filePath: sourceFile, archivePath: 'input.txt' }); + await Promise.all( + [1, 2].map(async (index) => { + const archiveFilePath: string = `${testFolder}/memoized-${availability}-${index}.tar`; + const archivePromise: Promise = manager.createArchiveAsync(archiveFilePath, { + terminal, + sourceFolder + }); + if (availability === 'available') { + await archivePromise; + expect((await readTarAsync(archiveFilePath)).get('input.txt')?.data).toEqual(fileContent); + } else { + await expect(archivePromise).rejects.toThrow('Native tar is required'); + } + }) + ); + expect(initializeSpy).toHaveBeenCalledTimes(1); + } + ); + + it('rejects unsupported extensions', () => { + expect(() => ArchiveManager.getArchiveFormat('deploy.gz')).toThrow('Supported archive file extensions'); + }); + + it('cleans up staging when generating an asset during finalization fails', async () => { + const archiveFilePath: string = `${testFolder}/copy-failure.tgz`; + const handler: AssetHandler = createHandler(archiveFilePath); + await handler.includeAssetAsync({ + sourceFileContent: generatedContent, + targetFilePath: `${testFolder}/generated.txt` + }); + jest.spyOn(FileSystem, 'writeFileAsync').mockRejectedValue(new Error('write failed')); + await expect( + handler.finalizeAsync({ + onAfterExtractSymlinksAsync: async () => { + await handler.includeAssetAsync({ + sourceFileContent: 'content', + targetFilePath: `${testFolder}/other.txt` + }); + } + }) + ).rejects.toThrow('write failed'); + expect(await FileSystem.readFolderItemNamesAsync(tempFolder)).toEqual([]); + expect(await FileSystem.existsAsync(archiveFilePath)).toBe(false); + }); + + it.each(['unavailable', 'incompatible'])('fails explicitly when native tar is %s', async (reason) => { + const nativeTar: TarExecutable | undefined = await TarExecutable.tryInitializeAsync(terminal); + const initializeSpy = jest.spyOn(TarExecutable, 'tryInitializeAsync'); + const archiveFilePath: string = `${testFolder}/failure-${reason}.tgz`; + if (reason === 'unavailable') { + initializeSpy.mockResolvedValue(undefined); + } else { + if (!nativeTar) { + throw new Error('Native tar is required for the incompatible-tar test'); + } + + jest.spyOn(nativeTar, 'tryCreateArchiveAsync').mockImplementation(async ({ baseFolderPath }) => { + expect(Path.convertToSlashes(baseFolderPath)).toContain( + `${Path.convertToSlashes(tempFolder)}/deploy-archive-` + ); + expect(await FileSystem.readFileToBufferAsync(`${baseFolderPath}/input.txt`)).toEqual(fileContent); + await FileSystem.writeFileAsync(archiveFilePath, 'partial archive'); + await FileSystem.writeFileAsync(`${archiveFilePath}.log`, 'native tar failed'); + return 1; + }); + initializeSpy.mockResolvedValue(nativeTar); + } + + const handler: AssetHandler = createHandler(archiveFilePath); + await handler.includeAssetAsync({ + sourceFilePath: sourceFile, + targetFilePath: `${testFolder}/input.txt` + }); + await expect(handler.finalizeAsync()).rejects.toThrow( + reason === 'unavailable' ? 'Native tar is required' : 'Native tar exited with code 1' + ); + expect(initializeSpy).toHaveBeenCalled(); + expect(await FileSystem.readFolderItemNamesAsync(tempFolder)).toEqual([]); + expect(await FileSystem.existsAsync(archiveFilePath)).toBe(false); + if (reason === 'incompatible') { + expect(await FileSystem.readFileAsync(`${archiveFilePath}.log`)).toBe('native tar failed'); + } + }); + + it('uses isolated staging folders for archive-only deployments started in the same millisecond', async () => { + const nativeTar: TarExecutable | undefined = await TarExecutable.tryInitializeAsync(terminal); + if (!nativeTar) { + throw new Error('Native tar is required for the staging test'); + } + + const createSpy = jest.spyOn(nativeTar, 'tryCreateArchiveAsync'); + const timestamp: number = Date.now(); + jest.spyOn(Date, 'now').mockReturnValue(timestamp); + const archivePaths: string[] = [`${testFolder}/concurrent-1.tgz`, `${testFolder}/concurrent-2.tgz`]; + await Promise.all( + archivePaths.map(async (archivePath, index) => { + const handler: AssetHandler = createHandler(archivePath); + await handler.includeAssetAsync({ + sourceFileContent: `content ${index}`, + targetFilePath: `${testFolder}/input.txt` + }); + await handler.finalizeAsync(); + expect((await readTarAsync(archivePath)).get('input.txt')?.data.toString()).toBe(`content ${index}`); + }) + ); + const stagingFolders: string[] = createSpy.mock.calls.map(([{ baseFolderPath }]) => baseFolderPath); + expect(new Set(stagingFolders).size).toBe(2); + for (const stagingFolder of stagingFolders) { + expect(Path.convertToSlashes(stagingFolder)).toContain( + `${Path.convertToSlashes(tempFolder)}/deploy-archive-${timestamp}-` + ); + expect(await FileSystem.existsAsync(stagingFolder)).toBe(false); + } + }); + + it('treats whitespace and leading dashes in member names literally', async () => { + const archiveFilePath: string = `${testFolder}/special-paths.tar`; + const memberNames: string[] = ['-C', ' leading spaces', 'nested/file with spaces.txt']; + if (process.platform !== 'win32') { + memberNames.push(' trailing spaces ', 'line\nbreak', 'line\rbreak'); + } + + const handler: AssetHandler = createHandler(archiveFilePath); + for (const archivePath of memberNames) { + await handler.includeAssetAsync({ + sourceFileContent: archivePath, + targetFilePath: `${testFolder}/${archivePath}` + }); + } + + await handler.finalizeAsync(); + const entries: Map = await readTarAsync(archiveFilePath); + for (const memberName of memberNames) { + expect(entries.get(memberName)?.data.toString()).toBe(memberName); + } + }); + + it('rejects archive entries outside the staging folder', async () => { + const manager: ArchiveManager = new ArchiveManager('tar'); + await expect( + manager.addToArchiveAsync({ filePath: sourceFile, archivePath: '../outside' }) + ).rejects.toThrow('relative paths within the archive'); + }); + + it.each(['..', '../outside.txt', 'nested/../../outside.txt'])( + 'rejects an asset path outside the target folder: %s', + async (relativePath) => { + const handler: AssetHandler = createHandler(`${testFolder}/outside.zip`); + await expect( + handler.includeAssetAsync({ + sourceFileContent: generatedContent, + targetFilePath: path.resolve(testFolder, relativePath) + }) + ).rejects.toThrow('The asset path must be under the target root folder'); + } + ); + + it('allows asset names that contain dots without traversing outside the target folder', async () => { + const archiveFilePath: string = `${testFolder}/dotted-name.zip`; + const handler: AssetHandler = createHandler(archiveFilePath); + await handler.includeAssetAsync({ + sourceFileContent: generatedContent, + targetFilePath: `${testFolder}/nested/..input.txt` + }); + await handler.finalizeAsync(); + const zip: JSZip = await JSZip.loadAsync(await FileSystem.readFileToBufferAsync(archiveFilePath)); + expect(await zip.file('nested/..input.txt')?.async('string')).toBe(generatedContent); + }); + + it('handles a native executable that exits before reading the file list', async () => { + const incompatibleTar: TarExecutable | undefined = await TarExecutable.tryInitializeAsync( + terminal, + process.execPath + ); + if (!incompatibleTar) { + throw new Error('The Node executable could not be located'); + } + + const exitCode: number = await incompatibleTar.tryCreateArchiveAsync({ + archivePath: `${testFolder}/incompatible.tgz`, + baseFolderPath: sourceFolder, + paths: new Array(10000).fill('input.txt'), + logFilePath: `${testFolder}/incompatible.log` + }); + expect(exitCode).not.toBe(0); + expect(await FileSystem.readFileAsync(`${testFolder}/incompatible.log`)).toContain('Exited with code'); + }); + + it('memoizes native discovery independently for each explicit executable', async () => { + const provider: StringBufferTerminalProvider = new StringBufferTerminalProvider(); + const discoveryTerminal: Terminal = new Terminal(provider); + const executablePath: string = `${testFolder}/memoized-tar`; + const [first, second] = await Promise.all([ + TarExecutable.tryInitializeAsync(discoveryTerminal, executablePath), + TarExecutable.tryInitializeAsync(discoveryTerminal, executablePath) + ]); + expect(first).toBe(second); + expect(provider.getVerboseOutput().match(/Trying to find/g)).toHaveLength(1); + const other: TarExecutable | undefined = await TarExecutable.tryInitializeAsync( + terminal, + process.execPath + ); + expect(first).not.toBe(other); + }); +}); diff --git a/libraries/package-extractor/src/test/PackageExtractor.test.ts b/libraries/package-extractor/src/test/PackageExtractor.test.ts index e16677fd277..fd6931ddcec 100644 --- a/libraries/package-extractor/src/test/PackageExtractor.test.ts +++ b/libraries/package-extractor/src/test/PackageExtractor.test.ts @@ -2,6 +2,7 @@ // See LICENSE in the project root for license information. import path from 'node:path'; +import fs from 'node:fs'; import type { ChildProcess } from 'node:child_process'; import { Executable, FileSystem, Sort } from '@rushstack/node-core-library'; @@ -52,6 +53,41 @@ describe(PackageExtractor.name, () => { const terminal = new Terminal(new StringBufferTerminalProvider()); const packageExtractor = new PackageExtractor(); + it('removes archive-only staging when extraction fails after copying a file', async () => { + const targetFolder: string = `${extractorTargetFolder}/archive-copy-failure`; + const archiveTempFolder: string = `${extractorTargetFolder}/archive-copy-failure-temp`; + await FileSystem.ensureEmptyFolderAsync(archiveTempFolder); + const copyFileAsync: typeof fs.promises.copyFile = fs.promises.copyFile; + const copySpy = jest + .spyOn(fs.promises, 'copyFile') + .mockImplementation(async (source, destination, mode) => { + await copyFileAsync(source, destination, mode); + throw new Error('copy failed after writing'); + }); + try { + await expect( + packageExtractor.extractAsync({ + mainProjectName: project1PackageName, + sourceRootFolder: repoRoot, + targetRootFolder: targetFolder, + overwriteExisting: true, + projectConfigurations: getDefaultProjectConfigurations(), + terminal, + createArchiveOnly: true, + createArchiveFilePath: 'deploy.tgz', + archiveTempFolder, + includeNpmIgnoreFiles: true, + linkCreation: 'none' + }) + ).rejects.toThrow('copy failed after writing'); + expect(copySpy).toHaveBeenCalled(); + expect(await FileSystem.readFolderItemNamesAsync(archiveTempFolder)).toEqual([]); + expect(await FileSystem.readFolderItemNamesAsync(targetFolder)).toEqual([]); + } finally { + copySpy.mockRestore(); + } + }); + it('should extract project', async () => { const targetFolder: string = path.join(extractorTargetFolder, 'extractor-output-01'); diff --git a/libraries/package-extractor/src/test/fixtures/archive/executable.sh b/libraries/package-extractor/src/test/fixtures/archive/executable.sh new file mode 100755 index 00000000000..59baf464cd5 --- /dev/null +++ b/libraries/package-extractor/src/test/fixtures/archive/executable.sh @@ -0,0 +1,2 @@ +#!/bin/sh +echo "Archive executable fixture." diff --git a/libraries/package-extractor/src/test/fixtures/archive/generated.txt b/libraries/package-extractor/src/test/fixtures/archive/generated.txt new file mode 100644 index 00000000000..9a4ea740cee --- /dev/null +++ b/libraries/package-extractor/src/test/fixtures/archive/generated.txt @@ -0,0 +1 @@ +Generated archive content. diff --git a/libraries/package-extractor/src/test/fixtures/archive/input.txt b/libraries/package-extractor/src/test/fixtures/archive/input.txt new file mode 100644 index 00000000000..d3773fd38f9 --- /dev/null +++ b/libraries/package-extractor/src/test/fixtures/archive/input.txt @@ -0,0 +1 @@ +Archive fixture content. diff --git a/libraries/rush-lib/src/api/test/__snapshots__/RushCommandLine.test.ts.snap b/libraries/rush-lib/src/api/test/__snapshots__/RushCommandLine.test.ts.snap index e28042fd3de..144bce05e7e 100644 --- a/libraries/rush-lib/src/api/test/__snapshots__/RushCommandLine.test.ts.snap +++ b/libraries/rush-lib/src/api/test/__snapshots__/RushCommandLine.test.ts.snap @@ -246,7 +246,7 @@ Object { "shortName": "-t", }, Object { - "description": "If specified, after the deployment has been prepared, \\"rush deploy\\" will create an archive containing the contents of the target folder. The newly created archive file will be placed according to the designated path, relative to the target folder. Supported file extensions: .zip", + "description": "If specified, after the deployment has been prepared, \\"rush deploy\\" will create an archive containing the contents of the target folder. The newly created archive file will be placed according to the designated path, relative to the target folder. Supported file extensions: .zip, .tar, .tar.gz, .tgz", "environmentVariable": undefined, "kind": "String", "longName": "--create-archive", diff --git a/libraries/rush-lib/src/cli/actions/DeployAction.ts b/libraries/rush-lib/src/cli/actions/DeployAction.ts index 62c9c33da88..a0eaeb06048 100644 --- a/libraries/rush-lib/src/cli/actions/DeployAction.ts +++ b/libraries/rush-lib/src/cli/actions/DeployAction.ts @@ -93,7 +93,7 @@ export class DeployAction extends BaseRushAction { 'If specified, after the deployment has been prepared, "rush deploy"' + ' will create an archive containing the contents of the target folder.' + ' The newly created archive file will be placed according to the designated path, relative' + - ' to the target folder. Supported file extensions: .zip' + ' to the target folder. Supported file extensions: .zip, .tar, .tar.gz, .tgz' }); this.#createArchiveOnly = this.defineFlagParameter({ @@ -220,6 +220,7 @@ export class DeployAction extends BaseRushAction { projectConfigurations, dependencyConfigurations: scenarioConfiguration.json.dependencySettings, createArchiveFilePath, + archiveTempFolder: this.rushConfiguration.commonTempFolder, createArchiveOnly, subspaces: Array.from(subspaces.values()) }); diff --git a/libraries/rush-lib/src/cli/test/__snapshots__/CommandLineHelp.test.ts.snap b/libraries/rush-lib/src/cli/test/__snapshots__/CommandLineHelp.test.ts.snap index 6d2357c00e9..7617470e7a9 100644 --- a/libraries/rush-lib/src/cli/test/__snapshots__/CommandLineHelp.test.ts.snap +++ b/libraries/rush-lib/src/cli/test/__snapshots__/CommandLineHelp.test.ts.snap @@ -481,7 +481,7 @@ Optional arguments: contents of the target folder. The newly created archive file will be placed according to the designated path, relative to the target folder. - Supported file extensions: .zip + Supported file extensions: .zip, .tar, .tar.gz, .tgz --create-archive-only If specified, \\"rush deploy\\" will only create an archive containing the contents of the target folder. diff --git a/libraries/rush-lib/src/logic/buildCache/OperationBuildCache.ts b/libraries/rush-lib/src/logic/buildCache/OperationBuildCache.ts index bf3476fdfc3..4ca883b405e 100644 --- a/libraries/rush-lib/src/logic/buildCache/OperationBuildCache.ts +++ b/libraries/rush-lib/src/logic/buildCache/OperationBuildCache.ts @@ -6,13 +6,13 @@ import * as crypto from 'node:crypto'; import { FileSystem, type FolderItem, InternalError, Async, LockFile } from '@rushstack/node-core-library'; import type { ITerminal } from '@rushstack/terminal'; +import { TarExecutable } from '@rushstack/package-extractor'; import type { RushConfigurationProject } from '../../api/RushConfigurationProject'; import type { BuildCacheConfiguration } from '../../api/BuildCacheConfiguration'; import type { ICloudBuildCacheProvider } from './ICloudBuildCacheProvider'; import type { FileSystemBuildCacheProvider } from './FileSystemBuildCacheProvider'; -import { TarExecutable } from '../../utilities/TarExecutable'; -import { EnvironmentVariableNames } from '../../api/EnvironmentConfiguration'; +import { EnvironmentConfiguration, EnvironmentVariableNames } from '../../api/EnvironmentConfiguration'; import type { IBaseOperationExecutionResult } from '../operations/IOperationExecutionResult'; import { OutputFolderReceipt, type PendingOutputFolderReceipt } from './OutputFolderReceipt'; import { tryRestoreThroughStagingFolderAsync } from './StagedRestore'; @@ -120,7 +120,7 @@ function _getTempLocalCacheEntryPath(finalLocalCacheEntryPath: string): string { function _tryGetTarUtility(terminal: ITerminal): Promise { if (!_tarUtilityPromise) { - _tarUtilityPromise = TarExecutable.tryInitializeAsync(terminal); + _tarUtilityPromise = TarExecutable.tryInitializeAsync(terminal, EnvironmentConfiguration.tarBinaryPath); } return _tarUtilityPromise; @@ -583,58 +583,58 @@ export class OperationBuildCache { let localCacheEntryPath: string | undefined; const tarUtility: TarExecutable | undefined = await _tryGetTarUtility(terminal); - if (tarUtility) { - const finalLocalCacheEntryPath: string = this.#localBuildCacheProvider.getCacheEntryPath(cacheId); - const tempLocalCacheEntryPath: string = _getTempLocalCacheEntryPath(finalLocalCacheEntryPath); - - const logFilePath: string = this.#getTarLogFilePath(cacheId, 'tar'); - const tarExitCode: number = await tarUtility.tryCreateArchiveFromProjectPathsAsync({ - archivePath: tempLocalCacheEntryPath, - paths: filesToCache.outputFilePaths, - project: this.#project, - logFilePath, - baseFolderPath: deferredWrite?.baseFolderPath, - abortSignal: deferredWrite?.abortSignal - }); + if (!tarUtility) { + terminal.writeWarningLine( + `Unable to locate "tar". Please ensure that "tar" is on your PATH environment variable, or set the ` + + `${EnvironmentVariableNames.RUSH_TAR_BINARY_PATH} environment variable to the full path to the "tar" binary.` + ); + return false; + } + + const finalLocalCacheEntryPath: string = this.#localBuildCacheProvider.getCacheEntryPath(cacheId); + const tempLocalCacheEntryPath: string = _getTempLocalCacheEntryPath(finalLocalCacheEntryPath); + + const logFilePath: string = this.#getTarLogFilePath(cacheId, 'tar'); + const baseFolderPath: string = deferredWrite?.baseFolderPath ?? this.#project.projectFolder; + const tarExitCode: number = await tarUtility.tryCreateArchiveAsync({ + archivePath: tempLocalCacheEntryPath, + paths: filesToCache.outputFilePaths, + logFilePath, + baseFolderPath, + abortSignal: deferredWrite?.abortSignal + }); - if (tarExitCode === 0) { - // Move after the archive is finished so that if the process is interrupted we aren't left with an invalid file + if (tarExitCode === 0) { + // Move after the archive is finished so that if the process is interrupted we aren't left with an invalid file + try { + await Async.runWithRetriesAsync({ + action: () => + FileSystem.moveAsync({ + sourcePath: tempLocalCacheEntryPath, + destinationPath: finalLocalCacheEntryPath, + overwrite: true + }), + maxRetries: 2, + retryDelayMs: 500 + }); + } catch (moveError) { try { - await Async.runWithRetriesAsync({ - action: () => - FileSystem.moveAsync({ - sourcePath: tempLocalCacheEntryPath, - destinationPath: finalLocalCacheEntryPath, - overwrite: true - }), - maxRetries: 2, - retryDelayMs: 500 - }); - } catch (moveError) { - try { - await FileSystem.deleteFileAsync(tempLocalCacheEntryPath); - } catch (deleteError) { - // Ignored - } - throw moveError; - } - localCacheEntryPath = finalLocalCacheEntryPath; - await this.#tryCommitReceiptAsync(terminal, pendingReceipt, cacheId, filesToCache.outputFilePaths); - } else { - if (deferredWrite) { - // A write in the background can be cut short, so it deletes its partial archive. await FileSystem.deleteFileAsync(tempLocalCacheEntryPath); + } catch (deleteError) { + // Ignored } - terminal.writeWarningLine( - `"tar" exited with code ${tarExitCode} while attempting to create the cache entry. ` + - `See "${logFilePath}" for logs from the tar process.` - ); - return false; + throw moveError; } + localCacheEntryPath = finalLocalCacheEntryPath; + await this.#tryCommitReceiptAsync(terminal, pendingReceipt, cacheId, filesToCache.outputFilePaths); } else { + if (deferredWrite) { + // A write in the background can be cut short, so it deletes its partial archive. + await FileSystem.deleteFileAsync(tempLocalCacheEntryPath); + } terminal.writeWarningLine( - `Unable to locate "tar". Please ensure that "tar" is on your PATH environment variable, or set the ` + - `${EnvironmentVariableNames.RUSH_TAR_BINARY_PATH} environment variable to the full path to the "tar" binary.` + `"tar" exited with code ${tarExitCode} while attempting to create the cache entry. ` + + `See "${logFilePath}" for logs from the tar process.` ); return false; } diff --git a/libraries/rush-lib/src/logic/buildCache/test/OperationBuildCache.test.ts b/libraries/rush-lib/src/logic/buildCache/test/OperationBuildCache.test.ts index 1a944aa8172..c2088c648ba 100644 --- a/libraries/rush-lib/src/logic/buildCache/test/OperationBuildCache.test.ts +++ b/libraries/rush-lib/src/logic/buildCache/test/OperationBuildCache.test.ts @@ -8,7 +8,7 @@ import type { BuildCacheConfiguration } from '../../../api/BuildCacheConfigurati import type { RushConfigurationProject } from '../../../api/RushConfigurationProject'; import type { IGenerateCacheEntryIdOptions } from '../CacheEntryId'; import type { FileSystemBuildCacheProvider } from '../FileSystemBuildCacheProvider'; -import type { TarExecutable } from '../../../utilities/TarExecutable'; +import type { TarExecutable } from '@rushstack/package-extractor'; import { OperationBuildCache, diff --git a/libraries/rush-lib/src/logic/buildCache/test/OperationBuildCacheDeferredWrites.test.ts b/libraries/rush-lib/src/logic/buildCache/test/OperationBuildCacheDeferredWrites.test.ts index 493650d404e..4b9c8063356 100644 --- a/libraries/rush-lib/src/logic/buildCache/test/OperationBuildCacheDeferredWrites.test.ts +++ b/libraries/rush-lib/src/logic/buildCache/test/OperationBuildCacheDeferredWrites.test.ts @@ -10,7 +10,7 @@ import { StringBufferTerminalProvider, Terminal } from '@rushstack/terminal'; import type { BuildCacheConfiguration } from '../../../api/BuildCacheConfiguration'; import type { RushConfigurationProject } from '../../../api/RushConfigurationProject'; -import { TarExecutable } from '../../../utilities/TarExecutable'; +import { TarExecutable } from '@rushstack/package-extractor'; import type { IGenerateCacheEntryIdOptions } from '../CacheEntryId'; import { DEFERRED_CACHE_ENTRY_STAGING_FOLDER_NAME, diff --git a/libraries/rush-lib/src/logic/buildCache/test/OperationBuildCacheReceipt.test.ts b/libraries/rush-lib/src/logic/buildCache/test/OperationBuildCacheReceipt.test.ts index 979e5df9e41..1a7b7d3199b 100644 --- a/libraries/rush-lib/src/logic/buildCache/test/OperationBuildCacheReceipt.test.ts +++ b/libraries/rush-lib/src/logic/buildCache/test/OperationBuildCacheReceipt.test.ts @@ -9,7 +9,7 @@ import { StringBufferTerminalProvider, Terminal, type ITerminal } from '@rushsta import type { BuildCacheConfiguration } from '../../../api/BuildCacheConfiguration'; import type { RushConfigurationProject } from '../../../api/RushConfigurationProject'; -import type { ICreateArchiveOptions, IUntarOptions, TarExecutable } from '../../../utilities/TarExecutable'; +import type { ICreateArchiveOptions, IUntarOptions, TarExecutable } from '@rushstack/package-extractor'; import type { IBaseOperationExecutionResult } from '../../operations/IOperationExecutionResult'; import type { IGenerateCacheEntryIdOptions } from '../CacheEntryId'; import { DeferredCacheEntryWrites } from '../DeferredCacheEntryWrites'; @@ -69,7 +69,7 @@ describe('OperationBuildCache receipts', () => { return 0; }); createArchiveMock = jest.fn( - async ({ archivePath, paths, project, baseFolderPath, abortSignal }: ICreateArchiveOptions) => { + async ({ archivePath, paths, baseFolderPath, abortSignal }: ICreateArchiveOptions) => { await waitForGateAsync(abortSignal); if (abortSignal?.aborted) { // As a killed tar would @@ -77,12 +77,9 @@ describe('OperationBuildCache receipts', () => { } const archive: FakeArchive = {}; for (const relativePath of paths) { - archive[relativePath] = fs.readFileSync( - path.join(baseFolderPath ?? project.projectFolder, relativePath), - 'utf8' - ); + archive[relativePath] = fs.readFileSync(path.join(baseFolderPath, relativePath), 'utf8'); } - tarHook?.(project.projectFolder); + tarHook?.(projectFolder); fs.writeFileSync(archivePath, JSON.stringify(archive)); return 0; } @@ -90,7 +87,7 @@ describe('OperationBuildCache receipts', () => { _setTarUtilityPromiseForTesting( Promise.resolve({ tryUntarAsync: untarMock, - tryCreateArchiveFromProjectPathsAsync: createArchiveMock + tryCreateArchiveAsync: createArchiveMock } as unknown as TarExecutable) ); }); diff --git a/libraries/rush-lib/src/logic/buildCache/test/StagedRestore.test.ts b/libraries/rush-lib/src/logic/buildCache/test/StagedRestore.test.ts index 698f31b3468..65d54cad61b 100644 --- a/libraries/rush-lib/src/logic/buildCache/test/StagedRestore.test.ts +++ b/libraries/rush-lib/src/logic/buildCache/test/StagedRestore.test.ts @@ -9,7 +9,7 @@ import { StringBufferTerminalProvider, Terminal, type ITerminal } from '@rushsta import type { BuildCacheConfiguration } from '../../../api/BuildCacheConfiguration'; import type { RushConfigurationProject } from '../../../api/RushConfigurationProject'; -import type { IUntarOptions, TarExecutable } from '../../../utilities/TarExecutable'; +import type { IUntarOptions, TarExecutable } from '@rushstack/package-extractor'; import type { IBaseOperationExecutionResult } from '../../operations/IOperationExecutionResult'; import type { IGenerateCacheEntryIdOptions } from '../CacheEntryId'; import { OperationBuildCache, _setTarUtilityPromiseForTesting } from '../OperationBuildCache'; diff --git a/libraries/rush-lib/src/utilities/test/TarExecutable.test.ts b/libraries/rush-lib/src/utilities/test/TarExecutable.test.ts index 78d6568bddb..6768104825a 100644 --- a/libraries/rush-lib/src/utilities/test/TarExecutable.test.ts +++ b/libraries/rush-lib/src/utilities/test/TarExecutable.test.ts @@ -2,20 +2,17 @@ // See LICENSE in the project root for license information. import * as fs from 'node:fs'; +import { ChildProcess } from 'node:child_process'; import * as os from 'node:os'; import * as path from 'node:path'; import { performance } from 'node:perf_hooks'; +import { PassThrough } from 'node:stream'; import { setTimeout as delayAsync } from 'node:timers/promises'; +import { Executable } from '@rushstack/node-core-library'; import { StringBufferTerminalProvider, Terminal } from '@rushstack/terminal'; -import type { RushConfigurationProject } from '../../api/RushConfigurationProject'; -import { TarExecutable } from '../TarExecutable'; - -// Archives are created from the base folder, so this folder is never used. -const project: RushConfigurationProject = { - projectFolder: path.join(os.tmpdir(), 'rush-tar-executable-missing-project') -} as RushConfigurationProject; +import { TarExecutable } from '@rushstack/package-extractor'; describe(TarExecutable.name, () => { let tar: TarExecutable; @@ -40,15 +37,42 @@ describe(TarExecutable.name, () => { }); afterEach(() => { + jest.restoreAllMocks(); fs.rmSync(folderPath, { recursive: true, force: true }); }); + it.each(['EPIPE', 'EOF'])('logs %s when tar exits before reading its file list', async (code) => { + const childProcess: ChildProcess = new ChildProcess(); + childProcess.stdin = new PassThrough(); + childProcess.stdout = new PassThrough(); + childProcess.stderr = new PassThrough(); + jest.spyOn(Executable, 'spawn').mockImplementationOnce(() => { + queueMicrotask(() => { + childProcess.stdin!.emit('error', Object.assign(new Error('pipe closed'), { code })); + childProcess.emit('close', 1, null); + }); + return childProcess; + }); + + const logFilePath: string = `${folderPath}/closed-pipe.log`; + expect( + await tar.tryCreateArchiveAsync({ + archivePath: `${folderPath}/closed-pipe.tar.gz`, + paths: ['lib/index.js'], + baseFolderPath, + logFilePath + }) + ).toBe(1); + const log: string = fs.readFileSync(logFilePath, 'utf8'); + expect(log).toContain('[stdin] pipe closed'); + expect(log).toContain('Exited with code "1"'); + }); + it('names the members of an archive from its base folder', async () => { const archivePath: string = path.join(folderPath, 'entry.tar.gz'); - const exitCode: number = await tar.tryCreateArchiveFromProjectPathsAsync({ + const exitCode: number = await tar.tryCreateArchiveAsync({ archivePath, paths: ['lib/index.js'], - project, baseFolderPath, logFilePath: path.join(folderPath, 'create.log') }); @@ -69,10 +93,9 @@ describe(TarExecutable.name, () => { it('kills tar at once when its signal was aborted before it started', async () => { const logFilePath: string = path.join(folderPath, 'create.log'); - const exitCode: number = await tar.tryCreateArchiveFromProjectPathsAsync({ + const exitCode: number = await tar.tryCreateArchiveAsync({ archivePath: path.join(folderPath, 'entry.tar.gz'), paths: ['lib/index.js'], - project, baseFolderPath, logFilePath, abortSignal: AbortSignal.abort() @@ -93,10 +116,9 @@ describe(TarExecutable.name, () => { } const logFilePath: string = path.join(folderPath, 'create.log'); const abortController: AbortController = new AbortController(); - const exitCodePromise: Promise = tar.tryCreateArchiveFromProjectPathsAsync({ + const exitCodePromise: Promise = tar.tryCreateArchiveAsync({ archivePath: path.join(folderPath, 'entry.tar.gz'), paths: ['lib/index.js', 'large.bin'], - project, baseFolderPath, logFilePath, abortSignal: abortController.signal