// Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the MIT license.
// See LICENSE in the project root for license information.
import * as path from 'node:path';
import * as tar from 'tar';
import { FileConstants, FileSystem, PosixModeBits } from '@rushstack/node-core-library';
import { RushConstants } from './RushConstants';
// The PosixModeBits are intended to be used with bitwise operations.
/* eslint-disable no-bitwise */
export class TempProjectHelper {
    constructor(rushConfiguration, subspace) {
        this._rushConfiguration = rushConfiguration;
        this._subspace = subspace;
    }
    /**
     * Deletes the existing tarball and creates a tarball for the given rush project
     */
    createTempProjectTarball(rushProject) {
        FileSystem.ensureFolder(path.resolve(this._subspace.getSubspaceTempFolderPath(), 'projects'));
        const tarballFile = this.getTarballFilePath(rushProject);
        const tempProjectFolder = this.getTempProjectFolder(rushProject);
        FileSystem.deleteFile(tarballFile);
        // NPM expects the root of the tarball to have a directory called 'package'
        const npmPackageFolder = 'package';
        const tarOptions = {
            gzip: true,
            file: tarballFile,
            cwd: tempProjectFolder,
            portable: true,
            noMtime: true,
            noPax: true,
            sync: true,
            prefix: npmPackageFolder,
            filter: (tarPath, stat) => {
                if (!this._rushConfiguration.experimentsConfiguration.configuration.noChmodFieldInTarHeaderNormalization) {
                    stat.mode =
                        (stat.mode & ~0x1ff) | PosixModeBits.AllRead | PosixModeBits.UserWrite | PosixModeBits.AllExecute;
                }
                return true;
            }
        };
        // create the new tarball
        tar.create(tarOptions, [FileConstants.PackageJson]);
    }
    /**
     * Gets the path to the tarball
     * Example: "C:\MyRepo\common\temp\projects\my-project-2.tgz"
     */
    getTarballFilePath(project) {
        return path.join(this._subspace.getSubspaceTempFolderPath(), RushConstants.rushTempProjectsFolderName, `${project.unscopedTempProjectName}.tgz`);
    }
    getTempProjectFolder(rushProject) {
        const unscopedTempProjectName = rushProject.unscopedTempProjectName;
        return path.join(this._subspace.getSubspaceTempFolderPath(), RushConstants.rushTempProjectsFolderName, unscopedTempProjectName);
    }
}
//# sourceMappingURL=TempProjectHelper.js.map