Skip to content

Commit

Permalink
feat(tasks): adds edit task
Browse files Browse the repository at this point in the history
  • Loading branch information
rafamel committed Feb 18, 2021
1 parent 86a44ed commit 8f09b48
Show file tree
Hide file tree
Showing 2 changed files with 50 additions and 0 deletions.
49 changes: 49 additions & 0 deletions src/tasks/create/edit.ts
Original file line number Diff line number Diff line change
@@ -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<Buffer | Serial.Type>,
options?: EditOptions
): Task.Async {
return async (ctx: Context): Promise<void> => {
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);
});
}
};
}
1 change: 1 addition & 0 deletions src/tasks/create/index.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
export * from './clear';
export * from './copy';
export * from './edit';
export * from './exec';
export * from './log';
export * from './mkdir';
Expand Down

0 comments on commit 8f09b48

Please sign in to comment.