UNPKG

@baseplate-dev/sync

Version:

Library for syncing Baseplate descriptions

68 lines 2.75 kB
import fs from 'node:fs/promises'; import path from 'node:path'; import { ensureDir, pathExists } from '#src/utils/fs.js'; /** * Rename a file if needed, throwing if the target path exists */ async function renameFileIfNeeded(previousPath, newPath, outputDirectory) { if (previousPath === newPath) return; const fullPreviousPath = path.join(outputDirectory, previousPath); const fullNewPath = path.join(outputDirectory, newPath); if (await pathExists(fullNewPath)) { throw new Error(`Cannot rename ${fullPreviousPath} to ${fullNewPath} as target path already exists`); } await ensureDir(path.dirname(fullNewPath)); await fs.rename(fullPreviousPath, fullNewPath); } /** * Write file contents to a specified path */ async function writeFileContents(contents, filePath) { await ensureDir(path.dirname(filePath)); await fs.writeFile(filePath, contents); } /** * Write merged contents if they exist */ async function writeMergedContents(mergedContents, relativePath, outputDirectory) { if (!mergedContents) return; const fullPath = path.join(outputDirectory, relativePath); await writeFileContents(mergedContents, fullPath); } /** * Write generated contents to specified directory */ async function writeGeneratedContents(generatedContents, relativePath, directory) { const fullPath = path.join(directory, relativePath); await writeFileContents(generatedContents, fullPath); } /** * Write conflict contents if needed */ async function writeConflictContents(generatedContents, conflictPath, outputDirectory) { if (!conflictPath) return; const fullPath = path.join(outputDirectory, conflictPath); await writeFileContents(generatedContents, fullPath); } /** * Write a generator file based on the prepare generator file result */ export async function writeGeneratorFile({ fileOperation, outputDirectory, generatedContentsDirectory, }) { const { relativePath, previousRelativePath, mergedContents, generatedContents, generatedConflictRelativePath, } = fileOperation; // Handle file renames first if (previousRelativePath) { await renameFileIfNeeded(previousRelativePath, relativePath, outputDirectory); } // Write merged contents if they exist await writeMergedContents(mergedContents, relativePath, outputDirectory); // Write generated contents to separate directory if specified if (generatedContentsDirectory) { await writeGeneratedContents(generatedContents, relativePath, generatedContentsDirectory); } // Write conflict contents if needed await writeConflictContents(generatedContents, generatedConflictRelativePath, outputDirectory); } //# sourceMappingURL=write-generator-file.js.map