|
| 1 | +#!/usr/bin/env node |
| 2 | +/* eslint-disable no-undef */ |
| 3 | +import meow from 'meow' |
| 4 | +import process from 'node:process' |
| 5 | +import { replaceRegex } from './dist/index.js' |
| 6 | + |
| 7 | +const cli = meow( |
| 8 | + ` |
| 9 | + Usage |
| 10 | + $ replace-regex <files…> |
| 11 | +
|
| 12 | + Options |
| 13 | + --from Regex pattern or string to find (Can be set multiple times) |
| 14 | + --to Replacement string or function (Required) |
| 15 | + --dry Dry run (do not actually replace, just show what would be replaced) |
| 16 | + --no-glob Disable globbing |
| 17 | + --count-matches Count matches and replacements |
| 18 | + --ignore Ignore files matching this pattern (Can be set multiple times) |
| 19 | + --ignore-case Search case-insensitively |
| 20 | +
|
| 21 | + Examples |
| 22 | + $ replace-regex --from='fox' --to='🦊' foo.md |
| 23 | + $ replace-regex --from='v\\d+\\.\\d+\\.\\d+' --to='v$npm_package_version' foo.css |
| 24 | + $ replace-regex --from='blob' --to='blog' 'some/**/[gb]lob/*' '!some/glob/foo' |
| 25 | +`, |
| 26 | + { |
| 27 | + importMeta: import.meta, |
| 28 | + flags: { |
| 29 | + from: { |
| 30 | + type: 'string', |
| 31 | + isMultiple: true, |
| 32 | + }, |
| 33 | + to: { |
| 34 | + type: 'string', |
| 35 | + isRequired: true, |
| 36 | + }, |
| 37 | + dry: { |
| 38 | + type: 'boolean', |
| 39 | + default: false, |
| 40 | + }, |
| 41 | + glob: { |
| 42 | + type: 'boolean', |
| 43 | + default: true, |
| 44 | + }, |
| 45 | + countMatches: { |
| 46 | + type: 'boolean', |
| 47 | + default: false, |
| 48 | + }, |
| 49 | + ignore: { |
| 50 | + type: 'string', |
| 51 | + isMultiple: true, |
| 52 | + }, |
| 53 | + ignoreCase: { |
| 54 | + type: 'boolean', |
| 55 | + default: false, |
| 56 | + }, |
| 57 | + }, |
| 58 | + }, |
| 59 | +) |
| 60 | + |
| 61 | +if (cli.input.length === 0) { |
| 62 | + console.error('Specify one or more file paths') |
| 63 | + process.exit(1) |
| 64 | +} |
| 65 | + |
| 66 | +if (!cli.flags.from || cli.flags.from.length === 0) { |
| 67 | + console.error('Specify at least `--from`') |
| 68 | + process.exit(1) |
| 69 | +} |
| 70 | + |
| 71 | +const replaceOptions = { |
| 72 | + files: cli.input, |
| 73 | + from: cli.flags.from, |
| 74 | + to: cli.flags.to, |
| 75 | + dry: cli.flags.dry, |
| 76 | + disableGlobs: !cli.flags.glob, |
| 77 | + countMatches: cli.flags.countMatches, |
| 78 | + ignore: cli.flags.ignore, |
| 79 | + ignoreCase: cli.flags.ignoreCase, |
| 80 | +} |
| 81 | + |
| 82 | +const results = await replaceRegex(replaceOptions) |
| 83 | + |
| 84 | +results.forEach((result) => { |
| 85 | + const { file, replaceCount, matchCount } = result |
| 86 | + console.log(`file: ${file} |
| 87 | +replace count: ${replaceCount} |
| 88 | +match count: ${matchCount}`) |
| 89 | +}) |
0 commit comments