repren 1.0.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
repren/__init__.py ADDED
@@ -0,0 +1,3 @@
1
+ from .repren import main
2
+
3
+ __all__ = ["main"]
repren/repren.py ADDED
@@ -0,0 +1,906 @@
1
+ #!/usr/bin/env python
2
+ """
3
+ ## Rename Anything
4
+
5
+ Repren is a simple but flexible command-line tool for rewriting file contents according to a
6
+ set of regular expression patterns, and to rename or move files according to patterns.
7
+ Essentially, it is a general-purpose, brute-force text file refactoring tool.
8
+
9
+ For example, repren could rename all occurrences of certain class and variable names in a
10
+ set of Java source files, while simultaneously renaming the Java files according to the same
11
+ pattern.
12
+
13
+ It's more powerful than usual options like `perl -pie`, `rpl`, or `sed`:
14
+
15
+ - It can also rename files, including moving files and creating directories.
16
+
17
+ - It supports fully expressive regular expression substitutions.
18
+
19
+ - It performs group renamings, i.e. rename "foo" as "bar", and "bar" as "foo" at once,
20
+ without requiring a temporary intermediate rename.
21
+
22
+ - It is careful. It has a nondestructive mode, and prints clear stats on its changes.
23
+ It leaves backups.
24
+ File operations are done atomically, so interruptions never leave a previously existing
25
+ file truncated or partly edited.
26
+
27
+ - It supports "magic" case-preserving renames that let you find and rename identifiers with
28
+ case variants (lowerCamel, UpperCamel, lower_underscore, and UPPER_UNDERSCORE)
29
+ consistently.
30
+
31
+ - It has this nice documentation!
32
+
33
+ If file paths are provided, repren replaces those files in place, leaving a backup with
34
+ extension ".orig".
35
+
36
+ If directory paths are provided, it applies replacements recursively to all files in the
37
+ supplied paths that are not in the exclude pattern.
38
+ If no arguments are supplied, it reads from stdin and writes to stdout.
39
+
40
+ ## Examples
41
+
42
+ Patterns can be supplied in a text file, with one or more replacements consisting of regular
43
+ expression and replacement.
44
+ For example:
45
+
46
+ ```
47
+ # Sample pattern file
48
+ frobinator<tab>glurp
49
+ WhizzleStick<tab>AcmeExtrudedPlasticFunProvider
50
+ figure ([0-9+])<tab>Figure \\1
51
+ ```
52
+
53
+ (Where `<tab>` is an actual tab character.)
54
+ Each line is a replacement.
55
+ Empty lines and #-prefixed comments are ignored.
56
+
57
+ As a short-cut, a single replacement can be specified on the command line using `--from`
58
+ (match) and `--to` (replacement).
59
+
60
+ Examples:
61
+
62
+ ```bash
63
+ # Here `patfile` is a patterns file.
64
+ # Rewrite stdin:
65
+ repren -p patfile < input > output
66
+
67
+ # Shortcut with a single pattern replacement (replace foo with bar):
68
+ repren --from foo --to bar < input > output
69
+
70
+ # Rewrite a few files in place, also requiring matches be on word breaks:
71
+ repren -p patfile --word-breaks myfile1 myfile2 myfile3
72
+
73
+ # Rewrite whole directory trees. Since this is a big operation, we use
74
+ # `-n` to do a dry run that only prints what would be done:
75
+ repren -n -p patfile --word-breaks --full mydir1
76
+
77
+ # Now actually do it:
78
+ repren -p patfile --word-breaks --full mydir1
79
+
80
+ # Same as above, for all case variants:
81
+ repren -p patfile --word-breaks --preserve-case --full mydir1
82
+ ```
83
+
84
+ ## Usage
85
+
86
+ Run `repren --help` for full usage and flags.
87
+
88
+ If file paths are provided, repren replaces those files in place, leaving a backup with
89
+ extension ".orig".
90
+ If directory paths are provided, it applies replacements recursively to all files in the
91
+ supplied paths that are not in the exclude pattern.
92
+ If no arguments are supplied, it reads from stdin and writes to stdout.
93
+
94
+ ## Alternatives
95
+
96
+ Aren't there standard tools for this already?
97
+
98
+ It's a bit surprising, but not really.
99
+ Getting the features right is a bit tricky, I guess.
100
+ The
101
+ [standard](http://stackoverflow.com/questions/11392478/how-to-replace-a-string-in-multiple-files-in-linux-command-line/29191549)
102
+ [answers](http://stackoverflow.com/questions/6840332/rename-multiple-files-by-replacing-a-particular-pattern-in-the-filenames-using-a)
103
+ like *sed*, *perl*, *awk*, *rename*, *Vim* macros, or even IDE refactoring tools, often
104
+ cover specific cases, but tend to be error-prone or not offer specific features you probably
105
+ want.
106
+ Things like nondestructive mode, file renaming as well as search/replace, multiple
107
+ simultaneous renames/swaps, or renaming enclosing parent directories.
108
+ Also many of these vary by platform, which adds to the corner cases.
109
+ Inevitably you end up digging through the darker corners of some man page or writing ugly
110
+ scripts that would scare your mother.
111
+
112
+ ## Installation
113
+
114
+ No dependencies except Python 3.10+. It's easiest to install with pip:
115
+
116
+ ```
117
+ pip install repren
118
+ ```
119
+
120
+ Or, since it's just one file, you can copy the
121
+ [repren.py](https://raw.githubusercontent.com/jlevy/repren/master/repren/repren.py) script
122
+ somewhere convenient and make it executable.
123
+
124
+ ## Try it
125
+
126
+ Let's try a simple replacement in my working directory (which has a few random source
127
+ files):
128
+
129
+ ```bash
130
+ $ repren --from frobinator-server --to glurp-server --full --dry-run .
131
+ Dry run: No files will be changed
132
+ Using 1 patterns:
133
+ 'frobinator-server' -> 'glurp-server'
134
+ Found 102 files in: .
135
+ - modify: ./site.yml: 1 matches
136
+ - rename: ./roles/frobinator-server/defaults/main.yml -> ./roles/glurp-server/defaults/main.yml
137
+ - rename: ./roles/frobinator-server/files/deploy-frobinator-server.sh -> ./roles/glurp-server/files/deploy-frobinator-server.sh
138
+ - rename: ./roles/frobinator-server/files/install-graphviz.sh -> ./roles/glurp-server/files/install-graphviz.sh
139
+ - rename: ./roles/frobinator-server/files/frobinator-purge-old-deployments -> ./roles/glurp-server/files/frobinator-purge-old-deployments
140
+ - rename: ./roles/frobinator-server/handlers/main.yml -> ./roles/glurp-server/handlers/main.yml
141
+ - rename: ./roles/frobinator-server/tasks/main.yml -> ./roles/glurp-server/tasks/main.yml
142
+ - rename: ./roles/frobinator-server/templates/frobinator-webservice.conf.j2 -> ./roles/glurp-server/templates/frobinator-webservice.conf.j2
143
+ - rename: ./roles/frobinator-server/templates/frobinator-webui.conf.j2 -> ./roles/glurp-server/templates/frobinator-webui.conf.j2
144
+ Read 102 files (190382 chars), found 2 matches (0 skipped due to overlaps)
145
+ Dry run: Would have changed 2 files, including 0 renames
146
+ ```
147
+
148
+ That was a dry run, so if it looks good, it's easy to repeat that a second time, dropping
149
+ the `--dry-run` flag.
150
+ If this is in git, we'd do a git diff to verify, test, then commit it all.
151
+ If we messed up, there are still .orig files present.
152
+
153
+ ## Patterns
154
+
155
+ Patterns can be supplied using the `--from` and `--to` syntax above, but that only works for
156
+ a single pattern.
157
+
158
+ In general, you can perform multiple simultaneous replacements by putting them in a
159
+ *patterns file*. Each line consists of a regular expression and replacement.
160
+ For example:
161
+
162
+ ```
163
+ # Sample pattern file
164
+ frobinator<tab>glurp
165
+ WhizzleStick<tab>AcmeExtrudedPlasticFunProvider
166
+ figure ([0-9+])<tab>Figure \1
167
+ ```
168
+
169
+ (Where `<tab>` is an actual tab character.)
170
+
171
+ Empty lines and #-prefixed comments are ignored.
172
+ Capturing groups and back substitutions (such as \1 above) are supported.
173
+
174
+ ## Examples
175
+
176
+ ```
177
+ # Here `patfile` is a patterns file.
178
+ # Rewrite stdin:
179
+ repren -p patfile < input > output
180
+
181
+ # Shortcut with a single pattern replacement (replace foo with bar):
182
+ repren --from foo --to bar < input > output
183
+
184
+ # Rewrite a few files in place, also requiring matches be on word breaks:
185
+ repren -p patfile --word-breaks myfile1 myfile2 myfile3
186
+
187
+ # Rewrite whole directory trees. Since this is a big operation, we use
188
+ # `-n` to do a dry run that only prints what would be done:
189
+ repren -n -p patfile --word-breaks --full mydir1
190
+
191
+ # Now actually do it:
192
+ repren -p patfile --word-breaks --full mydir1
193
+
194
+ # Same as above, for all case variants:
195
+ repren -p patfile --word-breaks --preserve-case --full mydir1
196
+ ```
197
+
198
+ ## Notes
199
+
200
+ - As with sed, replacements are made line by line by default.
201
+ Memory permitting, replacements may be done on entire files using `--at-once`.
202
+
203
+ - As with sed, replacement text may include backreferences to groups within the regular
204
+ expression, using the usual syntax: \\1, \\2, etc.
205
+
206
+ - In the pattern file, both the regular expression and the replacement may contain the usual
207
+ escapes `\\n`, `\\t`, etc.
208
+ (To match a multi-line pattern, containing `\\n`, you must must use `--at-once`.)
209
+
210
+ - Replacements are all matched on each input file, then all replaced, so it's possible to
211
+ swap or otherwise change names in ways that would require multiple steps if done one
212
+ replacement at at a time.
213
+
214
+ - If two patterns have matches that overlap, only one replacement is applied, with
215
+ preference to the pattern appearing first in the patterns file.
216
+
217
+ - If one pattern is a subset of another, consider if `--word-breaks` will help.
218
+
219
+ - If patterns have special characters, `--literal` may help.
220
+
221
+ - The case-preserving option works by adding all case variants to the pattern replacements,
222
+ e.g. if the pattern file has foo_bar -> xxx_yyy, the replacements fooBar -> xxxYyy, FooBar
223
+ -> XxxYyy, FOO_BAR -> XXX_YYY are also made.
224
+ Assumes each pattern has one casing convention.
225
+
226
+ - The same logic applies to filenames, with patterns applied to the full file path with
227
+ slashes replaced and then and parent directories created as needed, e.g.
228
+ `my/path/to/filename` can be rewritten to `my/other/path/to/otherfile`. (Use caution and
229
+ test with `-n`, especially when using absolute path arguments!)
230
+
231
+ - Files are never clobbered by renames.
232
+ If a target already exists, or multiple files are renamed to the same target, numeric
233
+ suffixes will be added to make the files distinct (".1", ".2", etc.).
234
+
235
+ - Files are created at a temporary location, then renamed, so original files are left intact
236
+ in case of unexpected errors.
237
+ File permissions are preserved.
238
+
239
+ - Backups are created of all modified files, with the suffix ".orig".
240
+
241
+ - By default, recursive searching omits paths starting with ".". This may be adjusted with
242
+ `--exclude`. Files ending in `.orig` are always ignored.
243
+
244
+ - Data is handled as bytes internally, allowing it to work with any encoding or binary
245
+ files.
246
+ File contents are not decoded unless necessary (e.g., for logging).
247
+ However, patterns are specified as strings in the pattern file and command line arguments,
248
+ and file paths are handled as strings for filesystem operations.
249
+ """
250
+
251
+
252
+ import argparse
253
+ import bisect
254
+ from dataclasses import dataclass
255
+ import importlib.metadata
256
+ import os
257
+ import re
258
+ import shutil
259
+ import sys
260
+ from typing import BinaryIO, Callable, List, Match, Optional, Pattern, Tuple, TypeAlias
261
+
262
+ # Type aliases for clarity.
263
+ PatternType: TypeAlias = Tuple[Pattern[bytes], bytes]
264
+ FileHandle: TypeAlias = BinaryIO
265
+ MatchType: TypeAlias = Match[bytes]
266
+ PatternPair: TypeAlias = Tuple[MatchType, bytes]
267
+ TransformFunc: TypeAlias = Callable[[bytes], Tuple[bytes, "_MatchCounts"]]
268
+
269
+ # Get the version from package metadata.
270
+ VERSION: str
271
+ try:
272
+ VERSION = importlib.metadata.version("repren")
273
+ except importlib.metadata.PackageNotFoundError:
274
+ # Fallback version if package metadata is not available.
275
+ VERSION = "0.0.0.dev"
276
+
277
+ DESCRIPTION: str = "repren: Multi-pattern string replacement and file renaming"
278
+ LONG_DESCRIPTION: str = __doc__.split("Patterns:")[0].strip() # type: ignore
279
+
280
+ BACKUP_SUFFIX: str = ".orig"
281
+ TEMP_SUFFIX: str = ".repren.tmp"
282
+ DEFAULT_EXCLUDE_PAT: str = r"\."
283
+
284
+
285
+ def log(op: Optional[str], msg: str) -> None:
286
+ if op:
287
+ msg = "- %s: %s" % (op, msg)
288
+ print(msg, file=sys.stderr)
289
+
290
+
291
+ def fail(msg: str) -> None:
292
+ print("error: " + msg, file=sys.stderr)
293
+ sys.exit(1)
294
+
295
+
296
+ def safe_decode(b: bytes) -> str:
297
+ """
298
+ Safely decode bytes to a string for logging purposes.
299
+ Replaces invalid UTF-8 sequences to prevent errors.
300
+ """
301
+ return b.decode("utf-8", errors="backslashreplace")
302
+
303
+
304
+ @dataclass
305
+ class _Tally:
306
+ files: int = 0
307
+ chars: int = 0
308
+ matches: int = 0
309
+ valid_matches: int = 0
310
+ files_changed: int = 0
311
+ files_rewritten: int = 0
312
+ renames: int = 0
313
+
314
+
315
+ _tally: _Tally = _Tally()
316
+
317
+ # --- String matching ---
318
+
319
+
320
+ def _overlap(match1: MatchType, match2: MatchType) -> bool:
321
+ return match1.start() < match2.end() and match2.start() < match1.end()
322
+
323
+
324
+ def _sort_drop_overlaps(
325
+ matches: List[PatternPair], source_name: Optional[str] = None
326
+ ) -> List[PatternPair]:
327
+ """Select and sort a set of disjoint intervals, omitting ones that overlap."""
328
+ non_overlaps: List[PatternPair] = []
329
+ starts: List[int] = []
330
+ for match, replacement in matches:
331
+ index: int = bisect.bisect_left(starts, match.start())
332
+ if index > 0:
333
+ (prev_match, _) = non_overlaps[index - 1]
334
+ if _overlap(prev_match, match):
335
+ log(
336
+ source_name,
337
+ "Skipping overlapping match '%s' of '%s' that overlaps '%s' of '%s' on its left"
338
+ % (
339
+ safe_decode(match.group()),
340
+ safe_decode(match.re.pattern),
341
+ safe_decode(prev_match.group()),
342
+ safe_decode(prev_match.re.pattern),
343
+ ),
344
+ )
345
+ continue
346
+ if index < len(non_overlaps):
347
+ (next_match, _) = non_overlaps[index]
348
+ if _overlap(next_match, match):
349
+ log(
350
+ source_name,
351
+ "Skipping overlapping match '%s' of '%s' that overlaps '%s' of '%s' on its right"
352
+ % (
353
+ safe_decode(match.group()),
354
+ safe_decode(match.re.pattern),
355
+ safe_decode(next_match.group()),
356
+ safe_decode(next_match.re.pattern),
357
+ ),
358
+ )
359
+ continue
360
+ starts.insert(index, match.start())
361
+ non_overlaps.insert(index, (match, replacement))
362
+ return non_overlaps
363
+
364
+
365
+ def _apply_replacements(input_bytes: bytes, matches: List[PatternPair]) -> bytes:
366
+ out: List[bytes] = []
367
+ pos: int = 0
368
+ for match, replacement in matches:
369
+ out.append(input_bytes[pos : match.start()])
370
+ out.append(match.expand(replacement))
371
+ pos = match.end()
372
+ out.append(input_bytes[pos:])
373
+ return b"".join(out)
374
+
375
+
376
+ @dataclass
377
+ class _MatchCounts:
378
+ found: int = 0
379
+ valid: int = 0
380
+
381
+ def add(self, o: "_MatchCounts") -> None:
382
+ self.found += o.found
383
+ self.valid += o.valid
384
+
385
+
386
+ def multi_replace(
387
+ input_bytes: bytes,
388
+ patterns: List[PatternType],
389
+ is_path: bool = False,
390
+ source_name: Optional[str] = None,
391
+ ) -> Tuple[bytes, _MatchCounts]:
392
+ """Replace all occurrences in the input given a list of patterns (regex,
393
+ replacement), simultaneously, so that no replacement affects any other."""
394
+ matches: List[PatternPair] = []
395
+ for regex, replacement in patterns:
396
+ for match in regex.finditer(input_bytes):
397
+ matches.append((match, replacement))
398
+ valid_matches: List[PatternPair] = _sort_drop_overlaps(matches, source_name=source_name)
399
+ result: bytes = _apply_replacements(input_bytes, valid_matches)
400
+
401
+ global _tally
402
+ if not is_path:
403
+ _tally.chars += len(input_bytes)
404
+ _tally.matches += len(matches)
405
+ _tally.valid_matches += len(valid_matches)
406
+
407
+ return result, _MatchCounts(len(matches), len(valid_matches))
408
+
409
+
410
+ # --- Case handling (only used for case-preserving magic) ---
411
+
412
+ # TODO: Could handle dash-separated names as well.
413
+
414
+ # FooBarBaz -> Foo, Bar, Baz
415
+ # XMLFooHTTPBar -> XML, Foo, HTTP, Bar
416
+ _camel_split_pat1 = re.compile("([^A-Z])([A-Z])")
417
+ _camel_split_pat2 = re.compile("([A-Z])([A-Z][^A-Z])")
418
+
419
+ _name_pat = re.compile(r"\w+")
420
+
421
+
422
+ def _split_name(name: str) -> Tuple[str, List[str]]:
423
+ """
424
+ Split a CamelCase or underscore-formatted name into words.
425
+ Return separator and list of words.
426
+ """
427
+ if "_" in name:
428
+ # Underscore-separated name
429
+ return "_", name.split("_")
430
+ else:
431
+ # CamelCase or mixed case name
432
+ words = []
433
+ current_word = ""
434
+ i = 0
435
+ while i < len(name):
436
+ char = name[i]
437
+ if i > 0 and char.isupper():
438
+ if name[i - 1].islower() or (i + 1 < len(name) and name[i + 1].islower()):
439
+ # Start a new word
440
+ words.append(current_word)
441
+ current_word = char
442
+ else:
443
+ current_word += char
444
+ else:
445
+ current_word += char
446
+ i += 1
447
+ if current_word:
448
+ words.append(current_word)
449
+ return "", words
450
+
451
+
452
+ def _capitalize(word: str) -> str:
453
+ return word[0].upper() + word[1:].lower() if word else "" # Handle empty strings safely
454
+
455
+
456
+ def to_lower_camel(name: str) -> str:
457
+ separator, words = _split_name(name)
458
+ return words[0].lower() + "".join(_capitalize(word) for word in words[1:])
459
+
460
+
461
+ def to_upper_camel(name: str) -> str:
462
+ separator, words = _split_name(name)
463
+ return "".join(_capitalize(word) for word in words)
464
+
465
+
466
+ def to_lower_underscore(name: str) -> str:
467
+ separator, words = _split_name(name)
468
+ return "_".join(word.lower() for word in words)
469
+
470
+
471
+ def to_upper_underscore(name: str) -> str:
472
+ separator, words = _split_name(name)
473
+ return "_".join(word.upper() for word in words)
474
+
475
+
476
+ def _transform_expr(expr: str, transform: Callable[[str], str]) -> str:
477
+ transformed = _name_pat.sub(lambda m: transform(m.group()), expr)
478
+ return transformed
479
+
480
+
481
+ def all_case_variants(expr: str) -> List[str]:
482
+ """
483
+ Return all casing variations of an expression.
484
+ Note: This operates on strings and is called before pattern compilation.
485
+ """
486
+ return [
487
+ _transform_expr(expr, transform)
488
+ for transform in [to_lower_camel, to_upper_camel, to_lower_underscore, to_upper_underscore]
489
+ ]
490
+
491
+
492
+ # --- File handling ---
493
+
494
+
495
+ def make_parent_dirs(path: str) -> str:
496
+ """Ensure parent directories of a file are created as needed."""
497
+ dirname = os.path.dirname(path)
498
+ if dirname and not os.path.isdir(dirname):
499
+ os.makedirs(dirname)
500
+ return path
501
+
502
+
503
+ def move_file(source_path: str, dest_path: str, clobber: bool = False) -> None:
504
+ if not clobber:
505
+ trailing_num = re.compile(r"(.*)[.]\d+$")
506
+ i = 1
507
+ while os.path.exists(dest_path):
508
+ match = trailing_num.match(dest_path)
509
+ if match:
510
+ dest_path = match.group(1)
511
+ dest_path = "%s.%s" % (dest_path, i)
512
+ i += 1
513
+ shutil.move(source_path, dest_path)
514
+
515
+
516
+ def transform_stream(
517
+ transform: Optional[TransformFunc],
518
+ stream_in: BinaryIO,
519
+ stream_out: BinaryIO,
520
+ by_line: bool = False,
521
+ ) -> _MatchCounts:
522
+ counts = _MatchCounts()
523
+ if by_line:
524
+ for line in stream_in: # line will be bytes
525
+ if transform:
526
+ (new_line, new_counts) = transform(line)
527
+ counts.add(new_counts)
528
+ else:
529
+ new_line = line
530
+ stream_out.write(new_line)
531
+ else:
532
+ contents = stream_in.read() # contents will be bytes
533
+ (new_contents, new_counts) = (
534
+ transform(contents) if transform else (contents, _MatchCounts())
535
+ )
536
+ stream_out.write(new_contents)
537
+ return counts
538
+
539
+
540
+ def transform_file(
541
+ transform: Optional[TransformFunc],
542
+ source_path: str,
543
+ dest_path: str,
544
+ orig_suffix: str = BACKUP_SUFFIX,
545
+ temp_suffix: str = TEMP_SUFFIX,
546
+ by_line: bool = False,
547
+ dry_run: bool = False,
548
+ ) -> _MatchCounts:
549
+ """
550
+ Transform full contents of file at source_path with specified function,
551
+ either line-by-line or at once in memory, writing dest_path atomically and keeping a backup.
552
+ Source and destination may be the same path.
553
+ """
554
+ counts = _MatchCounts()
555
+ global _tally
556
+ changed = False
557
+ if transform:
558
+ orig_path = source_path + orig_suffix
559
+ temp_path = dest_path + temp_suffix
560
+ # TODO: This will create a directory even in dry_run mode, but perhaps that's acceptable.
561
+ # https://github.com/jlevy/repren/issues/6
562
+ make_parent_dirs(temp_path)
563
+ perms = os.stat(source_path).st_mode & 0o777
564
+ with open(source_path, "rb") as stream_in:
565
+ with os.fdopen(os.open(temp_path, os.O_WRONLY | os.O_CREAT, perms), "wb") as stream_out:
566
+ counts = transform_stream(transform, stream_in, stream_out, by_line=by_line)
567
+
568
+ # All the above happens in dry-run mode so we get tallies.
569
+ # Important: We don't modify original file until the above succeeds without exceptions.
570
+ if not dry_run and (dest_path != source_path or counts.found > 0):
571
+ move_file(source_path, orig_path, clobber=True)
572
+ move_file(temp_path, dest_path, clobber=False)
573
+ else:
574
+ # If we're in dry-run mode, or if there were no changes at all, just forget the output.
575
+ os.remove(temp_path)
576
+
577
+ _tally.files += 1
578
+ if counts.found > 0:
579
+ _tally.files_rewritten += 1
580
+ changed = True
581
+ if dest_path != source_path:
582
+ _tally.renames += 1
583
+ changed = True
584
+ elif dest_path != source_path:
585
+ if not dry_run:
586
+ make_parent_dirs(dest_path)
587
+ move_file(source_path, dest_path, clobber=False)
588
+ _tally.files += 1
589
+ _tally.renames += 1
590
+ changed = True
591
+ if changed:
592
+ _tally.files_changed += 1
593
+
594
+ return counts
595
+
596
+
597
+ def rewrite_file(
598
+ path: str, # Paths stay as str
599
+ patterns: List[PatternType],
600
+ do_renames: bool = False,
601
+ do_contents: bool = False,
602
+ by_line: bool = False,
603
+ dry_run: bool = False,
604
+ ) -> None:
605
+ # Convert path to bytes for pattern matching, then back to str for filesystem ops.
606
+ path_bytes = path.encode("utf-8")
607
+ dest_path_bytes = (
608
+ multi_replace(path_bytes, patterns, is_path=True)[0] if do_renames else path_bytes
609
+ )
610
+ dest_path = dest_path_bytes.decode("utf-8")
611
+
612
+ transform = None
613
+ if do_contents:
614
+ transform = lambda contents: multi_replace(contents, patterns, source_name=path)
615
+ counts = transform_file(transform, path, dest_path, by_line=by_line, dry_run=dry_run)
616
+ if counts.found > 0:
617
+ log("modify", "%s: %s matches" % (path, counts.found))
618
+ if dest_path != path:
619
+ log("rename", "%s -> %s" % (path, dest_path))
620
+
621
+
622
+ def walk_files(paths: List[str], exclude_pat: str = DEFAULT_EXCLUDE_PAT) -> List[str]:
623
+ out: List[str] = []
624
+ exclude_re = re.compile(exclude_pat)
625
+ for path in paths:
626
+ if not os.path.exists(path):
627
+ fail("path not found: %s" % path)
628
+ if os.path.isfile(path):
629
+ out.append(path)
630
+ else:
631
+ for root, dirs, files in os.walk(path):
632
+ out += [
633
+ os.path.join(root, f)
634
+ for f in files
635
+ if not exclude_re.match(f)
636
+ and not f.endswith(BACKUP_SUFFIX)
637
+ and not f.endswith(TEMP_SUFFIX)
638
+ ]
639
+ dirs[:] = [d for d in dirs if not exclude_re.match(d)]
640
+ return out
641
+
642
+
643
+ def rewrite_files(
644
+ root_paths: List[str],
645
+ patterns: List[PatternType],
646
+ do_renames: bool = False,
647
+ do_contents: bool = False,
648
+ exclude_pat: str = DEFAULT_EXCLUDE_PAT,
649
+ by_line: bool = False,
650
+ dry_run: bool = False,
651
+ ) -> None:
652
+ paths = walk_files(root_paths, exclude_pat=exclude_pat)
653
+ paths.sort() # Ensure deterministic order of file processing.
654
+ log(None, "Found %s files in: %s" % (len(paths), ", ".join(root_paths)))
655
+ for path in paths:
656
+ rewrite_file(
657
+ path,
658
+ patterns,
659
+ do_renames=do_renames,
660
+ do_contents=do_contents,
661
+ by_line=by_line,
662
+ dry_run=dry_run,
663
+ )
664
+
665
+
666
+ # --- Invocation ---
667
+
668
+
669
+ def parse_patterns(
670
+ patterns_str: str,
671
+ literal: bool = False,
672
+ word_breaks: bool = False,
673
+ insensitive: bool = False,
674
+ dotall: bool = False,
675
+ preserve_case: bool = False,
676
+ ) -> List[PatternType]:
677
+ patterns: List[PatternType] = []
678
+ flags = (re.IGNORECASE if insensitive else 0) | (re.DOTALL if dotall else 0)
679
+ for line in patterns_str.splitlines():
680
+ bits = None
681
+ try:
682
+ bits = line.split("\t")
683
+ if line.strip().startswith("#"):
684
+ continue
685
+ elif line.strip() and len(bits) == 2:
686
+ (regex, replacement) = bits
687
+ if literal:
688
+ regex = re.escape(regex)
689
+ pairs: List[Tuple[str, str]] = []
690
+ if preserve_case:
691
+ pairs += zip(all_case_variants(regex), all_case_variants(replacement))
692
+ pairs.append((regex, replacement))
693
+ # Avoid spurious overlap warnings by removing dups.
694
+ pairs = sorted(set(pairs))
695
+ for regex_variant, replacement_variant in pairs:
696
+ if word_breaks:
697
+ regex_variant = r"\b" + regex_variant + r"\b"
698
+ # Convert to bytes here
699
+ patterns.append(
700
+ (
701
+ re.compile(regex_variant.encode("utf-8"), flags),
702
+ replacement_variant.encode("utf-8"),
703
+ )
704
+ )
705
+ except Exception as e:
706
+ fail("error parsing pattern: %s: %s" % (e, bits))
707
+ return patterns
708
+
709
+
710
+ def main() -> None:
711
+ parser = argparse.ArgumentParser(
712
+ description=DESCRIPTION,
713
+ epilog=__doc__,
714
+ formatter_class=argparse.RawDescriptionHelpFormatter,
715
+ )
716
+ parser.add_argument(
717
+ "--version",
718
+ action="version",
719
+ version=f"%(prog)s {VERSION}",
720
+ help="show program's version number and exit",
721
+ )
722
+ parser.add_argument("--from", help="single replacement: match string", dest="from_pat")
723
+ parser.add_argument("--to", help="single replacement: replacement string", dest="to_pat")
724
+ parser.add_argument(
725
+ "-p",
726
+ "--patterns",
727
+ help="file with multiple replacement patterns (see below)",
728
+ dest="pat_file",
729
+ )
730
+ parser.add_argument(
731
+ "--full",
732
+ help="do file renames and search/replace on file contents",
733
+ dest="do_full",
734
+ action="store_true",
735
+ )
736
+ parser.add_argument(
737
+ "--renames",
738
+ help="do file renames only; do not modify file contents",
739
+ dest="do_renames",
740
+ action="store_true",
741
+ )
742
+ parser.add_argument(
743
+ "--literal",
744
+ help="use exact string matching, rather than regular expression matching",
745
+ dest="literal",
746
+ action="store_true",
747
+ )
748
+ parser.add_argument(
749
+ "-i",
750
+ "--insensitive",
751
+ help="match case-insensitively",
752
+ dest="insensitive",
753
+ action="store_true",
754
+ )
755
+ parser.add_argument("--dotall", help="match . to newlines", dest="dotall", action="store_true")
756
+ parser.add_argument(
757
+ "--preserve-case",
758
+ help="do case-preserving magic to transform all case variants (see below)",
759
+ dest="preserve_case",
760
+ action="store_true",
761
+ )
762
+ parser.add_argument(
763
+ "-b",
764
+ "--word-breaks",
765
+ help="require word breaks (regex \\b) around all matches",
766
+ dest="word_breaks",
767
+ action="store_true",
768
+ )
769
+ parser.add_argument(
770
+ "--exclude",
771
+ help="file/directory name regex to exclude",
772
+ dest="exclude_pat",
773
+ default=DEFAULT_EXCLUDE_PAT,
774
+ )
775
+ parser.add_argument(
776
+ "--at-once",
777
+ help="transform each file's contents at once, instead of line by line",
778
+ dest="at_once",
779
+ action="store_true",
780
+ )
781
+ parser.add_argument(
782
+ "-t",
783
+ "--parse-only",
784
+ help="parse and show patterns only",
785
+ dest="parse_only",
786
+ action="store_true",
787
+ )
788
+ parser.add_argument(
789
+ "-n",
790
+ "--dry-run",
791
+ help="dry run: just log matches without changing files",
792
+ dest="dry_run",
793
+ action="store_true",
794
+ )
795
+ parser.add_argument("root_paths", nargs="*", help="root paths to process")
796
+
797
+ options = parser.parse_args()
798
+
799
+ if options.dry_run:
800
+ log(None, "Dry run: No files will be changed")
801
+
802
+ options.do_contents = not options.do_renames
803
+ options.do_renames = options.do_renames or options.do_full
804
+
805
+ # log(None, "Settings: %s" % options)
806
+
807
+ if options.pat_file:
808
+ if options.from_pat or options.to_pat:
809
+ parser.error("cannot use both --patterns and --from/--to")
810
+ elif options.from_pat is None or options.to_pat is None:
811
+ parser.error("must specify --patterns or both --from and --to")
812
+ if options.insensitive and options.preserve_case:
813
+ parser.error("cannot use --insensitive and --preserve-case at once")
814
+
815
+ by_line = not options.at_once
816
+
817
+ if options.pat_file:
818
+ with open(options.pat_file, "rb") as f:
819
+ pat_str = f.read().decode("utf-8")
820
+ else:
821
+ pat_str = "%s\t%s" % (options.from_pat, options.to_pat)
822
+ patterns = parse_patterns(
823
+ pat_str,
824
+ literal=options.literal,
825
+ word_breaks=options.word_breaks,
826
+ insensitive=options.insensitive,
827
+ dotall=options.dotall,
828
+ preserve_case=options.preserve_case,
829
+ )
830
+
831
+ if len(patterns) == 0:
832
+ fail("found no parse patterns")
833
+
834
+ def format_flags(flags: int) -> str:
835
+ flags_str = "|".join([s for s in ["IGNORECASE", "DOTALL"] if flags & getattr(re, s)])
836
+ if flags_str:
837
+ flags_str += " "
838
+ return flags_str
839
+
840
+ log(
841
+ None,
842
+ ("Using %s patterns:\n " % len(patterns))
843
+ + "\n ".join(
844
+ [
845
+ "'%s' %s-> '%s'"
846
+ % (
847
+ safe_decode(regex.pattern),
848
+ format_flags(regex.flags),
849
+ safe_decode(replacement),
850
+ )
851
+ for (regex, replacement) in patterns
852
+ ]
853
+ ),
854
+ )
855
+
856
+ if not options.parse_only:
857
+ if len(options.root_paths) > 0:
858
+ rewrite_files(
859
+ options.root_paths,
860
+ patterns,
861
+ do_renames=options.do_renames,
862
+ do_contents=options.do_contents,
863
+ exclude_pat=options.exclude_pat,
864
+ by_line=by_line,
865
+ dry_run=options.dry_run,
866
+ )
867
+
868
+ log(
869
+ None,
870
+ "Read %s files (%s chars), found %s matches (%s skipped due to overlaps)"
871
+ % (
872
+ _tally.files,
873
+ _tally.chars,
874
+ _tally.valid_matches,
875
+ _tally.matches - _tally.valid_matches,
876
+ ),
877
+ )
878
+ change_words = "Dry run: Would have changed" if options.dry_run else "Changed"
879
+ log(
880
+ None,
881
+ "%s %s files (%s rewritten and %s renamed)"
882
+ % (change_words, _tally.files_changed, _tally.files_rewritten, _tally.renames),
883
+ )
884
+ else:
885
+ if options.do_renames:
886
+ parser.error("can't specify --renames on stdin; give filename arguments")
887
+ if options.dry_run:
888
+ parser.error("can't specify --dry-run on stdin; give filename arguments")
889
+ transform = lambda contents: multi_replace(contents, patterns)
890
+ transform_stream(transform, sys.stdin.buffer, sys.stdout.buffer, by_line=by_line)
891
+
892
+ log(
893
+ None,
894
+ "Read %s chars, made %s replacements (%s skipped due to overlaps)"
895
+ % (_tally.chars, _tally.valid_matches, _tally.matches - _tally.valid_matches),
896
+ )
897
+
898
+
899
+ if __name__ == "__main__":
900
+ main()
901
+
902
+ # TODO:
903
+ # --undo mode to revert a previous run by using .orig files; --clean mode to remove .orig files
904
+ # Log collisions
905
+ # Separate patterns file for renames and replacements
906
+ # Quiet and verbose modes (the latter logging each substitution)
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2014-2024 Joshua Levy
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,291 @@
1
+ Metadata-Version: 2.1
2
+ Name: repren
3
+ Version: 1.0.0
4
+ Summary: repren: Multi-pattern string replacement and file renaming
5
+ Home-page: https://github.com/jlevy/repren
6
+ License: MIT
7
+ Author: Joshua Levy
8
+ Author-email: joshua@cal.berkeley.edu
9
+ Requires-Python: >=3.10,<4.0
10
+ Classifier: Development Status :: 4 - Beta
11
+ Classifier: Environment :: Console
12
+ Classifier: Intended Audience :: Developers
13
+ Classifier: Intended Audience :: End Users/Desktop
14
+ Classifier: Intended Audience :: System Administrators
15
+ Classifier: License :: OSI Approved :: MIT License
16
+ Classifier: Operating System :: MacOS :: MacOS X
17
+ Classifier: Operating System :: POSIX
18
+ Classifier: Operating System :: Unix
19
+ Classifier: Programming Language :: Python :: 3
20
+ Classifier: Programming Language :: Python :: 3.10
21
+ Classifier: Programming Language :: Python :: 3.11
22
+ Classifier: Programming Language :: Python :: 3.12
23
+ Classifier: Programming Language :: Python :: 3.13
24
+ Classifier: Topic :: Software Development
25
+ Classifier: Topic :: Text Processing
26
+ Classifier: Topic :: Utilities
27
+ Project-URL: Repository, https://github.com/jlevy/repren
28
+ Description-Content-Type: text/markdown
29
+
30
+ # repren
31
+
32
+ ![But call me repren for short](images/awkward-150.jpg)
33
+
34
+
35
+ ## Rename Anything
36
+
37
+ Repren is a simple but flexible command-line tool for rewriting file contents according to a
38
+ set of regular expression patterns, and to rename or move files according to patterns.
39
+ Essentially, it is a general-purpose, brute-force text file refactoring tool.
40
+
41
+ For example, repren could rename all occurrences of certain class and variable names in a
42
+ set of Java source files, while simultaneously renaming the Java files according to the same
43
+ pattern.
44
+
45
+ It's more powerful than usual options like `perl -pie`, `rpl`, or `sed`:
46
+
47
+ - It can also rename files, including moving files and creating directories.
48
+
49
+ - It supports fully expressive regular expression substitutions.
50
+
51
+ - It performs group renamings, i.e. rename "foo" as "bar", and "bar" as "foo" at once,
52
+ without requiring a temporary intermediate rename.
53
+
54
+ - It is careful. It has a nondestructive mode, and prints clear stats on its changes.
55
+ It leaves backups.
56
+ File operations are done atomically, so interruptions never leave a previously existing
57
+ file truncated or partly edited.
58
+
59
+ - It supports "magic" case-preserving renames that let you find and rename identifiers with
60
+ case variants (lowerCamel, UpperCamel, lower_underscore, and UPPER_UNDERSCORE)
61
+ consistently.
62
+
63
+ - It has this nice documentation!
64
+
65
+ If file paths are provided, repren replaces those files in place, leaving a backup with
66
+ extension ".orig".
67
+
68
+ If directory paths are provided, it applies replacements recursively to all files in the
69
+ supplied paths that are not in the exclude pattern.
70
+ If no arguments are supplied, it reads from stdin and writes to stdout.
71
+
72
+ ## Examples
73
+
74
+ Patterns can be supplied in a text file, with one or more replacements consisting of regular
75
+ expression and replacement.
76
+ For example:
77
+
78
+ ```
79
+ # Sample pattern file
80
+ frobinator<tab>glurp
81
+ WhizzleStick<tab>AcmeExtrudedPlasticFunProvider
82
+ figure ([0-9+])<tab>Figure \1
83
+ ```
84
+
85
+ (Where `<tab>` is an actual tab character.)
86
+ Each line is a replacement.
87
+ Empty lines and #-prefixed comments are ignored.
88
+
89
+ As a short-cut, a single replacement can be specified on the command line using `--from`
90
+ (match) and `--to` (replacement).
91
+
92
+ Examples:
93
+
94
+ ```bash
95
+ # Here `patfile` is a patterns file.
96
+ # Rewrite stdin:
97
+ repren -p patfile < input > output
98
+
99
+ # Shortcut with a single pattern replacement (replace foo with bar):
100
+ repren --from foo --to bar < input > output
101
+
102
+ # Rewrite a few files in place, also requiring matches be on word breaks:
103
+ repren -p patfile --word-breaks myfile1 myfile2 myfile3
104
+
105
+ # Rewrite whole directory trees. Since this is a big operation, we use
106
+ # `-n` to do a dry run that only prints what would be done:
107
+ repren -n -p patfile --word-breaks --full mydir1
108
+
109
+ # Now actually do it:
110
+ repren -p patfile --word-breaks --full mydir1
111
+
112
+ # Same as above, for all case variants:
113
+ repren -p patfile --word-breaks --preserve-case --full mydir1
114
+ ```
115
+
116
+ ## Usage
117
+
118
+ Run `repren --help` for full usage and flags.
119
+
120
+ If file paths are provided, repren replaces those files in place, leaving a backup with
121
+ extension ".orig".
122
+ If directory paths are provided, it applies replacements recursively to all files in the
123
+ supplied paths that are not in the exclude pattern.
124
+ If no arguments are supplied, it reads from stdin and writes to stdout.
125
+
126
+ ## Alternatives
127
+
128
+ Aren't there standard tools for this already?
129
+
130
+ It's a bit surprising, but not really.
131
+ Getting the features right is a bit tricky, I guess.
132
+ The
133
+ [standard](http://stackoverflow.com/questions/11392478/how-to-replace-a-string-in-multiple-files-in-linux-command-line/29191549)
134
+ [answers](http://stackoverflow.com/questions/6840332/rename-multiple-files-by-replacing-a-particular-pattern-in-the-filenames-using-a)
135
+ like *sed*, *perl*, *awk*, *rename*, *Vim* macros, or even IDE refactoring tools, often
136
+ cover specific cases, but tend to be error-prone or not offer specific features you probably
137
+ want.
138
+ Things like nondestructive mode, file renaming as well as search/replace, multiple
139
+ simultaneous renames/swaps, or renaming enclosing parent directories.
140
+ Also many of these vary by platform, which adds to the corner cases.
141
+ Inevitably you end up digging through the darker corners of some man page or writing ugly
142
+ scripts that would scare your mother.
143
+
144
+ ## Installation
145
+
146
+ No dependencies except Python 3.10+. It's easiest to install with pip:
147
+
148
+ ```
149
+ pip install repren
150
+ ```
151
+
152
+ Or, since it's just one file, you can copy the
153
+ [repren.py](https://raw.githubusercontent.com/jlevy/repren/master/repren/repren.py) script
154
+ somewhere convenient and make it executable.
155
+
156
+ ## Try it
157
+
158
+ Let's try a simple replacement in my working directory (which has a few random source
159
+ files):
160
+
161
+ ```bash
162
+ $ repren --from frobinator-server --to glurp-server --full --dry-run .
163
+ Dry run: No files will be changed
164
+ Using 1 patterns:
165
+ 'frobinator-server' -> 'glurp-server'
166
+ Found 102 files in: .
167
+ - modify: ./site.yml: 1 matches
168
+ - rename: ./roles/frobinator-server/defaults/main.yml -> ./roles/glurp-server/defaults/main.yml
169
+ - rename: ./roles/frobinator-server/files/deploy-frobinator-server.sh -> ./roles/glurp-server/files/deploy-frobinator-server.sh
170
+ - rename: ./roles/frobinator-server/files/install-graphviz.sh -> ./roles/glurp-server/files/install-graphviz.sh
171
+ - rename: ./roles/frobinator-server/files/frobinator-purge-old-deployments -> ./roles/glurp-server/files/frobinator-purge-old-deployments
172
+ - rename: ./roles/frobinator-server/handlers/main.yml -> ./roles/glurp-server/handlers/main.yml
173
+ - rename: ./roles/frobinator-server/tasks/main.yml -> ./roles/glurp-server/tasks/main.yml
174
+ - rename: ./roles/frobinator-server/templates/frobinator-webservice.conf.j2 -> ./roles/glurp-server/templates/frobinator-webservice.conf.j2
175
+ - rename: ./roles/frobinator-server/templates/frobinator-webui.conf.j2 -> ./roles/glurp-server/templates/frobinator-webui.conf.j2
176
+ Read 102 files (190382 chars), found 2 matches (0 skipped due to overlaps)
177
+ Dry run: Would have changed 2 files, including 0 renames
178
+ ```
179
+
180
+ That was a dry run, so if it looks good, it's easy to repeat that a second time, dropping
181
+ the `--dry-run` flag.
182
+ If this is in git, we'd do a git diff to verify, test, then commit it all.
183
+ If we messed up, there are still .orig files present.
184
+
185
+ ## Patterns
186
+
187
+ Patterns can be supplied using the `--from` and `--to` syntax above, but that only works for
188
+ a single pattern.
189
+
190
+ In general, you can perform multiple simultaneous replacements by putting them in a
191
+ *patterns file*. Each line consists of a regular expression and replacement.
192
+ For example:
193
+
194
+ ```
195
+ # Sample pattern file
196
+ frobinator<tab>glurp
197
+ WhizzleStick<tab>AcmeExtrudedPlasticFunProvider
198
+ figure ([0-9+])<tab>Figure 
199
+ ```
200
+
201
+ (Where `<tab>` is an actual tab character.)
202
+
203
+ Empty lines and #-prefixed comments are ignored.
204
+ Capturing groups and back substitutions (such as  above) are supported.
205
+
206
+ ## Examples
207
+
208
+ ```
209
+ # Here `patfile` is a patterns file.
210
+ # Rewrite stdin:
211
+ repren -p patfile < input > output
212
+
213
+ # Shortcut with a single pattern replacement (replace foo with bar):
214
+ repren --from foo --to bar < input > output
215
+
216
+ # Rewrite a few files in place, also requiring matches be on word breaks:
217
+ repren -p patfile --word-breaks myfile1 myfile2 myfile3
218
+
219
+ # Rewrite whole directory trees. Since this is a big operation, we use
220
+ # `-n` to do a dry run that only prints what would be done:
221
+ repren -n -p patfile --word-breaks --full mydir1
222
+
223
+ # Now actually do it:
224
+ repren -p patfile --word-breaks --full mydir1
225
+
226
+ # Same as above, for all case variants:
227
+ repren -p patfile --word-breaks --preserve-case --full mydir1
228
+ ```
229
+
230
+ ## Notes
231
+
232
+ - As with sed, replacements are made line by line by default.
233
+ Memory permitting, replacements may be done on entire files using `--at-once`.
234
+
235
+ - As with sed, replacement text may include backreferences to groups within the regular
236
+ expression, using the usual syntax: \1, \2, etc.
237
+
238
+ - In the pattern file, both the regular expression and the replacement may contain the usual
239
+ escapes `\n`, `\t`, etc.
240
+ (To match a multi-line pattern, containing `\n`, you must must use `--at-once`.)
241
+
242
+ - Replacements are all matched on each input file, then all replaced, so it's possible to
243
+ swap or otherwise change names in ways that would require multiple steps if done one
244
+ replacement at at a time.
245
+
246
+ - If two patterns have matches that overlap, only one replacement is applied, with
247
+ preference to the pattern appearing first in the patterns file.
248
+
249
+ - If one pattern is a subset of another, consider if `--word-breaks` will help.
250
+
251
+ - If patterns have special characters, `--literal` may help.
252
+
253
+ - The case-preserving option works by adding all case variants to the pattern replacements,
254
+ e.g. if the pattern file has foo_bar -> xxx_yyy, the replacements fooBar -> xxxYyy, FooBar
255
+ -> XxxYyy, FOO_BAR -> XXX_YYY are also made.
256
+ Assumes each pattern has one casing convention.
257
+
258
+ - The same logic applies to filenames, with patterns applied to the full file path with
259
+ slashes replaced and then and parent directories created as needed, e.g.
260
+ `my/path/to/filename` can be rewritten to `my/other/path/to/otherfile`. (Use caution and
261
+ test with `-n`, especially when using absolute path arguments!)
262
+
263
+ - Files are never clobbered by renames.
264
+ If a target already exists, or multiple files are renamed to the same target, numeric
265
+ suffixes will be added to make the files distinct (".1", ".2", etc.).
266
+
267
+ - Files are created at a temporary location, then renamed, so original files are left intact
268
+ in case of unexpected errors.
269
+ File permissions are preserved.
270
+
271
+ - Backups are created of all modified files, with the suffix ".orig".
272
+
273
+ - By default, recursive searching omits paths starting with ".". This may be adjusted with
274
+ `--exclude`. Files ending in `.orig` are always ignored.
275
+
276
+ - Data is handled as bytes internally, allowing it to work with any encoding or binary
277
+ files.
278
+ File contents are not decoded unless necessary (e.g., for logging).
279
+ However, patterns are specified as strings in the pattern file and command line arguments,
280
+ and file paths are handled as strings for filesystem operations.
281
+
282
+
283
+ ## Contributing
284
+
285
+ Contributions and issues welcome!
286
+ Do understand and run the (manual) regression tests, review the output, and commit the clean
287
+ log changes if you submit a PR. (And mention this in the PR.)
288
+
289
+ ## License
290
+
291
+ MIT.
@@ -0,0 +1,7 @@
1
+ repren/__init__.py,sha256=J7PZmcXa7gIhIHoq0AwfXxqAu8ZuoCSx1vRcF9vddTw,45
2
+ repren/repren.py,sha256=lkFp0d-GYufrOcEkN34aZsXnqhTT1NDQtdZdp1C0NFk,31455
3
+ repren-1.0.0.dist-info/LICENSE,sha256=JgXH85sbHWY0JbRUAHif8NHnH9MTwpXwLmn7XSkdELI,1073
4
+ repren-1.0.0.dist-info/METADATA,sha256=0SWwyUreA6rbgPxIBP4slfBg79_bkG3w985BDQZ94Ds,11361
5
+ repren-1.0.0.dist-info/WHEEL,sha256=Nq82e9rUAnEjt98J6MlVmMCZb-t9cYE2Ir1kpBmnWfs,88
6
+ repren-1.0.0.dist-info/entry_points.txt,sha256=HzgzlYw4GJkg6C78_cuRE2vZZvn8rBpgLvHrwyxCXao,38
7
+ repren-1.0.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: poetry-core 1.9.1
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,3 @@
1
+ [console_scripts]
2
+ repren=repren:main
3
+