import { existsSync, safeRemoveDirSync } from "../../deno_ral/fs.ts";
import { dirname, extname, isAbsolute, join } from "../../deno_ral/path.ts";
import * as ld from "../../core/lodash.ts";
import {
normalizePath,
removeIfEmptyDir,
removeIfExists,
safeRemoveSync,
} from "../../core/path.ts";
import { figuresDir, inputFilesDir } from "../../core/render.ts";
import { Format } from "../../config/types.ts";
import { isHtmlFileOutput, isLatexOutput } from "../../config/format.ts";
import { kKeepMd, kKeepTex, kKeepTyp } from "../../config/constants.ts";
import { filesDirLibDir, filesDirMediabagDir } from "./render-paths.ts";
import { ProjectContext } from "../../project/types.ts";
export function renderCleanup(
input: string,
output: string,
format: Format,
project: ProjectContext,
supporting?: string[],
keepMd?: string,
) {
const figureFormat = isLatexOutput(format.pandoc)
? extname(output).slice(1)
: format.pandoc.to;
if (!isAbsolute(output)) {
output = join(dirname(input), output);
}
if (keepMd && !format.execute[kKeepMd] && keepMd !== output) {
removeIfExists(keepMd);
}
if (
!format.execute[kKeepMd] &&
!format.render[kKeepTex] &&
!format.render[kKeepTyp] &&
supporting
) {
if (isHtmlFileOutput(format.pandoc)) {
const libDir = join(
dirname(input),
filesDirLibDir(input),
);
if (existsSync(libDir)) {
supporting.push(normalizePath(libDir));
}
} else {
let filesDir = join(
dirname(input),
inputFilesDir(input),
);
if (existsSync(filesDir)) {
filesDir = normalizePath(filesDir);
}
supporting = supporting.map((supportingDir) => {
if (filesDir === supportingDir) {
return join(filesDir, figuresDir(figureFormat));
} else {
return supportingDir;
}
});
}
const mediabagDir = join(dirname(input), filesDirMediabagDir(input));
if (existsSync(mediabagDir)) {
supporting.push(mediabagDir);
}
ld.uniq(supporting).forEach((path) => {
if (existsSync(path)) {
safeRemoveDirSync(path, project.dir);
}
});
}
const filesDir = join(dirname(input), inputFilesDir(input));
const figsDir = join(filesDir, figuresDir(figureFormat));
const libDir = join(dirname(input), filesDirLibDir(input));
const mediabagDir = join(dirname(input), filesDirMediabagDir(input));
removeIfEmptyDir(figsDir);
removeIfEmptyDir(libDir);
removeIfEmptyDir(mediabagDir);
removeIfEmptyDir(filesDir);
}