From 86a44edfedb65afe014daafa18a5482431af02c9 Mon Sep 17 00:00:00 2001 From: Rafa Mel Date: Thu, 18 Feb 2021 10:28:05 +0100 Subject: [PATCH] feat(tasks): adds write task --- src/tasks/create/index.ts | 1 + src/tasks/create/write.ts | 33 +++++++++++++++++++++++++++++++++ 2 files changed, 34 insertions(+) create mode 100644 src/tasks/create/write.ts diff --git a/src/tasks/create/index.ts b/src/tasks/create/index.ts index 154a5e9..a1d8039 100644 --- a/src/tasks/create/index.ts +++ b/src/tasks/create/index.ts @@ -8,3 +8,4 @@ export * from './print'; export * from './raises'; export * from './remove'; export * from './sleep'; +export * from './write'; diff --git a/src/tasks/create/write.ts b/src/tasks/create/write.ts new file mode 100644 index 0000000..def903a --- /dev/null +++ b/src/tasks/create/write.ts @@ -0,0 +1,33 @@ +import { Task, Context } from '../../definitions'; +import { useDestination } from '../../helpers/paths'; +import { log } from './log'; +import { Serial } from 'type-core'; +import { into } from 'pipettes'; +import fs from 'fs-extra'; + +export interface WriteOptions { + exists?: 'error' | 'ignore' | 'overwrite'; +} + +export function write( + path: string, + content: Buffer | Serial.Type, + options?: WriteOptions +): Task.Async { + return async (ctx: Context): Promise => { + into(ctx, log('debug', 'Write:', path)); + + const data = Buffer.isBuffer(content) + ? content + : typeof content === 'object' + ? JSON.stringify(content, null, 2) + : String(content); + + await useDestination( + path, + ctx, + Object.assign({ exists: 'error' }, options), + (dest) => fs.writeFile(dest, data) + ); + }; +}