From 45907e8a2cdfd84280ca8547f044f8e4d22942c3 Mon Sep 17 00:00:00 2001 From: Sebastian Malton Date: Thu, 27 Jan 2022 10:58:46 -0500 Subject: [PATCH] Fix writeJsonFileInjectable - Previous change accidentally removed the ensureDir and default spacing code Signed-off-by: Sebastian Malton --- src/common/fs/write-json-file.injectable.ts | 34 ++++++++++++++++++++- 1 file changed, 33 insertions(+), 1 deletion(-) diff --git a/src/common/fs/write-json-file.injectable.ts b/src/common/fs/write-json-file.injectable.ts index c6581f9195..04fa68d392 100644 --- a/src/common/fs/write-json-file.injectable.ts +++ b/src/common/fs/write-json-file.injectable.ts @@ -3,10 +3,42 @@ * Licensed under MIT License. See LICENSE in root directory for more information. */ import { getInjectable, lifecycleEnum } from "@ogre-tools/injectable"; +import type { EnsureOptions, WriteOptions } from "fs-extra"; +import path from "path"; +import type { JsonValue } from "type-fest"; +import { bind } from "../utils"; import fsInjectable from "./fs.injectable"; +interface Dependencies { + writeJson: (file: string, object: any, options?: WriteOptions | BufferEncoding | string) => Promise; + ensureDir: (dir: string, options?: EnsureOptions | number) => Promise; +} + +async function writeJsonFile({ writeJson, ensureDir }: Dependencies, filePath: string, content: JsonValue, options?: WriteOptions | BufferEncoding) { + await ensureDir(path.dirname(filePath), { mode: 0o755 }); + + const resolvedOptions = typeof options === "string" + ? { + encoding: options, + } + : options; + + await writeJson(filePath, content, { + encoding: "utf-8", + spaces: 2, + ...resolvedOptions, + }); +} + const writeJsonFileInjectable = getInjectable({ - instantiate: (di) => di.inject(fsInjectable).writeJson, + instantiate: (di) => { + const { writeJson, ensureDir } = di.inject(fsInjectable); + + return bind(writeJsonFile, null, { + writeJson, + ensureDir, + }); + }, lifecycle: lifecycleEnum.singleton, });