Coder Social home page Coder Social logo

repren's Introduction

repren

But call me repren for short

Rename anything

Repren is a simple but flexible command-line tool for rewriting file contents according to a set of regular expression patterns, and to rename or move files according to patterns. Essentially, it is a general-purpose, brute-force text file refactoring tool. For example, repren could rename all occurrences of certain class and variable names in a set of Java source files, while simultaneously renaming the Java files according to the same pattern. It's more powerful than usual options like perl -pie, rpl, or sed:

  • It can do search-and-replace, file renaming, or both.
  • It allows file renaming on full paths, including moving files, creating directories, or rewriting directory hierarchies.
  • It supports fully expressive regular expressions, with capturing groups and back substitutions.
  • It performs simultaneous group renamings, i.e. rename "foo" as "bar", and "bar" as "foo" at once, without requiring a temporary intermediate rename.
  • It is careful. It has a nondestructive mode, and prints clear stats on its changes. It leaves backups. File operations are done atomically, so interruptions never leave a previously existing file truncated or partly edited.
  • It supports helpful variations like an option to replace on word breaks, so you avoid splitting a word, and "case-preserving" renames that let you find and rename identifiers with case variants (lowerCamel, UpperCamel, lower_underscore, and UPPER_UNDERSCORE) consistently.
  • It has this nice documentaion!

Usage

Run repren --help for full usage and flags.

If file paths are provided, repren replaces those files in place, leaving a backup with extension ".orig". If directory paths are provided, it applies replacements recursively to all files in the supplied paths that are not in the exclude pattern. If no arguments are supplied, it reads from stdin and writes to stdout.

Alternatives

Aren't there standard tools for this already?

It's a bit surprising, but not really. Getting the features right is a bit tricky, I guess. The standard answers like sed, perl, awk, rename, Vim macros, or even IDE refactoring tools, often cover specific cases, but tend to be error-prone or not offer specific features you probably want. Things like nondestructive mode, file renaming as well as search/replace, multiple simultaneous renames/swaps, or renaming enclosing parent directories. Also many of these vary by platform, which adds to the corner cases. Inevitably you end up digging through the darker corners of some man page or writing ugly scripts that would scare your mother.

Installation

No dependencies except Python 2.7+. It's easiest to install with pip (using sudo if desired):

pip2.7 install repren

Or, since it's just one file, you can copy the repren script somewhere (perhaps within your own project) and make it executable.

Try it

Let's try a simple replacement in my working directory (which has a few random source files):

bash-3.2$ repren --from frobinator-server --to glurp-server --full --dry-run .
Dry run: No files will be changed
Using 1 patterns:
  'frobinator-server' -> 'glurp-server'
Found 102 files in: .
- modify: ./site.yml: 1 matches
- rename: ./roles/frobinator-server/defaults/main.yml -> ./roles/glurp-server/defaults/main.yml
- rename: ./roles/frobinator-server/files/deploy-frobinator-server.sh -> ./roles/glurp-server/files/deploy-frobinator-server.sh
- rename: ./roles/frobinator-server/files/install-graphviz.sh -> ./roles/glurp-server/files/install-graphviz.sh
- rename: ./roles/frobinator-server/files/frobinator-purge-old-deployments -> ./roles/glurp-server/files/frobinator-purge-old-deployments
- rename: ./roles/frobinator-server/handlers/main.yml -> ./roles/glurp-server/handlers/main.yml
- rename: ./roles/frobinator-server/tasks/main.yml -> ./roles/glurp-server/tasks/main.yml
- rename: ./roles/frobinator-server/templates/frobinator-webservice.conf.j2 -> ./roles/glurp-server/templates/frobinator-webservice.conf.j2
- rename: ./roles/frobinator-server/templates/frobinator-webui.conf.j2 -> ./roles/glurp-server/templates/frobinator-webui.conf.j2
Read 102 files (190382 chars), found 2 matches (0 skipped due to overlaps)
Dry run: Would have changed 2 files, including 0 renames

