From 8f09b4898d265f59abb9f24219d7fdf3414d297a Mon Sep 17 00:00:00 2001 From: Rafa Mel Date: Thu, 18 Feb 2021 10:28:55 +0100 Subject: [PATCH] feat(tasks): adds edit task --- src/tasks/create/edit.ts | 49 +++++++++++++++++++++++++++++++++++++++ src/tasks/create/index.ts | 1 + 2 files changed, 50 insertions(+) create mode 100644 src/tasks/create/edit.ts diff --git a/src/tasks/create/edit.ts b/src/tasks/create/edit.ts new file mode 100644 index 0000000..177c100 --- /dev/null +++ b/src/tasks/create/edit.ts @@ -0,0 +1,49 @@ +import { Task, Context } from '../../definitions'; +import { getPaths, useSource } from '../../helpers/paths'; +import { isCancelled } from '../../utils'; +import { log } from './log'; +import { Serial } from 'type-core'; +import { into } from 'pipettes'; +import fs from 'fs-extra'; + +export interface EditOptions { + glob?: boolean; + strict?: boolean; +} + +export function edit( + paths: string | string[], + cb: ( + buffer: Buffer, + path: string + ) => Buffer | Serial.Type | Promise, + options?: EditOptions +): Task.Async { + return async (ctx: Context): Promise => { + into(ctx, log('debug', 'Edit:', paths)); + + const opts = Object.assign({ glob: false, strict: false }, options); + const sources = await getPaths(paths, ctx, { + glob: opts.glob, + strict: opts.strict + }); + + for (const source of sources) { + if (await isCancelled(ctx)) return; + + await useSource(source, ctx, { strict: opts.strict }, async () => { + const buffer = await fs.readFile(source); + const content = await cb(buffer, source); + + if (await isCancelled(ctx)) return; + + const data = Buffer.isBuffer(content) + ? content + : typeof content === 'object' + ? JSON.stringify(content, null, 2) + : String(content); + await fs.writeFile(source, data); + }); + } + }; +} diff --git a/src/tasks/create/index.ts b/src/tasks/create/index.ts index a1d8039..2b1c605 100644 --- a/src/tasks/create/index.ts +++ b/src/tasks/create/index.ts @@ -1,5 +1,6 @@ export * from './clear'; export * from './copy'; +export * from './edit'; export * from './exec'; export * from './log'; export * from './mkdir';