Path: blob/main/src/command/use/commands/binder/binder-utils.ts
3593 views
/*1* binder-utils.ts2*3* Copyright (C) 2021-2022 Posit Software, PBC4*/56import { md5HashAsync } from "../../../../core/hash.ts";7import { projectScratchPath } from "../../../../project/project-scratch.ts";89import { info, warning } from "../../../../deno_ral/log.ts";10import { ensureDirSync, existsSync } from "../../../../deno_ral/fs.ts";11import { dirname, join } from "../../../../deno_ral/path.ts";1213import { Confirm } from "cliffy/prompt/mod.ts";1415export const safeFileWriter = (projectDir: string, prompt = true) => {16// The index file in the project scratch directory17const idxPath = join(projectScratchPath(projectDir), "use", "binder.json");1819// Ensure directory is there20ensureDirSync(dirname(idxPath));2122// Read the index, if it is there23let fileIndex: Record<string, string> = {};24if (existsSync(idxPath)) {25fileIndex = JSON.parse(Deno.readTextFileSync(idxPath));26}2728return async (projRelativePath: string, contents: string) => {29const absPath = join(projectDir, projRelativePath);3031const write = () => {32fileIndex[projRelativePath] = hash;33Deno.writeTextFileSync(absPath, contents);34Deno.writeTextFileSync(idxPath, JSON.stringify(fileIndex, null, 2));35info(`[✓] ${projRelativePath}`);36};3738const hash = await md5HashAsync(contents);39if (existsSync(absPath)) {40const lastHash = fileIndex[projRelativePath];41const currentContents = Deno.readTextFileSync(absPath);42const currentHash = await md5HashAsync(currentContents);4344let writeFile = true;45if (!lastHash || lastHash !== currentHash) {46// The file exists and wasn't generated, prompt to overwrite47if (prompt) {48const question = lastHash49? `File ${projRelativePath} was modified since last generated. Overwrite?`50: `File ${projRelativePath} wasn't created by the this command. Overwrite?`;51writeFile = await Confirm.prompt({52message: question,53});54} else {55writeFile = false;56lastHash57? warning(58`Skipped ${projRelativePath} - modified since last generated.`,59)60: warning(61`Skipped ${projRelativePath} - wasn't created by the this command.`,62);63}64}6566if (writeFile) {67write();68}69} else {70// the file doesn't exists, generate hash and store that, write the file71write();72}73};74};757677