That was a dry run, so if it looks good, it's easy to repeat that a second time, dropping the --dry-run flag. If this is in git, we'd do a git diff to verify, test, then commit it all. If we messed up, there are still .orig files present.

Patterns

Patterns can be supplied using the --from and --to syntax above, but that only works for a single pattern.

In general, you can perform multiple simultaneous replacements by putting them in a patterns file. Each line consists of a regular expression and replacement. For example:

# Sample pattern file
frobinator<tab>glurp
WhizzleStick<tab>AcmeExtrudedPlasticFunProvider
figure ([0-9+])<tab>Figure \1

(Where <tab> is an actual tab character.)

Empty lines and #-prefixed comments are ignored. Capturing groups and back substitutions (such as \1 above) are supported.

Examples

# Here `patfile` is a patterns file.
# Rewrite stdin:
repren -p patfile < input > output

# Shortcut with a single pattern replacement (replace foo with bar):
repren --from foo --to bar < input > output

# Rewrite a few files in place, also requiring matches be on word breaks:
repren -p patfile --word-breaks myfile1 myfile2 myfile3

# Rewrite whole directory trees. Since this is a big operation, we use
# `-n` to do a dry run that only prints what would be done:
repren -n -p patfile --word-breaks --full mydir1

# Now actually do it:
repren -p patfile --word-breaks --full mydir1

# Same as above, for all case variants:
repren -p patfile --word-breaks --preserve-case --full mydir1

Notes

  • As with sed, replacements are made line by line by default. Memory permitting, replacements may be done on entire files using --at-once.
  • As with sed, replacement text may include backreferences to groups within the regular expression, using the usual syntax: \1, \2, etc.
  • In the pattern file, both the regular expression and the replacement may contain the usual escapes \n, \t, etc. (To match a multi-line pattern, containing \n, you must must use --at-once.)
  • Replacements are all matched on each input file, then all replaced, so it's possible to swap or otherwise change names in ways that would require multiple steps if done one replacement at at a time.
  • If two patterns have matches that overlap, only one replacement is applied, with preference to the pattern appearing first in the patterns file.
  • If one pattern is a subset of another, consider if --word-breaks will help.
  • If patterns have special charaters, --literal may help.
  • The case-preserving option works by adding all case variants to the pattern replacements, e.g. if the pattern file has foo_bar -> xxx_yyy, the replacements fooBar -> xxxYyy, FooBar -> XxxYyy, FOO_BAR -> XXX_YYY are also made. Assumes each pattern has one casing convention. (Plain ASCII names only.)
  • The same logic applies to filenames, with patterns applied to the full file path with slashes replaced and then and parent directories created as needed, e.g. my/path/to/filename can be rewritten to my/other/path/to/otherfile. (Use caution and test with -n, especially when using absolute path arguments!)
  • Files are never clobbered by renames. If a target already exists, or multiple files are renamed to the same target, numeric suffixes will be added to make the files distinct (".1", ".2", etc.).
  • Files are created at a temporary location, then renamed, so original files are left intact in case of unexpected errors. File permissions are preserved.
  • Backups are created of all modified files, with the suffix ".orig".
  • By default, recursive searching omits paths starting with ".". This may be adjusted with --exclude. Files ending in .orig are always ignored.
  • Data can be in any encoding, as it is treated as binary, and not interpreted in a specific encoding like UTF-8. This is less error prone in real-life situations where files have encoding inconsistencies. However, note the --case-preserving logic only handles casing conversions correctly for plain ASCII letters [a-zA-Z].

Contributing

Contributions and issues welcome! Do understand and run the (manual) regression tests, review the output, and commit the clean log changes if you submit a PR. (And mention this in the PR.)

License

Apache 2.

repren's People

Contributors

c4rlo avatar jlevy avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

repren's Issues

Regular expressions dialect

Hi there, great tool, really useful.

From the documentation, it is implicitly deduced that the expressions may be regular expressions. It would be nice to know exactly what dialect of regular expressions is accepted and what features are available.

Thanks!

--from does not accept pattern starting with #

