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 all 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
63 changes: 63 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,31 @@ export default {
},
},
],
replaceInFile: [
{
source: '/path/to/file.txt',
mutations: [
{
pattern: 'lorem-ipsum',
replacement: 'lorem.ipsum',
},
{
pattern: 'm',
replacement: 'n',
iterations: 2
},
],
},
{
source: '/path/to/anotherfile.txt',
mutations: [
{
pattern: 'lorem-ipsum',
replacement: 'lorem.ipsum',
},
],
}
],
},
},
}),
Expand Down Expand Up @@ -244,6 +269,44 @@ If you need to preserve the order in which operations will run you can set the o
}
```

### Replace In File

Replace individual or multiple files.

```js
[
{
source: '/path/to/file.txt',
mutations: [
{
pattern: 'lorem-ipsum',
replacement: 'lorem.ipsum',
},
{
pattern: 'm',
replacement: 'n',
iterations: 2
},
],
},
{
source: '/path/to/anotherfile.txt',
mutations: [
{
pattern: 'lorem-ipsum',
replacement: 'lorem.ipsum',
},
],
},
];
```

- source[`string`] - a file to replace some content
- mutations[`array`] - changes you intend to make to the file.
- pattern[`string`] - a string to find.
- replacement[`string`] - a string to replace.
- iterations[`number`] - optional. number of times it will search and replace the term. default is 1.

## Other Options

- **runTasksInSeries** [`boolean`] - Run tasks in series. Defaults to false
Expand Down
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 replaceInFileAction } from './replaceInFile.js';
39 changes: 39 additions & 0 deletions src/actions/replaceInFile.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 replaceInFileAction = 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 replaceInFileAction;
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, replaceInFileAction, 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 'replaceInFile':
await this.applyAction(replaceInFileAction, action);
break;

default:
throw Error('Unknown action');
}
Expand Down
28 changes: 27 additions & 1 deletion src/options-schema.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ export default {
type: 'array',
minItems: 1,
additionalItems: true,
itmes: [
items: [
{
type: 'object',
additionalProperties: false,
Expand Down Expand Up @@ -147,6 +147,29 @@ export default {
},
],
},
ReplaceInFile: {
description: 'Replace file contents.',
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',
},
replaceInFile: {
$ref: '#/definitions/ReplaceInFile',
},
},
},
},
Expand Down
59 changes: 59 additions & 0 deletions tests/replaceInFile.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: 'replaceInFile-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: {
replaceInFile: [
{
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 ReplaceInFile = {
/** 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;
replaceInFile?: ReplaceInFile;
}

interface Options {
Expand Down