Changeset 388 for python/vendor/current/Tools/scripts
- Timestamp:
- Mar 19, 2014, 11:11:30 AM (11 years ago)
- Location:
- python/vendor/current/Tools/scripts
- Files:
-
- 3 added
- 19 edited
Legend:
- Unmodified
- Added
- Removed
-
python/vendor/current/Tools/scripts/2to3
r2 r388 1 1 #!/usr/bin/env python 2 import sys 2 3 from lib2to3.main import main 3 import sys4 import os5 4 6 5 sys.exit(main("lib2to3.fixes")) -
python/vendor/current/Tools/scripts/README
r2 r388 5 5 See also the Demo/scripts directory! 6 6 7 analyze_dxp.py Analyzes the result of sys.getdxp() 7 8 byext.py Print lines/words/chars stats of files by extension 8 9 byteyears.py Print product of a file's size and age … … 19 20 dutree.py Format du(1) output as a tree sorted by size 20 21 eptags.py Create Emacs TAGS file for Python modules 21 finddiv.py A grep-like tool that looks for division operators. 22 find_recursionlimit.py Find the maximum recursion limit on this machine 23 finddiv.py A grep-like tool that looks for division operators 22 24 findlinksto.py Recursively find symbolic links to a given path prefix 23 25 findnocoding.py Find source files which need an encoding declaration … … 28 30 fixps.py Fix Python scripts' first line (if #!) 29 31 ftpmirror.py FTP mirror script 30 google.py Open a webbrowser with Google .31 gprof2html.py Transform gprof(1) output into useful HTML .32 google.py Open a webbrowser with Google 33 gprof2html.py Transform gprof(1) output into useful HTML 32 34 h2py.py Translate #define's into Python assignments 33 35 hotshotmain.py Main program to run script under control of hotshot … … 56 58 reindent.py Change .py files to use 4-space indents. 57 59 rgrep.py Reverse grep through a file (useful for big logfiles) 58 setup.py Install all scripts listed here. 60 serve.py Small wsgiref-based web server, used in make serve in Doc 61 setup.py Install all scripts listed here 59 62 suff.py Sort a list of files by suffix 60 svneol.py Sets svn:eol-style on all files in directory .63 svneol.py Sets svn:eol-style on all files in directory 61 64 texcheck.py Validate Python LaTeX formatting (Raymond Hettinger) 62 65 texi2html.py Convert GNU texinfo files into HTML -
python/vendor/current/Tools/scripts/byext.py
r2 r388 2 2 3 3 """Show file statistics by extension.""" 4 5 from __future__ import print_function 4 6 5 7 import os … … 24 26 self.addstats("<dir>", "dirs", 1) 25 27 try: 26 names = os.listdir(dir)27 except os.error ,err:28 names = sorted(os.listdir(dir)) 29 except os.error as err: 28 30 sys.stderr.write("Can't list %s: %s\n" % (dir, err)) 29 31 self.addstats("<dir>", "unlistable", 1) 30 32 return 31 names.sort()32 33 for name in names: 33 34 if name.startswith(".#"): … … 54 55 try: 55 56 f = open(filename, "rb") 56 except IOError ,err:57 except IOError as err: 57 58 sys.stderr.write("Can't open %s: %s\n" % (filename, err)) 58 59 self.addstats(ext, "unopenable", 1) … … 61 62 f.close() 62 63 self.addstats(ext, "bytes", len(data)) 63 if '\0' in data:64 if b'\0' in data: 64 65 self.addstats(ext, "binary", 1) 65 66 return … … 78 79 79 80 def report(self): 80 exts = self.stats.keys() 81 exts.sort() 81 exts = sorted(self.stats.keys()) 82 82 # Get the column keys 83 83 columns = {} 84 84 for ext in exts: 85 85 columns.update(self.stats[ext]) 86 cols = columns.keys() 87 cols.sort() 86 cols = sorted(columns.keys()) 88 87 colwidth = {} 89 88 colwidth["ext"] = max([len(ext) for ext in exts]) … … 110 109 def printheader(): 111 110 for col in cols: 112 print "%*s" % (colwidth[col], col),113 print 111 print("%*s" % (colwidth[col], col), end=" ") 112 print() 114 113 printheader() 115 114 for ext in exts: 116 115 for col in cols: 117 116 value = self.stats[ext].get(col, "") 118 print "%*s" % (colwidth[col], value),119 print 117 print("%*s" % (colwidth[col], value), end=" ") 118 print() 120 119 printheader() # Another header at the bottom 121 120 -
python/vendor/current/Tools/scripts/diff.py
r2 r388 1 #!/usr/bin/env python 1 2 """ Command line interface to difflib.py providing diffs in four formats: 2 3 -
python/vendor/current/Tools/scripts/findnocoding.py
r2 r388 33 33 34 34 35 decl_re = re.compile(r "coding[=:]\s*([-\w.]+)")35 decl_re = re.compile(r'^[ \t\f]*#.*coding[:=][ \t]*([-\w.]+)') 36 36 37 37 def get_declaration(line): 38 match = decl_re. search(line)38 match = decl_re.match(line) 39 39 if match: 40 40 return match.group(1) 41 return ''41 return b'' 42 42 43 43 def has_correct_encoding(text, codec): -
python/vendor/current/Tools/scripts/fixcid.py
r2 r388 189 189 err(filename + ': rename failed (' + str(msg) + ')\n') 190 190 return 1 191 # Return succes 191 # Return success 192 192 return 0 193 193 -
python/vendor/current/Tools/scripts/fixnotice.py
r2 r388 3 3 """(Ostensibly) fix copyright notices in files. 4 4 5 Actually, this s ript will simply replace a block of text in a file from one5 Actually, this script will simply replace a block of text in a file from one 6 6 string to another. It will only do this once though, i.e. not globally 7 7 throughout the file. It writes a backup file and then does an os.rename() -
python/vendor/current/Tools/scripts/gprof2html.py
r2 r388 1 #! /usr/bin/env python 2.31 #! /usr/bin/env python 2 2 3 3 """Transform gprof(1) output into useful HTML.""" -
python/vendor/current/Tools/scripts/h2py.py
r2 r388 59 59 except KeyError: 60 60 searchdirs=['/usr/include'] 61 try: 62 searchdirs.insert(0, os.path.join('/usr/include', 63 os.environ['MULTIARCH'])) 64 except KeyError: 65 pass 66 61 67 62 68 def main(): … … 96 102 body = p.sub(' ', body) 97 103 # replace char literals by ord(...) 98 body = p_char.sub( 'ord(\\0)', body)104 body = p_char.sub("ord('\\1')", body) 99 105 # Compute negative hexadecimal constants 100 106 start = 0 -
python/vendor/current/Tools/scripts/ifdef.py
r2 r388 10 10 # minus those code sections that are suppressed by the selected 11 11 # combination of defined/undefined symbols. The #if(n)def/#else/#else 12 # lines themsel fs (if the #if(n)def tests for one of the mentioned12 # lines themselves (if the #if(n)def tests for one of the mentioned 13 13 # names) are removed as well. 14 14 15 15 # Features: Arbitrary nesting of recognized and unrecognized 16 # preproces or statements works correctly. Unrecognized #if* commands16 # preprocessor statements works correctly. Unrecognized #if* commands 17 17 # are left in place, so it will never remove too much, only too 18 18 # little. It does accept whitespace around the '#' character. -
python/vendor/current/Tools/scripts/mailerdaemon.py
r2 r388 1 #!/usr/bin/env python 1 2 """mailerdaemon - classes to parse mailer-daemon messages""" 2 3 -
python/vendor/current/Tools/scripts/parseentities.py
r2 r388 1 #!/usr/ local/bin/python1 #!/usr/bin/env python 2 2 """ Utility for parsing HTML entity definitions available from: 3 3 -
python/vendor/current/Tools/scripts/patchcheck.py
r2 r388 1 #!/usr/bin/env python 2 import re 3 import sys 4 import shutil 1 5 import os.path 2 6 import subprocess 3 import sys 7 import sysconfig 4 8 5 9 import reindent 10 import untabify 11 12 13 SRCDIR = sysconfig.get_config_var('srcdir') 14 15 16 def n_files_str(count): 17 """Return 'N file(s)' with the proper plurality on 'file'.""" 18 return "{} file{}".format(count, "s" if count != 1 else "") 6 19 7 20 … … 18 31 print info(result) 19 32 else: 20 if result: 21 print "yes" 22 else: 23 print "NO" 33 print "yes" if result else "NO" 24 34 return result 25 35 return call_fxn 26 36 return decorated_fxn 27 37 38 39 def mq_patches_applied(): 40 """Check if there are any applied MQ patches.""" 41 cmd = 'hg qapplied' 42 st = subprocess.Popen(cmd.split(), 43 stdout=subprocess.PIPE, 44 stderr=subprocess.PIPE) 45 try: 46 bstdout, _ = st.communicate() 47 return st.returncode == 0 and bstdout 48 finally: 49 st.stdout.close() 50 st.stderr.close() 51 52 28 53 @status("Getting the list of files that have been added/changed", 29 info=lambda x: "%s files" % len(x))54 info=lambda x: n_files_str(len(x))) 30 55 def changed_files(): 31 """Run ``svn status`` and return a set of files that have been 32 changed/added.""" 33 cmd = 'svn status --quiet --non-interactive --ignore-externals' 34 svn_st = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE) 35 svn_st.wait() 36 output = [line.strip() for line in svn_st.stdout.readlines()] 37 files = set() 38 for line in output: 39 if not line[0] in ('A', 'M'): 40 continue 41 line_parts = line.split() 42 path = line_parts[-1] 43 if os.path.isfile(path): 44 files.add(path) 45 return files 56 """Get the list of changed or added files from the VCS.""" 57 if os.path.isdir(os.path.join(SRCDIR, '.hg')): 58 vcs = 'hg' 59 cmd = 'hg status --added --modified --no-status' 60 if mq_patches_applied(): 61 cmd += ' --rev qparent' 62 elif os.path.isdir('.svn'): 63 vcs = 'svn' 64 cmd = 'svn status --quiet --non-interactive --ignore-externals' 65 else: 66 sys.exit('need a checkout to get modified files') 46 67 47 @status("Fixing whitespace", info=lambda x: "%s files" % x) 68 st = subprocess.Popen(cmd.split(), stdout=subprocess.PIPE) 69 try: 70 st.wait() 71 if vcs == 'hg': 72 return [x.decode().rstrip() for x in st.stdout] 73 else: 74 output = (x.decode().rstrip().rsplit(None, 1)[-1] 75 for x in st.stdout if x[0] in 'AM') 76 return set(path for path in output if os.path.isfile(path)) 77 finally: 78 st.stdout.close() 79 80 81 def report_modified_files(file_paths): 82 count = len(file_paths) 83 if count == 0: 84 return n_files_str(count) 85 else: 86 lines = ["{}:".format(n_files_str(count))] 87 for path in file_paths: 88 lines.append(" {}".format(path)) 89 return "\n".join(lines) 90 91 92 @status("Fixing whitespace", info=report_modified_files) 48 93 def normalize_whitespace(file_paths): 49 94 """Make sure that the whitespace for .py files have been normalized.""" 50 95 reindent.makebackup = False # No need to create backups. 51 result = map(reindent.check, (x for x in file_paths if x.endswith('.py'))) 52 return sum(result) 96 fixed = [] 97 for path in (x for x in file_paths if x.endswith('.py')): 98 if reindent.check(os.path.join(SRCDIR, path)): 99 fixed.append(path) 100 return fixed 101 102 103 @status("Fixing C file whitespace", info=report_modified_files) 104 def normalize_c_whitespace(file_paths): 105 """Report if any C files """ 106 fixed = [] 107 for path in file_paths: 108 abspath = os.path.join(SRCDIR, path) 109 with open(abspath, 'r') as f: 110 if '\t' not in f.read(): 111 continue 112 untabify.process(abspath, 8, verbose=False) 113 fixed.append(path) 114 return fixed 115 116 117 ws_re = re.compile(br'\s+(\r?\n)$') 118 119 @status("Fixing docs whitespace", info=report_modified_files) 120 def normalize_docs_whitespace(file_paths): 121 fixed = [] 122 for path in file_paths: 123 abspath = os.path.join(SRCDIR, path) 124 try: 125 with open(abspath, 'rb') as f: 126 lines = f.readlines() 127 new_lines = [ws_re.sub(br'\1', line) for line in lines] 128 if new_lines != lines: 129 shutil.copyfile(abspath, abspath + '.bak') 130 with open(abspath, 'wb') as f: 131 f.writelines(new_lines) 132 fixed.append(path) 133 except Exception as err: 134 print 'Cannot fix %s: %s' % (path, err) 135 return fixed 136 53 137 54 138 @status("Docs modified", modal=True) 55 139 def docs_modified(file_paths): 56 """Report if any files in the Docs directory.""" 57 for path in file_paths: 58 if path.startswith("Doc"): 59 return True 60 return False 140 """Report if any file in the Doc directory has been changed.""" 141 return bool(file_paths) 142 61 143 62 144 @status("Misc/ACKS updated", modal=True) 63 145 def credit_given(file_paths): 64 146 """Check if Misc/ACKS has been changed.""" 65 return 'Misc/ACKS' in file_paths 147 return os.path.join('Misc', 'ACKS') in file_paths 148 66 149 67 150 @status("Misc/NEWS updated", modal=True) 68 151 def reported_news(file_paths): 69 152 """Check if Misc/NEWS has been changed.""" 70 return 'Misc/NEWS'in file_paths153 return os.path.join('Misc', 'NEWS') in file_paths 71 154 72 155 73 156 def main(): 74 157 file_paths = changed_files() 75 # PEP 7/8 verification. 76 normalize_whitespace(file_paths) 158 python_files = [fn for fn in file_paths if fn.endswith('.py')] 159 c_files = [fn for fn in file_paths if fn.endswith(('.c', '.h'))] 160 doc_files = [fn for fn in file_paths if fn.startswith('Doc')] 161 misc_files = {os.path.join('Misc', 'ACKS'), os.path.join('Misc', 'NEWS')}\ 162 & set(file_paths) 163 # PEP 8 whitespace rules enforcement. 164 normalize_whitespace(python_files) 165 # C rules enforcement. 166 normalize_c_whitespace(c_files) 167 # Doc whitespace enforcement. 168 normalize_docs_whitespace(doc_files) 77 169 # Docs updated. 78 docs_modified( file_paths)170 docs_modified(doc_files) 79 171 # Misc/ACKS changed. 80 credit_given( file_paths)172 credit_given(misc_files) 81 173 # Misc/NEWS changed. 82 reported_news( file_paths)174 reported_news(misc_files) 83 175 84 176 # Test suite run and passed. 85 print 86 print "Did you run the test suite?" 177 if python_files or c_files: 178 end = " and check for refleaks?" if c_files else "?" 179 print 180 print "Did you run the test suite" + end 87 181 88 182 -
python/vendor/current/Tools/scripts/pathfix.py
r2 r388 136 136 err('%s: rename failed (%r)\n' % (filename, msg)) 137 137 return 1 138 # Return succes 138 # Return success 139 139 return 0 140 140 -
python/vendor/current/Tools/scripts/pindent.py
r2 r388 77 77 # - optionally do much more thorough reformatting, a la C indent 78 78 79 from __future__ import print_function 80 79 81 # Defaults 80 82 STEPSIZE = 8 81 83 TABSIZE = 8 82 EXPANDTABS = 0 83 84 EXPANDTABS = False 85 86 import io 84 87 import re 85 88 import sys … … 90 93 next['try'] = 'except', 'finally' 91 94 next['except'] = 'except', 'else', 'finally', 'end' 92 next['else'] = next['finally'] = next['def'] = next['class'] = 'end' 95 next['else'] = next['finally'] = next['with'] = \ 96 next['def'] = next['class'] = 'end' 93 97 next['end'] = () 94 98 start = 'if', 'while', 'for', 'try', 'with', 'def', 'class' … … 106 110 self._write = fpo.write 107 111 self.kwprog = re.compile( 108 r'^ \s*(?P<kw>[a-z]+)'109 r'( \s+(?P<id>[a-zA-Z_]\w*))?'112 r'^(?:\s|\\\n)*(?P<kw>[a-z]+)' 113 r'((?:\s|\\\n)+(?P<id>[a-zA-Z_]\w*))?' 110 114 r'[^\w]') 111 115 self.endprog = re.compile( 112 r'^ \s*#?\s*end\s+(?P<kw>[a-z]+)'116 r'^(?:\s|\\\n)*#?\s*end\s+(?P<kw>[a-z]+)' 113 117 r'(\s+(?P<id>[a-zA-Z_]\w*))?' 114 118 r'[^\w]') … … 126 130 def readline(self): 127 131 line = self.fpi.readline() 128 if line: self.lineno = self.lineno +1132 if line: self.lineno += 1 129 133 # end if 130 134 return line … … 144 148 if not line2: break 145 149 # end if 146 line = line +line2150 line += line2 147 151 # end while 148 152 return line 149 153 # end def getline 150 154 151 def putline(self, line, indent = None): 152 if indent is None: 153 self.write(line) 154 return 155 # end if 155 def putline(self, line, indent): 156 156 tabs, spaces = divmod(indent*self.indentsize, self.tabsize) 157 i = 0 158 m = self.wsprog.match(line) 159 if m: i = m.end() 160 # end if 161 self.write('\t'*tabs + ' '*spaces + line[i:]) 157 i = self.wsprog.match(line).end() 158 line = line[i:] 159 if line[:1] not in ('\n', '\r', ''): 160 line = '\t'*tabs + ' '*spaces + line 161 # end if 162 self.write(line) 162 163 # end def putline 163 164 164 165 def reformat(self): 165 166 stack = [] 166 while 1:167 while True: 167 168 line = self.getline() 168 169 if not line: break # EOF … … 174 175 if not stack: 175 176 self.error('unexpected end') 176 elif stack [-1][0] != kw2:177 elif stack.pop()[0] != kw2: 177 178 self.error('unmatched end') 178 179 # end if 179 del stack[-1:]180 180 self.putline(line, len(stack)) 181 181 continue … … 209 209 begin_counter = 0 210 210 end_counter = 0 211 while 1:211 while True: 212 212 line = self.getline() 213 213 if not line: break # EOF … … 215 215 m = self.endprog.match(line) 216 216 if m: 217 end_counter = end_counter +1217 end_counter += 1 218 218 continue 219 219 # end if … … 222 222 kw = m.group('kw') 223 223 if kw in start: 224 begin_counter = begin_counter +1225 # end if 226 # end if 227 self. putline(line)224 begin_counter += 1 225 # end if 226 # end if 227 self.write(line) 228 228 # end while 229 229 if begin_counter - end_counter < 0: … … 235 235 236 236 def complete(self): 237 self.indentsize = 1238 237 stack = [] 239 238 todo = [] 240 thisid = '' 241 current, firstkw, lastkw, topid = 0, '', '', '' 242 while 1: 239 currentws = thisid = firstkw = lastkw = topid = '' 240 while True: 243 241 line = self.getline() 244 i = 0 245 m = self.wsprog.match(line) 246 if m: i = m.end() 247 # end if 242 i = self.wsprog.match(line).end() 248 243 m = self.endprog.match(line) 249 244 if m: … … 270 265 # end if 271 266 # end if 272 indent = len(line[:i].expandtabs(self.tabsize)) 267 indentws = line[:i] 268 indent = len(indentws.expandtabs(self.tabsize)) 269 current = len(currentws.expandtabs(self.tabsize)) 273 270 while indent < current: 274 271 if firstkw: … … 279 276 s = '# end %s\n' % firstkw 280 277 # end if 281 self. putline(s, current)278 self.write(currentws + s) 282 279 firstkw = lastkw = '' 283 280 # end if 284 current , firstkw, lastkw, topid = stack[-1]285 del stack[-1]281 currentws, firstkw, lastkw, topid = stack.pop() 282 current = len(currentws.expandtabs(self.tabsize)) 286 283 # end while 287 284 if indent == current and firstkw: … … 298 295 s = '# end %s\n' % firstkw 299 296 # end if 300 self. putline(s, current)297 self.write(currentws + s) 301 298 firstkw = lastkw = topid = '' 302 299 # end if 303 300 # end if 304 301 if indent > current: 305 stack.append((current , firstkw, lastkw, topid))302 stack.append((currentws, firstkw, lastkw, topid)) 306 303 if thiskw and thiskw not in start: 307 304 # error 308 305 thiskw = '' 309 306 # end if 310 current , firstkw, lastkw, topid = \311 indent, thiskw, thiskw, thisid307 currentws, firstkw, lastkw, topid = \ 308 indentws, thiskw, thiskw, thisid 312 309 # end if 313 310 if thiskw: … … 327 324 # end while 328 325 # end def complete 329 330 326 # end class PythonIndenter 331 327 … … 353 349 # end def reformat_filter 354 350 355 class StringReader:356 def __init__(self, buf):357 self.buf = buf358 self.pos = 0359 self.len = len(self.buf)360 # end def __init__361 def read(self, n = 0):362 if n <= 0:363 n = self.len - self.pos364 else:365 n = min(n, self.len - self.pos)366 # end if367 r = self.buf[self.pos : self.pos + n]368 self.pos = self.pos + n369 return r370 # end def read371 def readline(self):372 i = self.buf.find('\n', self.pos)373 return self.read(i + 1 - self.pos)374 # end def readline375 def readlines(self):376 lines = []377 line = self.readline()378 while line:379 lines.append(line)380 line = self.readline()381 # end while382 return lines383 # end def readlines384 # seek/tell etc. are left as an exercise for the reader385 # end class StringReader386 387 class StringWriter:388 def __init__(self):389 self.buf = ''390 # end def __init__391 def write(self, s):392 self.buf = self.buf + s393 # end def write394 def getvalue(self):395 return self.buf396 # end def getvalue397 # end class StringWriter398 399 351 def complete_string(source, stepsize = STEPSIZE, tabsize = TABSIZE, expandtabs = EXPANDTABS): 400 input = StringReader(source)401 output = StringWriter()352 input = io.BytesIO(source) 353 output = io.BytesIO() 402 354 pi = PythonIndenter(input, output, stepsize, tabsize, expandtabs) 403 355 pi.complete() … … 406 358 407 359 def delete_string(source, stepsize = STEPSIZE, tabsize = TABSIZE, expandtabs = EXPANDTABS): 408 input = StringReader(source)409 output = StringWriter()360 input = io.BytesIO(source) 361 output = io.BytesIO() 410 362 pi = PythonIndenter(input, output, stepsize, tabsize, expandtabs) 411 363 pi.delete() … … 414 366 415 367 def reformat_string(source, stepsize = STEPSIZE, tabsize = TABSIZE, expandtabs = EXPANDTABS): 416 input = StringReader(source)417 output = StringWriter()368 input = io.BytesIO(source) 369 output = io.BytesIO() 418 370 pi = PythonIndenter(input, output, stepsize, tabsize, expandtabs) 419 371 pi.reformat() … … 421 373 # end def reformat_string 422 374 375 def make_backup(filename): 376 import os, os.path 377 backup = filename + '~' 378 if os.path.lexists(backup): 379 try: 380 os.remove(backup) 381 except os.error: 382 print("Can't remove backup %r" % (backup,), file=sys.stderr) 383 # end try 384 # end if 385 try: 386 os.rename(filename, backup) 387 except os.error: 388 print("Can't rename %r to %r" % (filename, backup), file=sys.stderr) 389 # end try 390 # end def make_backup 391 423 392 def complete_file(filename, stepsize = STEPSIZE, tabsize = TABSIZE, expandtabs = EXPANDTABS): 424 source = open(filename, 'r').read() 393 with open(filename, 'r') as f: 394 source = f.read() 395 # end with 425 396 result = complete_string(source, stepsize, tabsize, expandtabs) 426 397 if source == result: return 0 427 398 # end if 428 import os 429 try: os.rename(filename, filename + '~') 430 except os.error: pass 431 # end try 432 f = open(filename, 'w') 433 f.write(result) 434 f.close() 399 make_backup(filename) 400 with open(filename, 'w') as f: 401 f.write(result) 402 # end with 435 403 return 1 436 404 # end def complete_file 437 405 438 406 def delete_file(filename, stepsize = STEPSIZE, tabsize = TABSIZE, expandtabs = EXPANDTABS): 439 source = open(filename, 'r').read() 407 with open(filename, 'r') as f: 408 source = f.read() 409 # end with 440 410 result = delete_string(source, stepsize, tabsize, expandtabs) 441 411 if source == result: return 0 442 412 # end if 443 import os 444 try: os.rename(filename, filename + '~') 445 except os.error: pass 446 # end try 447 f = open(filename, 'w') 448 f.write(result) 449 f.close() 413 make_backup(filename) 414 with open(filename, 'w') as f: 415 f.write(result) 416 # end with 450 417 return 1 451 418 # end def delete_file 452 419 453 420 def reformat_file(filename, stepsize = STEPSIZE, tabsize = TABSIZE, expandtabs = EXPANDTABS): 454 source = open(filename, 'r').read() 421 with open(filename, 'r') as f: 422 source = f.read() 423 # end with 455 424 result = reformat_string(source, stepsize, tabsize, expandtabs) 456 425 if source == result: return 0 457 426 # end if 458 import os 459 try: os.rename(filename, filename + '~') 460 except os.error: pass 461 # end try 462 f = open(filename, 'w') 463 f.write(result) 464 f.close() 427 make_backup(filename) 428 with open(filename, 'w') as f: 429 f.write(result) 430 # end with 465 431 return 1 466 432 # end def reformat_file … … 475 441 -s stepsize: indentation step (default %(STEPSIZE)d) 476 442 -t tabsize : the worth in spaces of a tab (default %(TABSIZE)d) 477 -e : expand TABs into spaces (defa ilt OFF)443 -e : expand TABs into spaces (default OFF) 478 444 [file] ... : files are changed in place, with backups in file~ 479 445 If no files are specified or a single - is given, … … 518 484 tabsize = int(a) 519 485 elif o == '-e': 520 expandtabs = 1486 expandtabs = True 521 487 # end if 522 488 # end for -
python/vendor/current/Tools/scripts/redemo.py
r2 r388 1 #!/usr/bin/env python 1 2 """Basic regular expression demostration facility (Perl style syntax).""" 2 3 -
python/vendor/current/Tools/scripts/reindent-rst.py
r2 r388 4 4 # Currently just remove trailing whitespace. 5 5 6 from __future__ import with_statement 7 import sys, re, shutil 6 import sys 8 7 9 ws_re = re.compile(r'\s+(\r?\n)$') 8 import patchcheck 10 9 11 10 def main(argv=sys.argv): 12 rv = 0 13 for filename in argv[1:]: 14 try: 15 with open(filename, 'rb') as f: 16 lines = f.readlines() 17 new_lines = [ws_re.sub(r'\1', line) for line in lines] 18 if new_lines != lines: 19 print 'Fixing %s...' % filename 20 shutil.copyfile(filename, filename + '.bak') 21 with open(filename, 'wb') as f: 22 f.writelines(new_lines) 23 except Exception, err: 24 print 'Cannot fix %s: %s' % (filename, err) 25 rv = 1 26 return rv 11 patchcheck.normalize_docs_whitespace(argv[1:]) 27 12 28 13 if __name__ == '__main__': -
python/vendor/current/Tools/scripts/reindent.py
r2 r388 36 36 The backup file is a copy of the one that is being reindented. The ".bak" 37 37 file is generated with shutil.copy(), but some corner cases regarding 38 user/group and permissions could leave the backup file more readable tha t38 user/group and permissions could leave the backup file more readable than 39 39 you'd prefer. You can always use the --nobackup option to prevent this. 40 40 """ … … 45 45 import os, shutil 46 46 import sys 47 import io 47 48 48 49 verbose = 0 … … 109 110 print "checking", file, "...", 110 111 try: 111 f = open(file)112 f = io.open(file) 112 113 except IOError, msg: 113 114 errprint("%s: I/O Error: %s" % (file, str(msg))) … … 116 117 r = Reindenter(f) 117 118 f.close() 119 120 newline = r.newlines 121 if isinstance(newline, tuple): 122 errprint("%s: mixed newlines detected; cannot process file" % file) 123 return 124 118 125 if r.run(): 119 126 if verbose: … … 127 134 if verbose: 128 135 print "backed up", file, "to", bak 129 f = open(file, "w")136 f = io.open(file, "w", newline=newline) 130 137 r.write(f) 131 138 f.close() … … 173 180 # indeed, they're our headache! 174 181 self.stats = [] 182 183 # Save the newlines found in the file so they can be used to 184 # create output without mutating the newlines. 185 self.newlines = f.newlines 175 186 176 187 def run(self): -
python/vendor/current/Tools/scripts/untabify.py
r2 r388 24 24 process(filename, tabsize) 25 25 26 def process(filename, tabsize ):26 def process(filename, tabsize, verbose=True): 27 27 try: 28 28 f = open(filename) … … 44 44 except os.error: 45 45 pass 46 f = open(filename, "w")47 f.write(newtext)48 f.close()49 print filename46 with open(filename, "w") as f: 47 f.write(newtext) 48 if verbose: 49 print filename 50 50 51 51 if __name__ == '__main__':
Note:
See TracChangeset
for help on using the changeset viewer.