$ repren --from '#include <a.h>' --to '#include <b.h>' .
error: found no parse patterns

Same with --literal:

$ repren --literal --from '#include <a.h>' --to '#include <b.h>' .
error: found no parse patterns

This is because it interprets the # as a comment character (in function parse_patterns()).

It would be nice if this comment logic did not apply when patterns are supplied directly via --from --to, and/or when --literal is given.

Nondestructive mode can create empty directories

When using dry-run mode (-n), files won't be modified.

However, if we are renaming entire paths, the implementation of transform_file() temporarily creates the parent paths of the new, rewritten path as part of the dry run (to better reproduce real behavior, and because it counts matches).

This means it can leave behind new, empty directories.

This isn't a really big deal, but it's arguably a bug.

"--at-once" option

Hi,

I can't seem to get the "--at-once" option working. My OS is "Linux Mint 17 Qiana".
I'm not really sure what version of Python is being used. "python2.7 -V" gives "Python 2.7.16", but When I do "python -V" gives "Python 2.7.6". I tested on a file containing "hello\nthere". It seems to find the match, but not do any changes:

repren -p toss_repren --at-once -i ./toss.txt
Using 1 patterns:
'hello' -> 'goodbye'
Found 1 files in: ./toss.txt
Read 1 files (12 chars), found 1 matches (0 skipped due to overlaps)
Changed 0 files (0 rewritten and 0 renamed)

When I drop the "--at-once" option, it works:

repren -p toss_repren -i ./toss.txt
Using 1 patterns:
'hello' -> 'goodbye'
Found 1 files in: ./toss.txt

  • modify: ./toss.txt: 1 matches
    Read 1 files (12 chars), found 1 matches (0 skipped due to overlaps)
    Changed 1 files (1 rewritten and 0 renamed)

I also did "bash run.sh" to run the tests. Most seemed to work but at the end I got "ls_portable test2
tail: cannot open ‘+2’ for reading: No such file or directory". Thanks in advance for your help.

Out-of-memory errors can be destructive

...unless the user uses backups. Multi-gigabyte stuff can be tricky (lost one XXL-sized file this way, fortunately an intermediate result though), so I would add some words of caution into the help screens/README, viz. after the following passage:

"File operations are done atomically, so interruptions never leave a previously existing file truncated or partly edited."

insert this:

"Users must be careful when processing very large files with --at-once option turned on."

clearer help about default mode

It is not clear from the documentation or from the --help page which mode is the default one.

I'd suggest either adding this into --help page:

- repren: Multi-pattern string replacement and file renaming
+ repren: Multi-pattern string replacement (default) and file renaming tool

or adding a command-line option:

  -p PAT_FILE, --patterns=PAT_FILE
                        file with multiple replacement patterns (see below)
+  --replace-only         do search/replace on file contents (default)
  --full                do file renames and search/replace on file contents
  --renames             do file renames only; do not modify file contents

or adding a simple example to the README that does nothing but a simple search-and-replace:

repren --from center --to centre .

This is the mode that I use most, but it was tricky to find out the exact syntax from the docs.

More extensive large-scale test

This is a big omission. Currently testing informally.

Need some end-to-end automated test to cover lots of corner cases by doing some complex renames on a complex tree of files and validating the matches. Can do a sequence of operations including rewrites, renames, and swaps, record the tallies, put them all back, and validate the final result is identical using diff -r.

Perhaps simplest to automate with a silly script harness a bit like https://github.com/jlevy/procdog/blob/master/tests/run.sh

TypeError: can't use a string pattern on a bytes-like object

