"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.updateArtifacts = void 0;
const tslib_1 = require("tslib");
const is_1 = tslib_1.__importDefault(require("@sindresorhus/is"));
const shlex_1 = require("shlex");
const error_messages_1 = require("../../../constants/error-messages");
const logger_1 = require("../../../logger");
const exec_1 = require("../../../util/exec");
const fs_1 = require("../../../util/fs");
const utils_1 = require("./utils");
const SDK_NAMES = ['dart', 'flutter'];
const PUB_GET_COMMAND = 'pub get --no-precompile';
async function updateArtifacts({ packageFileName, updatedDeps, newPackageFileContent, config, }) {
    logger_1.logger.debug(`pub.updateArtifacts(${packageFileName})`);
    const isLockFileMaintenance = config.updateType === 'lockFileMaintenance';
    if (is_1.default.emptyArray(updatedDeps) && !isLockFileMaintenance) {
        logger_1.logger.debug('No updated pub deps - returning null');
        return null;
    }
    const lockFileName = (0, fs_1.getSiblingFileName)(packageFileName, 'pubspec.lock');
    const oldLockFileContent = await (0, fs_1.readLocalFile)(lockFileName, 'utf8');
    if (!oldLockFileContent) {
        logger_1.logger.debug('No pubspec.lock found');
        return null;
    }
    try {
        await (0, fs_1.writeLocalFile)(packageFileName, newPackageFileContent);
        const isFlutter = newPackageFileContent.includes('sdk: flutter');
        const toolName = isFlutter ? 'flutter' : 'dart';
        const cmd = getExecCommand(toolName, updatedDeps, isLockFileMaintenance);
        let constraint = config.constraints?.[toolName];
        if (!constraint) {
            const pubspec = (0, utils_1.parsePubspec)(packageFileName, newPackageFileContent);
            const pubspecToolName = isFlutter ? 'flutter' : 'sdk';
            constraint = pubspec?.environment[pubspecToolName];
            if (!constraint) {
                const pubspecLock = (0, utils_1.parsePubspecLock)(lockFileName, oldLockFileContent);
                constraint = pubspecLock?.sdks[toolName];
            }
        }
        const execOptions = {
            cwdFile: packageFileName,
            docker: {},
            toolConstraints: [
                {
                    toolName,
                    constraint,
                },
            ],
        };
        await (0, exec_1.exec)(cmd, execOptions);
        const newLockFileContent = await (0, fs_1.readLocalFile)(lockFileName, 'utf8');
        if (oldLockFileContent === newLockFileContent) {
            return null;
        }
        return [
            {
                file: {
                    type: 'addition',
                    path: lockFileName,
                    contents: newLockFileContent,
                },
            },
        ];
    }
    catch (err) {
        // istanbul ignore if
        if (err.message === error_messages_1.TEMPORARY_ERROR) {
            throw err;
        }
        logger_1.logger.warn({ lockfile: lockFileName, err }, `Failed to update lock file`);
        return [
            {
                artifactError: {
                    lockFile: lockFileName,
                    stderr: err.message,
                },
            },
        ];
    }
}
exports.updateArtifacts = updateArtifacts;
function getExecCommand(toolName, updatedDeps, isLockFileMaintenance) {
    if (isLockFileMaintenance) {
        return `${toolName} pub upgrade`;
    }
    else {
        const depNames = updatedDeps.map((dep) => dep.depName).filter(is_1.default.string);
        if (depNames.length === 1 && SDK_NAMES.includes(depNames[0])) {
            return `${toolName} ${PUB_GET_COMMAND}`;
        }
        // If there are two updated dependencies and both of them are SDK updates (Dart and Flutter),
        // we use Flutter over Dart to run `pub get` as it is a Flutter project.
        else if (depNames.length === 2 &&
            depNames.filter((depName) => SDK_NAMES.includes(depName)).length === 2) {
            return `flutter ${PUB_GET_COMMAND}`;
        }
        else {
            const depNamesCmd = depNames
                .filter((depName) => !SDK_NAMES.includes(depName))
                .map(shlex_1.quote)
                .join(' ');
            return `${toolName} pub upgrade ${depNamesCmd}`;
        }
    }
}
//# sourceMappingURL=artifacts.js.map