|
| 1 | +#!/usr/bin/env python |
| 2 | + |
| 3 | +import optparse, sys, os, tempfile, re |
| 4 | +try: import readline |
| 5 | +except ImportError: pass |
| 6 | +from stat import * |
| 7 | + |
| 8 | +def show_license(*eat): |
| 9 | + print """rpl - replace strings in files |
| 10 | +Copyright (C) 2004-2005 Goran Weinholt <[email protected]> |
| 11 | +Copyright (C) 2004 Christian Haggstrom <[email protected]> |
| 12 | +
|
| 13 | +This program is free software; you can redistribute it and/or modify |
| 14 | +it under the terms of the GNU General Public License as published by |
| 15 | +the Free Software Foundation; either version 2 of the License, or |
| 16 | +(at your option) any later version. |
| 17 | +
|
| 18 | +This program is distributed in the hope that it will be useful, |
| 19 | +but WITHOUT ANY WARRANTY; without even the implied warranty of |
| 20 | +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
| 21 | +GNU General Public License for more details. |
| 22 | +
|
| 23 | +You should have received a copy of the GNU General Public License |
| 24 | +along with this program; if not, write to the Free Software |
| 25 | +Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA |
| 26 | +""" |
| 27 | + sys.exit(0) |
| 28 | + |
| 29 | +def get_files(filenames, recurse, suffixen, verbose, hidden_files): |
| 30 | + new_files = [] |
| 31 | + for filename in filenames: |
| 32 | + try: |
| 33 | + perms = os.lstat(filename) |
| 34 | + except OSError, e: |
| 35 | + sys.stderr.write("\nrpl: Unable to read permissions of %s." |
| 36 | + % filename) |
| 37 | + sys.stderr.write("\nrpl: Error: %s" % e) |
| 38 | + sys.stderr.write("\nrpl: SKIPPING %s\n\n" % filename) |
| 39 | + continue |
| 40 | + |
| 41 | + if S_ISDIR(perms.st_mode): |
| 42 | + if recurse: |
| 43 | + if verbose: |
| 44 | + sys.stderr.write("Scanning Directory: %s\n" % filename) |
| 45 | + for f in os.listdir(filename): |
| 46 | + if not hidden_files and f.startswith('.'): |
| 47 | + if verbose: |
| 48 | + sys.stderr.write("Skipping: %s (hidden)\n" |
| 49 | + % os.path.join(filename, f)) |
| 50 | + continue |
| 51 | + new_files += get_files([os.path.join(filename, f)], |
| 52 | + recurse, suffixen, verbose, |
| 53 | + hidden_files) |
| 54 | + else: |
| 55 | + if verbose: |
| 56 | + sys.stderr.write("Directory: %s skipped.\n" % filename) |
| 57 | + continue |
| 58 | + elif S_ISREG(perms.st_mode): |
| 59 | + if suffixen != [] and \ |
| 60 | + not True in [ filename.endswith(s) for s in suffixen ]: |
| 61 | + sys.stderr.write("Skipping: %s (suffix not in list)\n" |
| 62 | + % filename) |
| 63 | + continue |
| 64 | + new_files += [(filename, perms)] |
| 65 | + else: |
| 66 | + sys.stderr.write("Skipping: %s (not a regular file)\n" |
| 67 | + % filename) |
| 68 | + return new_files |
| 69 | + |
| 70 | +def unescape(s): |
| 71 | + regex = re.compile(r'\\([0-7]{1,3}|x[0-9a-fA-F]{2}|[nrtvafb\\])') |
| 72 | + return regex.sub(lambda match: eval('"%s"' % match.group()), s) |
| 73 | + |
| 74 | +def blockrepl(instream, outstream, regex, before, after, blocksize=None): |
| 75 | + patlen = len(before) |
| 76 | + sum = 0 |
| 77 | + if not blocksize: blocksize = 2*patlen |
| 78 | + tonext = '' |
| 79 | + while 1: |
| 80 | + block = instream.read(blocksize) |
| 81 | + if not block: break |
| 82 | + parts = regex.split(tonext+block) |
| 83 | + sum += len(parts)-1 |
| 84 | + lastpart = parts[-1] |
| 85 | + if lastpart: |
| 86 | + tonext = lastpart[-patlen:] |
| 87 | + parts[-1] = lastpart[:-len(tonext)] |
| 88 | + else: |
| 89 | + tonext = '' |
| 90 | + outstream.write(after.join(parts)) |
| 91 | + outstream.write(tonext) |
| 92 | + return sum |
| 93 | + |
| 94 | +def main(): |
| 95 | + # First we parse the command line arguments... |
| 96 | + usage = "usage: %prog [options] old_string new_string target_file(s)" |
| 97 | + parser = optparse.OptionParser(usage, version="%prog 1.5.2") |
| 98 | + parser.add_option("-L", "--license", action="callback", |
| 99 | + callback=show_license, help="show the software license") |
| 100 | + parser.add_option("-x", metavar="SUFFIX", |
| 101 | + action="append", dest="suffixen", default=[], |
| 102 | + help="specify file suffix to match") |
| 103 | + parser.add_option("-i", "--ignore-case", |
| 104 | + action="store_true", dest="ignore_case", default=False, |
| 105 | + help="do a case insensitive match") |
| 106 | + parser.add_option("-w", "--whole-words", |
| 107 | + action="store_true", dest="whole_words", default=False, |
| 108 | + help="whole words (old_string matches on word boundaries only)") |
| 109 | + parser.add_option("-b", "--backup", |
| 110 | + action="store_true", dest="do_backup", default=False, |
| 111 | + help="make a backup before overwriting files") |
| 112 | + parser.add_option("-q", "--quiet", |
| 113 | + action="store_true", dest="quiet", default=False, |
| 114 | + help="quiet mode") |
| 115 | + parser.add_option("-v", "--verbose", |
| 116 | + action="store_true", dest="verbose", default=False, |
| 117 | + help="verbose mode") |
| 118 | + parser.add_option("-s", "--dry-run", |
| 119 | + action="store_true", dest="dry_run", default=False, |
| 120 | + help="simulation mode") |
| 121 | + parser.add_option("-R", "--recursive", |
| 122 | + action="store_true", dest="recurse", default=False, |
| 123 | + help="recurse into subdirectories") |
| 124 | + parser.add_option("-e", "--escape", |
| 125 | + action="store_true", dest="escapes", default=False, |
| 126 | + help="expand escapes in old_string and new_string") |
| 127 | + parser.add_option("-p", "--prompt", |
| 128 | + action="store_true", dest="prompt", default=False, |
| 129 | + help="prompt before modifying each file") |
| 130 | + parser.add_option("-f", "--force", |
| 131 | + action="store_true", dest="force", default=False, |
| 132 | + help="ignore errors when trying to preserve permissions") |
| 133 | + parser.add_option("-d", "--keep-times", |
| 134 | + action="store_true", dest="keep_times", default=False, |
| 135 | + help="keep the modification times on modified files") |
| 136 | + parser.add_option("-t", "--use-tmpdir", |
| 137 | + action="store_true", dest="use_tmpdir", default=False, |
| 138 | + help="use $TMPDIR for storing temporary files") |
| 139 | + parser.add_option("-a", "--all", |
| 140 | + action="store_true", dest="hidden_files", default=False, |
| 141 | + help="do not ignore files and directories starting with .") |
| 142 | + (opts, args) = parser.parse_args() |
| 143 | + |
| 144 | + # args should now contain old_str, new_str and a list of files/dirs |
| 145 | + if len(args) < 3: |
| 146 | + parser.error("must have at least three arguments") |
| 147 | + if args[0] == "": |
| 148 | + parser.error("must have something to replace") |
| 149 | + |
| 150 | + old_str = args[0] |
| 151 | + new_str = args[1] |
| 152 | + files = args[2:] |
| 153 | + |
| 154 | + # See if all the files actually exist |
| 155 | + for file in files: |
| 156 | + if not os.path.exists(file): |
| 157 | + sys.stderr.write("\nrpl: File \"%s\" not found.\n" % file) |
| 158 | + sys.exit(os.EX_DATAERR) |
| 159 | + |
| 160 | + if new_str == "" and not opts.quiet: |
| 161 | + sys.stderr.write("Really DELETE all occurences of %s " % old_str) |
| 162 | + if opts.ignore_case: |
| 163 | + sys.stderr.write("(ignoring case)? (Y/[N]) ") |
| 164 | + else: |
| 165 | + sys.stderr.write("(case sensitive)? (Y/[N]) ") |
| 166 | + line = raw_input() |
| 167 | + if line != "" and line[0] in "nN": |
| 168 | + sys.stderr.write("\nrpl: User cancelled operation.\n") |
| 169 | + sys.exit(os.EX_TEMPFAIL) |
| 170 | + |
| 171 | + # Tell the user what is going to happen |
| 172 | + if opts.dry_run: |
| 173 | + sys.stderr.write("Simulating replacement of \"%s\" with \"%s\" " |
| 174 | + % (old_str, new_str)) |
| 175 | + else: |
| 176 | + sys.stderr.write("Replacing \"%s\" with \"%s\" " % (old_str, new_str)) |
| 177 | + if opts.ignore_case: sys.stderr.write("(ignoring case) ") |
| 178 | + else: sys.stderr.write("(case sensitive) ") |
| 179 | + if opts.whole_words: sys.stderr.write("(whole words only)\n") |
| 180 | + else: sys.stderr.write("(partial words matched)\n") |
| 181 | + if opts.dry_run and not opts.quiet: |
| 182 | + sys.stderr.write("The files listed below would be modified in a replace operation.\n") |
| 183 | + |
| 184 | + if opts.escapes: |
| 185 | + old_str = unescape(old_str) |
| 186 | + new_str = unescape(new_str) |
| 187 | + if opts.whole_words: |
| 188 | + regex = re.compile(r"(?:(?<=\s)|^)" + re.escape(old_str) + r"(?=\s|$)", |
| 189 | + opts.ignore_case and re.I or 0) |
| 190 | + else: |
| 191 | + regex = re.compile(re.escape(old_str), opts.ignore_case and re.I or 0) |
| 192 | + |
| 193 | + total_matches = 0 |
| 194 | + files = get_files(files, opts.recurse, opts.suffixen, opts.verbose, opts.hidden_files) |
| 195 | + for filename, perms in files: |
| 196 | + # Open the input file |
| 197 | + try: f = open(filename, "rb") |
| 198 | + except IOError, e: |
| 199 | + sys.stderr.write("\nrpl: Unable to open %s for reading." % fn) |
| 200 | + sys.stderr.write("\nrpl: Error: %s" % e) |
| 201 | + sys.stderr.write("\nrpl: SKIPPING %s\n\n" % fn) |
| 202 | + continue |
| 203 | + |
| 204 | + # Find out where we should put the temporary file |
| 205 | + if opts.use_tmpdir: tempfile.tempdir = None |
| 206 | + else: tempfile.tempdir = os.path.dirname(filename) |
| 207 | + |
| 208 | + # Create the output file |
| 209 | + try: |
| 210 | + o, tmp_path = tempfile.mkstemp("", ".tmp.") |
| 211 | + o = os.fdopen(o, "wb") |
| 212 | + except OSError, e: |
| 213 | + sys.stderr.write("\nrpl: Unable to create temp file.") |
| 214 | + sys.stderr.write("\nrpl: Error: %s" % e) |
| 215 | + sys.stderr.write("\nrpl: (Type \"rpl -h\" and consider \"-t\" to specify temp file location.)") |
| 216 | + sys.stderr.write("\nrpl: SKIPPING %s\n\n" % filename) |
| 217 | + continue |
| 218 | + |
| 219 | + # Set permissions and owner |
| 220 | + try: |
| 221 | + os.chown(tmp_path, perms.st_uid, perms.st_gid) |
| 222 | + os.chmod(tmp_path, perms.st_mode) |
| 223 | + except OSError, e: |
| 224 | + sys.stderr.write("\nrpl: Unable to set owner/group/perms of %s" |
| 225 | + % filename) |
| 226 | + sys.stderr.write("\nrpl: Error: %s" % e) |
| 227 | + if opts.force: |
| 228 | + sys.stderr.write("\nrpl: WARNING: New owner/group/perms may not match!\n\n") |
| 229 | + else: |
| 230 | + sys.stderr.write("\nrpl: SKIPPING %s!\n\n" % filename) |
| 231 | + os.unlink(tmp_path) |
| 232 | + continue |
| 233 | + |
| 234 | + if opts.verbose and not opts.dry_run: |
| 235 | + sys.stderr.write("Processing: %s\n" % filename) |
| 236 | + elif not opts.quiet and not opts.dry_run: |
| 237 | + sys.stderr.write(".") |
| 238 | + sys.stderr.flush() |
| 239 | + |
| 240 | + # Do the actual work now |
| 241 | + matches = blockrepl(f, o, regex, old_str, new_str, 1024) |
| 242 | + |
| 243 | + f.close() |
| 244 | + o.close() |
| 245 | + |
| 246 | + if matches == 0: |
| 247 | + os.unlink(tmp_path) |
| 248 | + continue |
| 249 | + |
| 250 | + if opts.dry_run: |
| 251 | + try: |
| 252 | + fn = os.path.realpath(filename) |
| 253 | + except OSError, e: |
| 254 | + fn = filename |
| 255 | + if not opts.quiet: sys.stderr.write(" %s\n" % fn) |
| 256 | + os.unlink(tmp_path) |
| 257 | + total_matches += matches |
| 258 | + continue |
| 259 | + |
| 260 | + if opts.prompt: |
| 261 | + sys.stderr.write("\nSave '%s' ? ([Y]/N) " % filename) |
| 262 | + line = "" |
| 263 | + while line == "" or line[0] not in "Yy\nnN": |
| 264 | + line = raw_input() |
| 265 | + if line[0] in "nN": |
| 266 | + sys.stderr.write("Not Saved.\n") |
| 267 | + os.unlink(tmp_path) |
| 268 | + continue |
| 269 | + sys.stderr.write("Saved.\n") |
| 270 | + |
| 271 | + if opts.do_backup: |
| 272 | + try: os.rename(filename, filename + "~") |
| 273 | + except OSError, e: |
| 274 | + sys.stderr.write("rpl: An error occured renaming %s to %s." % (filename, filename + "~")) |
| 275 | + sys.stderr.write("\nrpl: Error: %s" % e) |
| 276 | + continue |
| 277 | + |
| 278 | + # Rename the file |
| 279 | + try: os.rename(tmp_path, filename) |
| 280 | + except OSError, e: |
| 281 | + sys.stderr.write("rpl: An error occured replacing %s with %s." |
| 282 | + % (tmp_path, filename)) |
| 283 | + sys.stderr.write("\nrpl: Error: %s" % e) |
| 284 | + os.unlink(tmp_path) |
| 285 | + continue |
| 286 | + |
| 287 | + # Restore the times |
| 288 | + if opts.keep_times: |
| 289 | + try: os.utime(filename, (perms.st_atime, perms.st_mtime)) |
| 290 | + except OSError, e: |
| 291 | + sys.stderr.write("\nrpl: An error occured setting the access time and mod time of the file %s.", filename) |
| 292 | + sys.stderr.write("\nrpl: Error: %s" % e) |
| 293 | + total_matches += matches |
| 294 | + |
| 295 | + # We're about to exit, give a summary |
| 296 | + if not opts.quiet: |
| 297 | + if opts.dry_run: |
| 298 | + sys.stderr.write("\nA Total of %lu matches found in %lu file%s searched." |
| 299 | + % (total_matches, |
| 300 | + len(files), |
| 301 | + len(files) != 1 and "s" or "")) |
| 302 | + sys.stderr.write("\nNone replaced (simulation mode).\n") |
| 303 | + else: |
| 304 | + sys.stderr.write("\nA Total of %lu matches replaced in %lu file%s searched.\n" |
| 305 | + % (total_matches, |
| 306 | + len(files), |
| 307 | + len(files) != 1 and "s" or "")) |
| 308 | + |
| 309 | +if __name__ == "__main__": |
| 310 | + main() |
0 commit comments