Ignore:
Timestamp:
Mar 19, 2014, 11:11:30 AM (11 years ago)
Author:
dmik
Message:

python: Update vendor to 2.7.6.

Location:
python/vendor/current/Tools/scripts
Files:
3 added
19 edited

Legend:

Unmodified
Added
Removed
  • python/vendor/current/Tools/scripts/2to3

    r2 r388  
    11#!/usr/bin/env python
     2import sys
    23from lib2to3.main import main
    3 import sys
    4 import os
    54
    65sys.exit(main("lib2to3.fixes"))
  • python/vendor/current/Tools/scripts/README

    r2 r388  
    55See also the Demo/scripts directory!
    66
     7analyze_dxp.py          Analyzes the result of sys.getdxp()
    78byext.py                Print lines/words/chars stats of files by extension
    89byteyears.py            Print product of a file's size and age
     
    1920dutree.py               Format du(1) output as a tree sorted by size
    2021eptags.py               Create Emacs TAGS file for Python modules
    21 finddiv.py              A grep-like tool that looks for division operators.
     22find_recursionlimit.py  Find the maximum recursion limit on this machine
     23finddiv.py              A grep-like tool that looks for division operators
    2224findlinksto.py          Recursively find symbolic links to a given path prefix
    2325findnocoding.py         Find source files which need an encoding declaration
     
    2830fixps.py                Fix Python scripts' first line (if #!)
    2931ftpmirror.py            FTP mirror script
    30 google.py               Open a webbrowser with Google.
    31 gprof2html.py           Transform gprof(1) output into useful HTML.
     32google.py               Open a webbrowser with Google
     33gprof2html.py           Transform gprof(1) output into useful HTML
    3234h2py.py                 Translate #define's into Python assignments
    3335hotshotmain.py          Main program to run script under control of hotshot
     
    5658reindent.py             Change .py files to use 4-space indents.
    5759rgrep.py                Reverse grep through a file (useful for big logfiles)
    58 setup.py                Install all scripts listed here.
     60serve.py                Small wsgiref-based web server, used in make serve in Doc
     61setup.py                Install all scripts listed here
    5962suff.py                 Sort a list of files by suffix
    60 svneol.py               Sets svn:eol-style on all files in directory.
     63svneol.py               Sets svn:eol-style on all files in directory
    6164texcheck.py             Validate Python LaTeX formatting (Raymond Hettinger)
    6265texi2html.py            Convert GNU texinfo files into HTML
  • python/vendor/current/Tools/scripts/byext.py

    r2 r388  
    22
    33"""Show file statistics by extension."""
     4
     5from __future__ import print_function
    46
    57import os
     
    2426        self.addstats("<dir>", "dirs", 1)
    2527        try:
    26             names = os.listdir(dir)
    27         except os.error, err:
     28            names = sorted(os.listdir(dir))
     29        except os.error as err:
    2830            sys.stderr.write("Can't list %s: %s\n" % (dir, err))
    2931            self.addstats("<dir>", "unlistable", 1)
    3032            return
    31         names.sort()
    3233        for name in names:
    3334            if name.startswith(".#"):
     
    5455        try:
    5556            f = open(filename, "rb")
    56         except IOError, err:
     57        except IOError as err:
    5758            sys.stderr.write("Can't open %s: %s\n" % (filename, err))
    5859            self.addstats(ext, "unopenable", 1)
     
    6162        f.close()
    6263        self.addstats(ext, "bytes", len(data))
    63         if '\0' in data:
     64        if b'\0' in data:
    6465            self.addstats(ext, "binary", 1)
    6566            return
     
    7879
    7980    def report(self):
    80         exts = self.stats.keys()
    81         exts.sort()
     81        exts = sorted(self.stats.keys())
    8282        # Get the column keys
    8383        columns = {}
    8484        for ext in exts:
    8585            columns.update(self.stats[ext])
    86         cols = columns.keys()
    87         cols.sort()
     86        cols = sorted(columns.keys())
    8887        colwidth = {}
    8988        colwidth["ext"] = max([len(ext) for ext in exts])
     
    110109        def printheader():
    111110            for col in cols:
    112                 print "%*s" % (colwidth[col], col),
    113             print
     111                print("%*s" % (colwidth[col], col), end=" ")
     112            print()
    114113        printheader()
    115114        for ext in exts:
    116115            for col in cols:
    117116                value = self.stats[ext].get(col, "")
    118                 print "%*s" % (colwidth[col], value),
    119             print
     117                print("%*s" % (colwidth[col], value), end=" ")
     118            print()
    120119        printheader() # Another header at the bottom
    121120
  • python/vendor/current/Tools/scripts/diff.py

    r2 r388  
     1#!/usr/bin/env python
    12""" Command line interface to difflib.py providing diffs in four formats:
    23
  • python/vendor/current/Tools/scripts/findnocoding.py

    r2 r388  
    3333
    3434
    35 decl_re = re.compile(r"coding[=:]\s*([-\w.]+)")
     35decl_re = re.compile(r'^[ \t\f]*#.*coding[:=][ \t]*([-\w.]+)')
    3636
    3737def get_declaration(line):
    38     match = decl_re.search(line)
     38    match = decl_re.match(line)
    3939    if match:
    4040        return match.group(1)
    41     return ''
     41    return b''
    4242
    4343def has_correct_encoding(text, codec):
  • python/vendor/current/Tools/scripts/fixcid.py

    r2 r388  
    189189        err(filename + ': rename failed (' + str(msg) + ')\n')
    190190        return 1
    191     # Return succes
     191    # Return success
    192192    return 0
    193193
  • python/vendor/current/Tools/scripts/fixnotice.py

    r2 r388  
    33"""(Ostensibly) fix copyright notices in files.
    44
    5 Actually, this sript will simply replace a block of text in a file from one
     5Actually, this script will simply replace a block of text in a file from one
    66string to another.  It will only do this once though, i.e. not globally
    77throughout 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 python2.3
     1#! /usr/bin/env python
    22
    33"""Transform gprof(1) output into useful HTML."""
  • python/vendor/current/Tools/scripts/h2py.py

    r2 r388  
    5959        except KeyError:
    6060            searchdirs=['/usr/include']
     61            try:
     62                searchdirs.insert(0, os.path.join('/usr/include',
     63                                                  os.environ['MULTIARCH']))
     64            except KeyError:
     65                pass
     66
    6167
    6268def main():
     
    96102        body = p.sub(' ', body)
    97103    # replace char literals by ord(...)
    98     body = p_char.sub('ord(\\0)', body)
     104    body = p_char.sub("ord('\\1')", body)
    99105    # Compute negative hexadecimal constants
    100106    start = 0
  • python/vendor/current/Tools/scripts/ifdef.py

    r2 r388  
    1010# minus those code sections that are suppressed by the selected
    1111# combination of defined/undefined symbols.  The #if(n)def/#else/#else
    12 # lines themselfs (if the #if(n)def tests for one of the mentioned
     12# lines themselves (if the #if(n)def tests for one of the mentioned
    1313# names) are removed as well.
    1414
    1515# Features: Arbitrary nesting of recognized and unrecognized
    16 # preprocesor statements works correctly.  Unrecognized #if* commands
     16# preprocessor statements works correctly.  Unrecognized #if* commands
    1717# are left in place, so it will never remove too much, only too
    1818# little.  It does accept whitespace around the '#' character.
  • python/vendor/current/Tools/scripts/mailerdaemon.py

    r2 r388  
     1#!/usr/bin/env python
    12"""mailerdaemon - classes to parse mailer-daemon messages"""
    23
  • python/vendor/current/Tools/scripts/parseentities.py

    r2 r388  
    1 #!/usr/local/bin/python
     1#!/usr/bin/env python
    22""" Utility for parsing HTML entity definitions available from:
    33
  • python/vendor/current/Tools/scripts/patchcheck.py

    r2 r388  
     1#!/usr/bin/env python
     2import re
     3import sys
     4import shutil
    15import os.path
    26import subprocess
    3 import sys
     7import sysconfig
    48
    59import reindent
     10import untabify
     11
     12
     13SRCDIR = sysconfig.get_config_var('srcdir')
     14
     15
     16def 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 "")
    619
    720
     
    1831                print info(result)
    1932            else:
    20                 if result:
    21                     print "yes"
    22                 else:
    23                     print "NO"
     33                print "yes" if result else "NO"
    2434            return result
    2535        return call_fxn
    2636    return decorated_fxn
    2737
     38
     39def 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
    2853@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)))
    3055def 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')
    4667
    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
     81def 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)
    4893def normalize_whitespace(file_paths):
    4994    """Make sure that the whitespace for .py files have been normalized."""
    5095    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)
     104def 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
     117ws_re = re.compile(br'\s+(\r?\n)$')
     118
     119@status("Fixing docs whitespace", info=report_modified_files)
     120def 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
    53137
    54138@status("Docs modified", modal=True)
    55139def 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
    61143
    62144@status("Misc/ACKS updated", modal=True)
    63145def credit_given(file_paths):
    64146    """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
    66149
    67150@status("Misc/NEWS updated", modal=True)
    68151def reported_news(file_paths):
    69152    """Check if Misc/NEWS has been changed."""
    70     return 'Misc/NEWS' in file_paths
     153    return os.path.join('Misc', 'NEWS') in file_paths
    71154
    72155
    73156def main():
    74157    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)
    77169    # Docs updated.
    78     docs_modified(file_paths)
     170    docs_modified(doc_files)
    79171    # Misc/ACKS changed.
    80     credit_given(file_paths)
     172    credit_given(misc_files)
    81173    # Misc/NEWS changed.
    82     reported_news(file_paths)
     174    reported_news(misc_files)
    83175
    84176    # 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
    87181
    88182
  • python/vendor/current/Tools/scripts/pathfix.py

    r2 r388  
    136136        err('%s: rename failed (%r)\n' % (filename, msg))
    137137        return 1
    138     # Return succes
     138    # Return success
    139139    return 0
    140140
  • python/vendor/current/Tools/scripts/pindent.py

    r2 r388  
    7777# - optionally do much more thorough reformatting, a la C indent
    7878
     79from __future__ import print_function
     80
    7981# Defaults
    8082STEPSIZE = 8
    8183TABSIZE = 8
    82 EXPANDTABS = 0
    83 
     84EXPANDTABS = False
     85
     86import io
    8487import re
    8588import sys
     
    9093next['try'] = 'except', 'finally'
    9194next['except'] = 'except', 'else', 'finally', 'end'
    92 next['else'] = next['finally'] = next['def'] = next['class'] = 'end'
     95next['else'] = next['finally'] = next['with'] = \
     96    next['def'] = next['class'] = 'end'
    9397next['end'] = ()
    9498start = 'if', 'while', 'for', 'try', 'with', 'def', 'class'
     
    106110        self._write = fpo.write
    107111        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*))?'
    110114                r'[^\w]')
    111115        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]+)'
    113117                r'(\s+(?P<id>[a-zA-Z_]\w*))?'
    114118                r'[^\w]')
     
    126130    def readline(self):
    127131        line = self.fpi.readline()
    128         if line: self.lineno = self.lineno + 1
     132        if line: self.lineno += 1
    129133        # end if
    130134        return line
     
    144148            if not line2: break
    145149            # end if
    146             line = line + line2
     150            line += line2
    147151        # end while
    148152        return line
    149153    # end def getline
    150154
    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):
    156156        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)
    162163    # end def putline
    163164
    164165    def reformat(self):
    165166        stack = []
    166         while 1:
     167        while True:
    167168            line = self.getline()
    168169            if not line: break      # EOF
     
    174175                if not stack:
    175176                    self.error('unexpected end')
    176                 elif stack[-1][0] != kw2:
     177                elif stack.pop()[0] != kw2:
    177178                    self.error('unmatched end')
    178179                # end if
    179                 del stack[-1:]
    180180                self.putline(line, len(stack))
    181181                continue
     
    209209        begin_counter = 0
    210210        end_counter = 0
    211         while 1:
     211        while True:
    212212            line = self.getline()
    213213            if not line: break      # EOF
     
    215215            m = self.endprog.match(line)
    216216            if m:
    217                 end_counter = end_counter + 1
     217                end_counter += 1
    218218                continue
    219219            # end if
     
    222222                kw = m.group('kw')
    223223                if kw in start:
    224                     begin_counter = begin_counter + 1
    225                 # end if
    226             # end if
    227             self.putline(line)
     224                    begin_counter += 1
     225                # end if
     226            # end if
     227            self.write(line)
    228228        # end while
    229229        if begin_counter - end_counter < 0:
     
    235235
    236236    def complete(self):
    237         self.indentsize = 1
    238237        stack = []
    239238        todo = []
    240         thisid = ''
    241         current, firstkw, lastkw, topid = 0, '', '', ''
    242         while 1:
     239        currentws = thisid = firstkw = lastkw = topid = ''
     240        while True:
    243241            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()
    248243            m = self.endprog.match(line)
    249244            if m:
     
    270265                # end if
    271266            # 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))
    273270            while indent < current:
    274271                if firstkw:
     
    279276                        s = '# end %s\n' % firstkw
    280277                    # end if
    281                     self.putline(s, current)
     278                    self.write(currentws + s)
    282279                    firstkw = lastkw = ''
    283280                # 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))
    286283            # end while
    287284            if indent == current and firstkw:
     
    298295                        s = '# end %s\n' % firstkw
    299296                    # end if
    300                     self.putline(s, current)
     297                    self.write(currentws + s)
    301298                    firstkw = lastkw = topid = ''
    302299                # end if
    303300            # end if
    304301            if indent > current:
    305                 stack.append((current, firstkw, lastkw, topid))
     302                stack.append((currentws, firstkw, lastkw, topid))
    306303                if thiskw and thiskw not in start:
    307304                    # error
    308305                    thiskw = ''
    309306                # end if
    310                 current, firstkw, lastkw, topid = \
    311                          indent, thiskw, thiskw, thisid
     307                currentws, firstkw, lastkw, topid = \
     308                          indentws, thiskw, thiskw, thisid
    312309            # end if
    313310            if thiskw:
     
    327324        # end while
    328325    # end def complete
    329 
    330326# end class PythonIndenter
    331327
     
    353349# end def reformat_filter
    354350
    355 class StringReader:
    356     def __init__(self, buf):
    357         self.buf = buf
    358         self.pos = 0
    359         self.len = len(self.buf)
    360     # end def __init__
    361     def read(self, n = 0):
    362         if n <= 0:
    363             n = self.len - self.pos
    364         else:
    365             n = min(n, self.len - self.pos)
    366         # end if
    367         r = self.buf[self.pos : self.pos + n]
    368         self.pos = self.pos + n
    369         return r
    370     # end def read
    371     def readline(self):
    372         i = self.buf.find('\n', self.pos)
    373         return self.read(i + 1 - self.pos)
    374     # end def readline
    375     def readlines(self):
    376         lines = []
    377         line = self.readline()
    378         while line:
    379             lines.append(line)
    380             line = self.readline()
    381         # end while
    382         return lines
    383     # end def readlines
    384     # seek/tell etc. are left as an exercise for the reader
    385 # end class StringReader
    386 
    387 class StringWriter:
    388     def __init__(self):
    389         self.buf = ''
    390     # end def __init__
    391     def write(self, s):
    392         self.buf = self.buf + s
    393     # end def write
    394     def getvalue(self):
    395         return self.buf
    396     # end def getvalue
    397 # end class StringWriter
    398 
    399351def 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()
    402354    pi = PythonIndenter(input, output, stepsize, tabsize, expandtabs)
    403355    pi.complete()
     
    406358
    407359def 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()
    410362    pi = PythonIndenter(input, output, stepsize, tabsize, expandtabs)
    411363    pi.delete()
     
    414366
    415367def 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()
    418370    pi = PythonIndenter(input, output, stepsize, tabsize, expandtabs)
    419371    pi.reformat()
     
    421373# end def reformat_string
    422374
     375def 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
    423392def 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
    425396    result = complete_string(source, stepsize, tabsize, expandtabs)
    426397    if source == result: return 0
    427398    # 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
    435403    return 1
    436404# end def complete_file
    437405
    438406def 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
    440410    result = delete_string(source, stepsize, tabsize, expandtabs)
    441411    if source == result: return 0
    442412    # 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
    450417    return 1
    451418# end def delete_file
    452419
    453420def 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
    455424    result = reformat_string(source, stepsize, tabsize, expandtabs)
    456425    if source == result: return 0
    457426    # 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
    465431    return 1
    466432# end def reformat_file
     
    475441-s stepsize: indentation step (default %(STEPSIZE)d)
    476442-t tabsize : the worth in spaces of a tab (default %(TABSIZE)d)
    477 -e         : expand TABs into spaces (defailt OFF)
     443-e         : expand TABs into spaces (default OFF)
    478444[file] ... : files are changed in place, with backups in file~
    479445If no files are specified or a single - is given,
     
    518484            tabsize = int(a)
    519485        elif o == '-e':
    520             expandtabs = 1
     486            expandtabs = True
    521487        # end if
    522488    # end for
  • python/vendor/current/Tools/scripts/redemo.py

    r2 r388  
     1#!/usr/bin/env python
    12"""Basic regular expression demostration facility (Perl style syntax)."""
    23
  • python/vendor/current/Tools/scripts/reindent-rst.py

    r2 r388  
    44# Currently just remove trailing whitespace.
    55
    6 from __future__ import with_statement
    7 import sys, re, shutil
     6import sys
    87
    9 ws_re = re.compile(r'\s+(\r?\n)$')
     8import patchcheck
    109
    1110def 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:])
    2712
    2813if __name__ == '__main__':
  • python/vendor/current/Tools/scripts/reindent.py

    r2 r388  
    3636The backup file is a copy of the one that is being reindented. The ".bak"
    3737file is generated with shutil.copy(), but some corner cases regarding
    38 user/group and permissions could leave the backup file more readable that
     38user/group and permissions could leave the backup file more readable than
    3939you'd prefer. You can always use the --nobackup option to prevent this.
    4040"""
     
    4545import os, shutil
    4646import sys
     47import io
    4748
    4849verbose    = 0
     
    109110        print "checking", file, "...",
    110111    try:
    111         f = open(file)
     112        f = io.open(file)
    112113    except IOError, msg:
    113114        errprint("%s: I/O Error: %s" % (file, str(msg)))
     
    116117    r = Reindenter(f)
    117118    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
    118125    if r.run():
    119126        if verbose:
     
    127134                if verbose:
    128135                    print "backed up", file, "to", bak
    129             f = open(file, "w")
     136            f = io.open(file, "w", newline=newline)
    130137            r.write(f)
    131138            f.close()
     
    173180        # indeed, they're our headache!
    174181        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
    175186
    176187    def run(self):
  • python/vendor/current/Tools/scripts/untabify.py

    r2 r388  
    2424        process(filename, tabsize)
    2525
    26 def process(filename, tabsize):
     26def process(filename, tabsize, verbose=True):
    2727    try:
    2828        f = open(filename)
     
    4444    except os.error:
    4545        pass
    46     f = open(filename, "w")
    47     f.write(newtext)
    48     f.close()
    49     print filename
     46    with open(filename, "w") as f:
     47        f.write(newtext)
     48    if verbose:
     49        print filename
    5050
    5151if __name__ == '__main__':
Note: See TracChangeset for help on using the changeset viewer.