diff --git a/src/exposed/file/index.ts b/src/exposed/file/index.ts new file mode 100644 index 0000000..f5b9aab --- /dev/null +++ b/src/exposed/file/index.ts @@ -0,0 +1 @@ +export { default as json } from './json'; diff --git a/src/exposed/file/json.ts b/src/exposed/file/json.ts new file mode 100644 index 0000000..7d468c4 --- /dev/null +++ b/src/exposed/file/json.ts @@ -0,0 +1,31 @@ +import path from 'path'; +import fs from 'fs-extra'; +import { exists } from '~/utils/file'; +import core from '~/core'; +import { IOfType, TScript } from '~/types'; +import { rejects } from 'errorish'; + +/** + * Reads a JSON `file` and passes it as an argument to a callback `fn`. If the callback returns an object, **`file` will be overwritten** with its contents. `file` can be relative to the project's directory. + * @returns A `TScript`, as a function, that won't be executed until called by `kpo` -hence, calling `json` won't have any effect until the returned function is called. + */ +export default function json( + file: string, + fn: (json: IOfType) => IOfType | void | Promise | void> +): TScript { + return async function json(): Promise { + if (!path.isAbsolute(file)) { + const paths = await core.paths(); + file = path.join(paths.directory, file); + } + + await exists(file, { fail: true }); + const json = await fs.readJSON(file).catch(rejects); + const response = await fn(json); + if (response) { + await fs + .writeFile(file, JSON.stringify(response, null, 2)) + .catch(rejects); + } + }; +} diff --git a/src/exposed/index.ts b/src/exposed/index.ts index 1692154..401f220 100644 --- a/src/exposed/index.ts +++ b/src/exposed/index.ts @@ -1,4 +1,5 @@ export * from './exec'; +export * from './file'; export * from './prompts'; export * from './tags'; export { default as options } from './options';