"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.updateArtifacts = void 0;
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 regex_1 = require("../../../util/regex");
function getFlutterConstraint(lockFileContent) {
    return (0, regex_1.regEx)(/^\tflutter: ['"](?<flutterVersion>.*)['"]$/m).exec(lockFileContent)?.groups?.flutterVersion;
}
function getDartConstraint(lockFileContent) {
    return (0, regex_1.regEx)(/^\tdart: ['"](?<dartVersion>.*)['"]$/m).exec(lockFileContent)
        ?.groups?.dartVersion;
}
async function updateArtifacts({ packageFileName, updatedDeps, newPackageFileContent, config, }) {
    if (!(config.updateType === 'lockFileMaintenance' ||
        config.updateType === 'lockfileUpdate') &&
        updatedDeps.length < 1) {
        return null;
    }
    const lockFileName = (0, fs_1.getSiblingFileName)(packageFileName, 'pubspec.lock');
    const oldLockFileContent = await (0, fs_1.readLocalFile)(lockFileName, 'utf8');
    if (!oldLockFileContent) {
        return null;
    }
    try {
        await (0, fs_1.writeLocalFile)(packageFileName, newPackageFileContent);
        const isFlutter = newPackageFileContent.includes('sdk: flutter');
        const toolName = isFlutter ? 'flutter' : 'dart';
        const constraint = isFlutter
            ? config.constraints?.flutter ?? getFlutterConstraint(oldLockFileContent)
            : config.constraints?.dart ?? getDartConstraint(oldLockFileContent);
        await (0, exec_1.exec)(`${toolName} pub upgrade`, {
            cwdFile: packageFileName,
            docker: {},
            toolConstraints: [
                {
                    toolName,
                    constraint,
                },
            ],
        });
        const newLockFileContent = await (0, fs_1.readLocalFile)(lockFileName, 'utf8');
        if (oldLockFileContent === newLockFileContent ||
            newLockFileContent === undefined) {
            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({ err }, `Failed to update ${lockFileName} file`);
        return [
            {
                artifactError: {
                    lockFile: lockFileName,
                    stderr: err.message,
                },
            },
        ];
    }
}
exports.updateArtifacts = updateArtifacts;
//# sourceMappingURL=artifacts.js.map