import { logger } from "../../../logger/index.js";
import { readLocalFile } from "../../../util/fs/index.js";
import { MavenDatasource } from "../../datasource/maven/index.js";
import { isXmlElement } from "../nuget/util.js";
import { XmlDocument } from "xmldoc";
//#region lib/modules/manager/ant/extract.ts
const scopeNames = new Set([
	"compile",
	"runtime",
	"test",
	"provided",
	"system"
]);
function getDependencyType(scope) {
	if (scope && scopeNames.has(scope)) return scope;
	return "compile";
}
function collectDependency(node) {
	const { groupId, artifactId, version, scope } = node.attr;
	if (!version || !groupId || !artifactId) return null;
	return {
		datasource: MavenDatasource.id,
		depName: `${groupId}:${artifactId}`,
		currentValue: version,
		depType: getDependencyType(scope),
		registryUrls: []
	};
}
function walkNode(node, deps) {
	for (const child of node.children) {
		if (!isXmlElement(child)) continue;
		if (child.name === "dependency") {
			const dep = collectDependency(child);
			if (dep) deps.push(dep);
		} else walkNode(child, deps);
	}
}
function extractPackageFile(content, packageFile) {
	let doc;
	try {
		doc = new XmlDocument(content);
	} catch {
		logger.debug(`ant manager: could not parse XML ${packageFile}`);
		return null;
	}
	const deps = [];
	walkNode(doc, deps);
	if (deps.length === 0) return null;
	return { deps };
}
async function walkXmlFile(packageFile, visitedFiles) {
	if (visitedFiles.has(packageFile)) return null;
	visitedFiles.add(packageFile);
	const content = await readLocalFile(packageFile, "utf8");
	if (!content) {
		logger.debug(`ant manager: could not read ${packageFile}`);
		return null;
	}
	const result = extractPackageFile(content, packageFile);
	if (!result) return null;
	return {
		packageFile,
		...result
	};
}
async function extractAllPackageFiles(_config, packageFiles) {
	const results = [];
	const visitedFiles = /* @__PURE__ */ new Set();
	for (const packageFile of packageFiles) {
		const result = await walkXmlFile(packageFile, visitedFiles);
		if (result) results.push(result);
	}
	return results.length > 0 ? results : null;
}
//#endregion
export { extractAllPackageFiles, extractPackageFile };

//# sourceMappingURL=extract.js.map