declapract
Version:
A tool to declaratively define best practices, maintainable evolve them, and scalably enforce them.
37 lines • 2.36 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.fixFile = void 0;
const UnexpectedCodePathError_1 = require("../../../../domain.operations/UnexpectedCodePathError");
const readFileIfExistsAsync_1 = require("../../../../utils/fileio/readFileIfExistsAsync");
const removeFileAsync_1 = require("../../../../utils/fileio/removeFileAsync");
const writeFileAsync_1 = require("../../../../utils/fileio/writeFileAsync");
/**
* fix a file using the fix function of a check, based on an evaluation of the file
*
* input is a "checkEvaluation", because:
* - it tells us this file _was_ checked before this was called
* - it has the exact "path" that the check was evaluated on (instead of just a glob, like on the path)
* - it has the reference to the declared check, which has the fix function
*/
const fixFile = async ({ evaluation, projectRootDirectory, }) => {
if (!evaluation.fix)
throw new UnexpectedCodePathError_1.UnexpectedCodePathError('fixFile called on an eval that doesnt have a fix defined');
// define the current state
const relativeFilePath = evaluation.path;
const filePath = `${projectRootDirectory}/${evaluation.path}`;
const fileContents = await (0, readFileIfExistsAsync_1.readFileIfExistsAsync)({ filePath });
// define the desired, "fixed", state
const { contents: desiredContents = fileContents, // if contents not returned from fix function, then desired contents = current contents
relativeFilePath: desiredRelativeFilePath = relativeFilePath, // if relative file path not returned from fix function, then desired relative file path = current relative file path
} = await evaluation.fix(fileContents, evaluation.context);
const desiredFilePath = `${projectRootDirectory}/${desiredRelativeFilePath}`;
// define what we need to do to get there
if (desiredContents)
// if they still desired contents, then write it to the desired path
await (0, writeFileAsync_1.writeFileAsync)({ path: desiredFilePath, content: desiredContents });
if (desiredFilePath !== filePath || !desiredContents)
// if the file path changed - or they no longer desire contents, then remove the orig file
await (0, removeFileAsync_1.removeFileAsync)({ path: filePath });
};
exports.fixFile = fixFile;
//# sourceMappingURL=fixFile.js.map