Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Action to replace file content #121

Open
wants to merge 5 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions src/actions/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,3 +3,4 @@ export { default as moveAction } from './move.js';
export { default as deleteAction } from './delete.js';
export { default as mkdirAction } from './mkdir.js';
export { default as archiveAction } from './archive.js';
export { default as replaceAction } from './replace.js';
39 changes: 39 additions & 0 deletions src/actions/replace.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
import fs, { existsSync } from 'fs';
import pExec from '../utils/p-exec.js';

const replaceAction = async (tasks, options) => {
const { runTasksInSeries, logger } = options;

logger.debug(`processing replace tasks. tasks: ${tasks}`);

await pExec(runTasksInSeries, tasks, async (task) => {
const file = task.source;

if (existsSync(file)) {
fs.readFile(file, 'utf8', function (err, data) {
if (err) {
logger.error(`unable to read ${file}, ${err}`);
}

task.mutations.forEach((mutation) => {
let iterations = mutation.iterations ? mutation.iterations : 1;
for (let index = 0; index < iterations; index++) {
data = data.replace(mutation.pattern, mutation.replacement);
}
});

fs.writeFile(file, data, 'utf8', function (err) {
if (err) {
logger.error(`unable to write ${file}, ${err}`);
}
});
});
} else {
logger.error(`unable to find ${file}`);
}
});

logger.debug(`replace tasks complete. tasks: ${tasks}`);
};

export default replaceAction;
6 changes: 5 additions & 1 deletion src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import normalizePath from 'normalize-path';

import optionsSchema from './options-schema.js';
import pExec from './utils/p-exec.js';
import { copyAction, moveAction, mkdirAction, archiveAction, deleteAction } from './actions/index.js';
import { copyAction, moveAction, mkdirAction, archiveAction, replaceAction, deleteAction } from './actions/index.js';

const PLUGIN_NAME = 'FileManagerPlugin';

Expand Down Expand Up @@ -99,6 +99,10 @@ class FileManagerPlugin {
await this.applyAction(archiveAction, action);
break;

case 'replace':
await this.applyAction(replaceAction, action);
break;

default:
throw Error('Unknown action');
}
Expand Down
26 changes: 26 additions & 0 deletions src/options-schema.js
Original file line number Diff line number Diff line change
Expand Up @@ -147,6 +147,29 @@ export default {
},
],
},
Replace: {
description: 'Replace files.',
type: 'array',
additionalItems: true,
items: [
{
type: 'object',
additionalProperties: false,
properties: {
source: {
description: 'Source. A file.',
type: 'string',
minLength: 1,
},
mutations: {
description: 'Multiple terms to find and replace. Multiple times (Optional).',
type: 'array',
minLength: 1,
},
},
},
],
},
Actions: {
type: 'object',
additionalProperties: false,
Expand All @@ -166,6 +189,9 @@ export default {
archive: {
$ref: '#/definitions/Archive',
},
replace: {
sibiraj-s marked this conversation as resolved.
Show resolved Hide resolved
$ref: '#/definitions/Replace',
},
},
},
},
Expand Down
59 changes: 59 additions & 0 deletions tests/replace.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
import { readFile } from 'node:fs';
import test from 'ava';
import del from 'del';
import compile from './utils/compile.js';
import getCompiler from './utils/getCompiler.js';
import tempy from './utils/tempy.js';
import FileManagerPlugin from '../src/index.js';

test.beforeEach(async (t) => {
t.context.tmpdir = await tempy.dir({ suffix: 'replace-action' });
});

test.afterEach(async (t) => {
await del(t.context.tmpdir);
});

const matchFileContent = async (pattern, file) => {
const data = readFile(file, 'utf-8', function (err, data) {
return data;
});

return data !== pattern;
};

test('should replace the given patterns in given files', async (t) => {
const { tmpdir } = t.context;
const dir = await tempy.dir({ root: tmpdir });
const file = await tempy.file(dir, 'file');

const config = {
context: tmpdir,
events: {
onEnd: {
replace: [
{
source: file,
mutations: [
{
pattern: 'lorem-ipsum',
replacement: 'lorem.ipsum',
},
{
pattern: 'm',
replacement: 'n',
iterations: 2
},
],
}
],
},
},
};

const compiler = getCompiler();
new FileManagerPlugin(config).apply(compiler);
await compile(compiler);

t.true(await matchFileContent('loren.ipsun', file))
});
18 changes: 18 additions & 0 deletions types.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,23 @@ type Archive = {
options?: ArchiverOptions | { globOptions: ReaddirGlobOptions };
}[];

/** Replace files content */
type Replace = {
/** File source. */
source: string;
/** Changes you want to make. */
mutations: Mutations[];
}[];

interface Mutations {
/** Pattern to find. */
pattern: string;
/** Term to replace in file. */
replacement: string;
/** Number of iterations for mutiple patterns. */
iterations?: number;
}

/** {@link https://github.com/Yqnn/node-readdir-glob#options} */
interface ReaddirGlobOptions {
/** Glob pattern or Array of Glob patterns to match the found files with. A file has to match at least one of the provided patterns to be returned. */
Expand Down Expand Up @@ -92,6 +109,7 @@ interface Actions {
move?: Move;
mkdir?: Mkdir;
archive?: Archive;
replace?: Replace;
}

interface Options {
Expand Down