Trying to replace a string in files inside a directory I get the following error:
Dry run: No files will be changed Using 1 patterns: 'xxx' -> 'yyy' Found 6617 files in: .eclipse/ Traceback (most recent call last): File "/usr/bin/repren", line 534, in <module> dry_run=options.dry_run) File "/usr/bin/repren", line 409, in rewrite_files rewrite_file(path, patterns, do_renames=do_renames, do_contents=do_contents, by_line=by_line, dry_run=dry_run) File "/usr/bin/repren", line 375, in rewrite_file counts = transform_file(transform, path, dest_path, by_line=by_line, dry_run=dry_run) File "/usr/bin/repren", line 339, in transform_file counts = transform_stream(transform, stream_in, stream_out, by_line=by_line) File "/usr/bin/repren", line 307, in transform_stream (new_line, new_counts) = transform(line) File "/usr/bin/repren", line 374, in <lambda> transform = lambda contents: multi_replace(contents, patterns, source_name=path) File "/usr/bin/repren", line 209, in multi_replace for match in regex.finditer(input_str): TypeError: can't use a string pattern on a bytes-like object

The exact command given is: repren --from xxx --to yyy --dry-run .eclipse/

My guess is that this happens because there are binary files in the directory.

Could there be an option to skip binary files?

Add option to skip binary files

./bin/k2pdfopt_linux is a binary file which should not be touched:

repren --dry-run --literal --from agC --to ag_c .
Dry run: No files will be changed
Using 1 patterns:
  'agC' -> 'ag_c'
Found 200 files in: .
- modify: ./bin/k2pdfopt_linux: 1 matches
- modify: ./zsh/auto-load/others/ag.zsh: 3 matches
Read 200 files (14410423 chars), found 4 matches (0 skipped due to overlaps)
Dry run: Would have changed 2 files (2 rewritten and 0 renamed)

Do not rename files, only content?

Possible to only rename the contents of files, and not the file names themselves?

I don't understand how --literal works, e.g.

python /Users/storm/bin/repren --dry-run --literal -i --from='light.mini_sov' --to='light.bedroom_mini' test
Dry run: No files will be changed
Using 1 patterns:
  'light\.mini\_sov' IGNORECASE -> 'light.bedroom_mini'

Why does the from escape the dots, while the to doesn`t?
I've tried including -i and --literal twice, but to no avail :)

Use unicode for internal processing?

Firstly, many thanks for putting this up - I think it's brilliant. In addition to code refactoring this is tremendously useful for people editing and revising books (with LaTeX, markdown and/or reStructured Text sources). For this purpose it would be very helpful to have repren deal also with non-ascii characters (e.g. accented characters in foreign words).

Would you consider adding an --encoding option to enable users to specify file encoding? repren could then decode the inputs read from pattern and input files to unicode, do all the internal processing in unicode and then encode again when writing output.

Automatic testing

Since repren has a test script, we should run it automatically with Travis CI.

I'm going to take a look at this now.

How to rename directories?

This is an example:

$ mkdir 1
$ cd 1
$ touch {1,2,3,4,5}.txt
$ mkdir {6,7,8,9}
$ cp *txt 6
$ repren -n --renames --from "^" --to "aaa_" [6789]
Dry run: No files will be changed
Using 1 patterns:
  '^' -> 'aaa_'
Found 5 files in: 6, 7, 8, 9
- rename: 6/4.txt -> aaa_6/4.txt
- rename: 6/1.txt -> aaa_6/1.txt
- rename: 6/3.txt -> aaa_6/3.txt
- rename: 6/5.txt -> aaa_6/5.txt
- rename: 6/2.txt -> aaa_6/2.txt
Read 5 files (0 chars), found 0 matches (0 skipped due to overlaps)
Dry run: Would have changed 5 files (0 rewritten and 5 renamed)

$ repren --renames --from "^" --to "aaa_" [6789]
Using 1 patterns:
  '^' -> 'aaa_'
Found 5 files in: 6, 7, 8, 9
Traceback (most recent call last):
  File "/home/alexey/bin/repren", line 531, in <module>
    dry_run=options.dry_run)
  File "/home/alexey/bin/repren", line 406, in rewrite_files
    rewrite_file(path, patterns, do_renames=do_renames, do_contents=do_contents, by_line=by_line, dry_run=dry_run)
  File "/home/alexey/bin/repren", line 372, in rewrite_file
    counts = transform_file(transform, path, dest_path, by_line=by_line, dry_run=dry_run)
  File "/home/alexey/bin/repren", line 357, in transform_file
    move_file(source_path, dest_path, clobber=False)
  File "/home/alexey/bin/repren", line 299, in move_file
    shutil.move(source_path, dest_path)
  File "/usr/lib/python2.7/shutil.py", line 302, in move
    copy2(src, real_dst)
  File "/usr/lib/python2.7/shutil.py", line 130, in copy2
    copyfile(src, dst)
  File "/usr/lib/python2.7/shutil.py", line 83, in copyfile
    with open(dst, 'wb') as fdst:
IOError: [Errno 2] No such file or directory: 'aaa_6/4.txt'

So it is a bug plus feature request (rename folders only, or at least rename them like files)

Support non-recursive renames on directories?

repren recurses into directories if they are supplied as arguments. This always makes sense for search/replace.

One feature I've heard: If you're doing renames and not search/replace, you might want to rename directories without recursing. Not sure if this is common or the best solution. Perhaps a --no-recurse option that only applies to files/directories that are listed?

Support to only include certain files? Support config file?

Hi there! the tool is really useful. I think it would be great if a simple config file would be supported where the settings are specified.

also would be useful to support --include as well as --exclude. In my case for example it is easy to specify what I want repren to work on... only hpp and cpp files

Cheers!

Windows support

Repren works on Mac and Linux. Currently no testing has been done on Windows. Would be great to have some help with this.

Backup destination configuration

First off, thanks for the great tool.

I like the fact it auto-creates backups. The only thing it seems to be missing is the ability to configure where backups are stored. Is this currently possible?

`--at-once option

