import { TEMPORARY_ERROR } from "../../../constants/error-messages.js";
import { logger } from "../../../logger/index.js";
import { getParentDir, getSiblingFileName, readLocalFile, writeLocalFile } from "../../../util/fs/index.js";
import { exec } from "../../../util/exec/index.js";
import { getRepoStatus } from "../../../util/git/index.js";

//#region lib/modules/manager/vendir/artifacts.ts
async function updateArtifacts({ packageFileName, newPackageFileContent, config }) {
	logger.debug(`vendir.updateArtifacts(${packageFileName})`);
	const lockFileName = getSiblingFileName(packageFileName, "vendir.lock.yml");
	if (!lockFileName) {
		logger.warn("No vendir.lock.yml found");
		return null;
	}
	const existingLockFileContent = await readLocalFile(lockFileName, "utf8");
	if (!existingLockFileContent) {
		logger.warn("Empty vendir.lock.yml found");
		return null;
	}
	try {
		await writeLocalFile(packageFileName, newPackageFileContent);
		logger.debug("Updating Vendir artifacts");
		await exec(`vendir sync`, {
			cwdFile: packageFileName,
			docker: {},
			toolConstraints: [{
				toolName: "vendir",
				constraint: config.constraints?.vendir
			}, {
				toolName: "helm",
				constraint: config.constraints?.helm
			}]
		});
		logger.debug("Returning updated Vendir artifacts");
		const fileChanges = [];
		const newVendirLockContent = await readLocalFile(lockFileName, "utf8");
		if (existingLockFileContent !== newVendirLockContent) fileChanges.push({ file: {
			type: "addition",
			path: lockFileName,
			contents: newVendirLockContent
		} });
		logger.debug("Adding Sync'd files to git");
		const vendorDir = getParentDir(packageFileName);
		const status = await getRepoStatus();
		if (status) {
			const modifiedFiles = status.modified ?? [];
			const notAddedFiles = status.not_added;
			const deletedFiles = status.deleted ?? [];
			for (const f of modifiedFiles.concat(notAddedFiles)) {
				const isFileInVendorDir = f.startsWith(vendorDir);
				if (vendorDir || isFileInVendorDir) fileChanges.push({ file: {
					type: "addition",
					path: f,
					contents: await readLocalFile(f)
				} });
			}
			for (const f of deletedFiles) fileChanges.push({ file: {
				type: "deletion",
				path: f
			} });
		} else logger.error("Failed to get git status");
		return fileChanges.length ? fileChanges : null;
	} catch (err) {
		if (err.message === TEMPORARY_ERROR) throw err;
		logger.debug({ err }, "Failed to update Vendir lock file");
		return [{ artifactError: {
			lockFile: lockFileName,
			stderr: err.message
		} }];
	}
}

//#endregion
export { updateArtifacts };
//# sourceMappingURL=artifacts.js.map