"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.PdmProcessor = void 0;
const tslib_1 = require("tslib");
const is_1 = tslib_1.__importDefault(require("@sindresorhus/is"));
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 pypi_1 = require("../../../datasource/pypi");
const utils_1 = require("../utils");
class PdmProcessor {
    process(project, deps) {
        const pdm = project.tool?.pdm;
        if (is_1.default.nullOrUndefined(pdm)) {
            return deps;
        }
        deps.push(...(0, utils_1.parseDependencyGroupRecord)('tool.pdm.dev-dependencies', pdm['dev-dependencies']));
        const pdmSource = pdm.source;
        if (is_1.default.nullOrUndefined(pdmSource)) {
            return deps;
        }
        // add pypi default url, if there is no source declared with the name `pypi`. https://daobook.github.io/pdm/pyproject/tool-pdm/#specify-other-sources-for-finding-packages
        const containsPyPiUrl = pdmSource.some((value) => value.name === 'pypi');
        const registryUrls = [];
        if (!containsPyPiUrl) {
            registryUrls.push(pypi_1.PypiDatasource.defaultURL);
        }
        for (const source of pdmSource) {
            registryUrls.push(source.url);
        }
        for (const dep of deps) {
            dep.registryUrls = registryUrls;
        }
        return deps;
    }
    async updateArtifacts(updateArtifact) {
        const { config, updatedDeps, packageFileName } = updateArtifact;
        const isLockFileMaintenance = config.updateType === 'lockFileMaintenance';
        // abort if no lockfile is defined
        const lockFileName = (0, fs_1.getSiblingFileName)(packageFileName, 'pdm.lock');
        try {
            const existingLockFileContent = await (0, fs_1.readLocalFile)(lockFileName, 'utf8');
            if (is_1.default.nullOrUndefined(existingLockFileContent)) {
                logger_1.logger.debug('No pdm.lock found');
                return null;
            }
            const pythonConstraint = {
                toolName: 'python',
                constraint: config.constraints?.python,
            };
            const pdmConstraint = {
                toolName: 'pdm',
                constraint: config.constraints?.pdm,
            };
            const execOptions = {
                cwdFile: packageFileName,
                docker: {},
                toolConstraints: [pythonConstraint, pdmConstraint],
            };
            // on lockFileMaintenance do not specify any packages and update the complete lock file
            // else only update specific packages
            let packageList = '';
            if (!isLockFileMaintenance) {
                packageList = ' ';
                packageList += updatedDeps.map((value) => value.packageName).join(' ');
            }
            const cmd = `pdm update${packageList}`;
            await (0, exec_1.exec)(cmd, execOptions);
            // check for changes
            const fileChanges = [];
            const newLockContent = await (0, fs_1.readLocalFile)(lockFileName, 'utf8');
            const isLockFileChanged = existingLockFileContent !== newLockContent;
            if (isLockFileChanged) {
                fileChanges.push({
                    file: {
                        type: 'addition',
                        path: lockFileName,
                        contents: newLockContent,
                    },
                });
            }
            else {
                logger_1.logger.debug('pdm.lock is unchanged');
            }
            return fileChanges.length ? fileChanges : null;
        }
        catch (err) {
            // istanbul ignore if
            if (err.message === error_messages_1.TEMPORARY_ERROR) {
                throw err;
            }
            logger_1.logger.debug({ err }, 'Failed to update PDM lock file');
            return [
                {
                    artifactError: {
                        lockFile: lockFileName,
                        stderr: err.message,
                    },
                },
            ];
        }
    }
}
exports.PdmProcessor = PdmProcessor;
//# sourceMappingURL=pdm.js.map