nt5a190812 [zhi:github_issue_aut_zhi_s]:*--at-once option^ (cntn Hi,

I can't seem to get the "--at-once" option working. My OS is "Linux Mint 17 Qiana".
I'm not really sure what version of Python is being used. "python2.7 -V" gives "Python 2.7.16", but When I do "python -V" gives "Python 2.7.6". I tested on a file containing "hello\there". It seems to find the match, but not do any changes:

repren -p toss_repren --at-once -i ./toss.txt
Using 1 patterns:
'hello' -> 'goodbye'
Found 1 files in: ./toss.txt
Read 1 files (12 chars), found 1 matches (0 skipped due to overlaps)
Changed 0 files (0 rewritten and 0 renamed)

When I drop the "--at-once" option, it works:

repren -p toss_repren -i ./toss.txt
Using 1 patterns:
'hello' -> 'goodbye'
Found 1 files in: ./toss.txt

  • modify: ./toss.txt: 1 matches
    Read 1 files (12 chars), found 1 matches (0 skipped due to overlaps)
    Changed 1 files (1 rewritten and 0 renamed)

I also did "bash run.sh" to run the tests. Most seemed to work but at the end I got "ls_portable test2
tail: cannot open ‘+2’ for reading: No such file or directory". Thanks i advance for your help.

--preserve-case enhancement: also use underscore-less CamelCase translations

Currently, when --preserve-case is used to translate a CamelCase replacements to additional lowercase and uppercase replacements, it inserts underscores in between the word segments. This is cool, but on some occasions it would be useful to additionally do the replacement without the added underscores.

For example, the current behaviour is like this:

$ repren --full --from CamelCase --to DromedaryCase --preserve-case .
Using 4 patterns:
  'CAMEL_CASE' -> 'DROMEDARY_CASE'
  'CamelCase' -> 'DromedaryCase'
  'camelCase' -> 'dromedaryCase'
  'camel_case' -> 'dromedary_case'

It would be awesome if it could be extended to do this:

$ repren --full --from CamelCase --to DromedaryCase --preserve-case .
Using 6 patterns:
  'CAMEL_CASE' -> 'DROMEDARY_CASE'
  'CAMELCASE' -> 'DROMEDARYCASE'
  'CamelCase' -> 'DromedaryCase'
  'camelCase' -> 'dromedaryCase'
  'camel_case' -> 'dromedary_case'
  'camelcase' -> 'dromedarycase'

Perhaps this could be opt-in.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.