diff options
author | Stefan Israelsson Tampe <stefan.itampe@gmail.com> | 2018-08-20 15:02:25 +0200 |
---|---|---|
committer | Stefan Israelsson Tampe <stefan.itampe@gmail.com> | 2018-08-20 15:02:25 +0200 |
commit | 03f46d99946975e1bd8baccfad4709a3e9d4354d (patch) | |
tree | efa86d9c08f5a3b1d7be77f60677400f8841b841 | |
parent | fc3fb780cd2395b58c1b36693d0947bb00ffcae4 (diff) |
getopt.py and filecmp.py
-rw-r--r-- | modules/language/python/compile.scm | 3 | ||||
-rw-r--r-- | modules/language/python/dict.scm | 15 | ||||
-rw-r--r-- | modules/language/python/module/filecmp.py | 304 | ||||
-rw-r--r-- | modules/language/python/module/getopt.py | 213 |
4 files changed, 534 insertions, 1 deletions
diff --git a/modules/language/python/compile.scm b/modules/language/python/compile.scm index 2cef86b..3bf81ef 100644 --- a/modules/language/python/compile.scm +++ b/modules/language/python/compile.scm @@ -1021,6 +1021,7 @@ (let ((s (exp vs a))) (fluid-set! ignore (cons s (fluid-ref ignore))) + (dont-warn s) s)) ((a . b) @@ -2442,6 +2443,8 @@ (set v x val)) ((_ v (#:vecref n) val) (pylist-set! v n val)) + ((_ v (#:array-ref n ...) val) + (pylist-set! v (list n ...) val)) ((_ v (#:vecsub x ...) val) (pylist-subset! v x ... val)))) diff --git a/modules/language/python/dict.scm b/modules/language/python/dict.scm index f32b134..4c94f2e 100644 --- a/modules/language/python/dict.scm +++ b/modules/language/python/dict.scm @@ -604,7 +604,20 @@ (if (pair? k) (pylist-set! self (car k) (cdr k)) (raise TypeError - "wrong type of argument to dict" k))))))))) + "wrong type of argument to dict" k)))))) + ((self . l) + (__init__ + self + (let lp ((l l)) + (match l + ((x y . l) + (cons (cons (symbol->string + (keyword->symbol x)) + y) (lp l))) + (() '()) + (_ (raise + (ValueError + "init argument to dict malformed expected key value list")))))))))) __init__))) diff --git a/modules/language/python/module/filecmp.py b/modules/language/python/module/filecmp.py new file mode 100644 index 0000000..57f9851 --- /dev/null +++ b/modules/language/python/module/filecmp.py @@ -0,0 +1,304 @@ +module(filecmp) + +"""Utilities for comparing files and directories. + +Classes: + dircmp + +Functions: + cmp(f1, f2, shallow=True) -> int + cmpfiles(a, b, common) -> ([], [], []) + clear_cache() + +""" + +import os +import stat +from itertools import filterfalse + +__all__ = ['clear_cache', 'cmp', 'dircmp', 'cmpfiles', 'DEFAULT_IGNORES'] + +_cache = {} +BUFSIZE = 8*1024 + +DEFAULT_IGNORES = [ + 'RCS', 'CVS', 'tags', '.git', '.hg', '.bzr', '_darcs', '__pycache__'] + +def clear_cache(): + """Clear the filecmp cache.""" + _cache.clear() + +def cmp(f1, f2, shallow=True): + """Compare two files. + + Arguments: + + f1 -- First file name + + f2 -- Second file name + + shallow -- Just check stat signature (do not read the files). + defaults to True. + + Return value: + + True if the files are the same, False otherwise. + + This function uses a cache for past comparisons and the results, + with cache entries invalidated if their stat information + changes. The cache may be cleared by calling clear_cache(). + + """ + + s1 = _sig(os.stat(f1)) + s2 = _sig(os.stat(f2)) + if s1[0] != stat.S_IFREG or s2[0] != stat.S_IFREG: + return False + if shallow and s1 == s2: + return True + if s1[1] != s2[1]: + return False + + outcome = _cache.get((f1, f2, s1, s2)) + if outcome is None: + outcome = _do_cmp(f1, f2) + if len(_cache) > 100: # limit the maximum size of the cache + clear_cache() + _cache[f1, f2, s1, s2] = outcome + return outcome + +def _sig(st): + return (stat.S_IFMT(st.st_mode), + st.st_size, + st.st_mtime) + +def _do_cmp(f1, f2): + bufsize = BUFSIZE + with open(f1, 'rb') as fp1, open(f2, 'rb') as fp2: + while True: + b1 = fp1.read(bufsize) + b2 = fp2.read(bufsize) + if b1 != b2: + return False + if not b1: + return True + +# Directory comparison class. +# +class dircmp: + """A class that manages the comparison of 2 directories. + + dircmp(a, b, ignore=None, hide=None) + A and B are directories. + IGNORE is a list of names to ignore, + defaults to DEFAULT_IGNORES. + HIDE is a list of names to hide, + defaults to [os.curdir, os.pardir]. + + High level usage: + x = dircmp(dir1, dir2) + x.report() -> prints a report on the differences between dir1 and dir2 + or + x.report_partial_closure() -> prints report on differences between dir1 + and dir2, and reports on common immediate subdirectories. + x.report_full_closure() -> like report_partial_closure, + but fully recursive. + + Attributes: + left_list, right_list: The files in dir1 and dir2, + filtered by hide and ignore. + common: a list of names in both dir1 and dir2. + left_only, right_only: names only in dir1, dir2. + common_dirs: subdirectories in both dir1 and dir2. + common_files: files in both dir1 and dir2. + common_funny: names in both dir1 and dir2 where the type differs between + dir1 and dir2, or the name is not stat-able. + same_files: list of identical files. + diff_files: list of filenames which differ. + funny_files: list of files which could not be compared. + subdirs: a dictionary of dircmp objects, keyed by names in common_dirs. + """ + + def __init__(self, a, b, ignore=None, hide=None): # Initialize + self.left = a + self.right = b + if hide is None: + self.hide = [os.curdir, os.pardir] # Names never to be shown + else: + self.hide = hide + if ignore is None: + self.ignore = DEFAULT_IGNORES + else: + self.ignore = ignore + + def phase0(self): # Compare everything except common subdirectories + self.left_list = _filter(os.listdir(self.left), + self.hide+self.ignore) + self.right_list = _filter(os.listdir(self.right), + self.hide+self.ignore) + self.left_list.sort() + self.right_list.sort() + + def phase1(self): # Compute common names + a = dict(zip(map(os.path.normcase, self.left_list), self.left_list)) + b = dict(zip(map(os.path.normcase, self.right_list), self.right_list)) + self.common = list(map(a.__getitem__, filter(b.__contains__, a))) + self.left_only = list(map(a.__getitem__, filterfalse(b.__contains__, a))) + self.right_only = list(map(b.__getitem__, filterfalse(a.__contains__, b))) + + def phase2(self): # Distinguish files, directories, funnies + self.common_dirs = [] + self.common_files = [] + self.common_funny = [] + + for x in self.common: + a_path = os.path.join(self.left, x) + b_path = os.path.join(self.right, x) + + ok = 1 + try: + a_stat = os.stat(a_path) + except OSError as why: + # print('Can\'t stat', a_path, ':', why.args[1]) + ok = 0 + try: + b_stat = os.stat(b_path) + except OSError as why: + # print('Can\'t stat', b_path, ':', why.args[1]) + ok = 0 + + if ok: + a_type = stat.S_IFMT(a_stat.st_mode) + b_type = stat.S_IFMT(b_stat.st_mode) + if a_type != b_type: + self.common_funny.append(x) + elif stat.S_ISDIR(a_type): + self.common_dirs.append(x) + elif stat.S_ISREG(a_type): + self.common_files.append(x) + else: + self.common_funny.append(x) + else: + self.common_funny.append(x) + + def phase3(self): # Find out differences between common files + xx = cmpfiles(self.left, self.right, self.common_files) + self.same_files, self.diff_files, self.funny_files = xx + + def phase4(self): # Find out differences between common subdirectories + # A new dircmp object is created for each common subdirectory, + # these are stored in a dictionary indexed by filename. + # The hide and ignore properties are inherited from the parent + self.subdirs = {} + for x in self.common_dirs: + a_x = os.path.join(self.left, x) + b_x = os.path.join(self.right, x) + self.subdirs[x] = dircmp(a_x, b_x, self.ignore, self.hide) + + def phase4_closure(self): # Recursively call phase4() on subdirectories + self.phase4() + for sd in self.subdirs.values(): + sd.phase4_closure() + + def report(self): # Print a report on the differences between a and b + # Output format is purposely lousy + print('diff', self.left, self.right) + if self.left_only: + self.left_only.sort() + print('Only in', self.left, ':', self.left_only) + if self.right_only: + self.right_only.sort() + print('Only in', self.right, ':', self.right_only) + if self.same_files: + self.same_files.sort() + print('Identical files :', self.same_files) + if self.diff_files: + self.diff_files.sort() + print('Differing files :', self.diff_files) + if self.funny_files: + self.funny_files.sort() + print('Trouble with common files :', self.funny_files) + if self.common_dirs: + self.common_dirs.sort() + print('Common subdirectories :', self.common_dirs) + if self.common_funny: + self.common_funny.sort() + print('Common funny cases :', self.common_funny) + + def report_partial_closure(self): # Print reports on self and on subdirs + self.report() + for sd in self.subdirs.values(): + print() + sd.report() + + def report_full_closure(self): # Report on self and subdirs recursively + self.report() + for sd in self.subdirs.values(): + print() + sd.report_full_closure() + + methodmap = dict(subdirs=phase4, + same_files=phase3, diff_files=phase3, funny_files=phase3, + common_dirs = phase2, common_files=phase2, common_funny=phase2, + common=phase1, left_only=phase1, right_only=phase1, + left_list=phase0, right_list=phase0) + + def __getattr__(self, attr): + if attr not in self.methodmap: + raise AttributeError(attr) + self.methodmap[attr](self) + return getattr(self, attr) + +def cmpfiles(a, b, common, shallow=True): + """Compare common files in two directories. + + a, b -- directory names + common -- list of file names found in both directories + shallow -- if true, do comparison based solely on stat() information + + Returns a tuple of three lists: + files that compare equal + files that are different + filenames that aren't regular files. + + """ + res = ([], [], []) + for x in common: + ax = os.path.join(a, x) + bx = os.path.join(b, x) + res[_cmp(ax, bx, shallow)].append(x) + return res + + +# Compare two files. +# Return: +# 0 for equal +# 1 for different +# 2 for funny cases (can't stat, etc.) +# +def _cmp(a, b, sh, abs=abs, cmp=cmp): + try: + return not abs(cmp(a, b, sh)) + except OSError: + return 2 + + +# Return a copy with items that occur in skip removed. +# +def _filter(flist, skip): + return list(filterfalse(skip.__contains__, flist)) + + +# Demonstration and testing. +# +def demo(): + import sys + import getopt + options, args = getopt.getopt(sys.argv[1:], 'r') + if len(args) != 2: + raise getopt.GetoptError('need exactly two args', None) + dd = dircmp(args[0], args[1]) + if ('-r', '') in options: + dd.report_full_closure() + else: + dd.report() diff --git a/modules/language/python/module/getopt.py b/modules/language/python/module/getopt.py new file mode 100644 index 0000000..4474234 --- /dev/null +++ b/modules/language/python/module/getopt.py @@ -0,0 +1,213 @@ +module(getopt) + +"""Parser for command line options. + +This module helps scripts to parse the command line arguments in +sys.argv. It supports the same conventions as the Unix getopt() +function (including the special meanings of arguments of the form `-' +and `--'). Long options similar to those supported by GNU software +may be used as well via an optional third argument. This module +provides two functions and an exception: + +getopt() -- Parse command line options +gnu_getopt() -- Like getopt(), but allow option and non-option arguments +to be intermixed. +GetoptError -- exception (class) raised with 'opt' attribute, which is the +option involved with the exception. +""" + +# Long option support added by Lars Wirzenius <liw@iki.fi>. +# +# Gerrit Holl <gerrit@nl.linux.org> moved the string-based exceptions +# to class-based exceptions. +# +# Peter Åstrand <astrand@lysator.liu.se> added gnu_getopt(). +# +# TODO for gnu_getopt(): +# +# - GNU getopt_long_only mechanism +# - allow the caller to specify ordering +# - RETURN_IN_ORDER option +# - GNU extension with '-' as first character of option string +# - optional arguments, specified by double colons +# - an option string with a W followed by semicolon should +# treat "-W foo" as "--foo" + +__all__ = ["GetoptError","error","getopt","gnu_getopt"] + +import os +try: + from gettext import gettext as _ +except ImportError: + # Bootstrapping Python: gettext's dependencies not built yet + def _(s): return s + +class GetoptError(Exception): + opt = '' + msg = '' + def __init__(self, msg, opt=''): + self.msg = msg + self.opt = opt + Exception.__init__(self, msg, opt) + + def __str__(self): + return self.msg + +error = GetoptError # backward compatibility + +def getopt(args, shortopts, longopts = []): + """getopt(args, options[, long_options]) -> opts, args + + Parses command line options and parameter list. args is the + argument list to be parsed, without the leading reference to the + running program. Typically, this means "sys.argv[1:]". shortopts + is the string of option letters that the script wants to + recognize, with options that require an argument followed by a + colon (i.e., the same format that Unix getopt() uses). If + specified, longopts is a list of strings with the names of the + long options which should be supported. The leading '--' + characters should not be included in the option name. Options + which require an argument should be followed by an equal sign + ('='). + + The return value consists of two elements: the first is a list of + (option, value) pairs; the second is the list of program arguments + left after the option list was stripped (this is a trailing slice + of the first argument). Each option-and-value pair returned has + the option as its first element, prefixed with a hyphen (e.g., + '-x'), and the option argument as its second element, or an empty + string if the option has no argument. The options occur in the + list in the same order in which they were found, thus allowing + multiple occurrences. Long and short options may be mixed. + + """ + + opts = [] + if type(longopts) == type(""): + longopts = [longopts] + else: + longopts = list(longopts) + while args and args[0].startswith('-') and args[0] != '-': + if args[0] == '--': + args = args[1:] + break + if args[0].startswith('--'): + opts, args = do_longs(opts, args[0][2:], longopts, args[1:]) + else: + opts, args = do_shorts(opts, args[0][1:], shortopts, args[1:]) + + return opts, args + +def gnu_getopt(args, shortopts, longopts = []): + """getopt(args, options[, long_options]) -> opts, args + + This function works like getopt(), except that GNU style scanning + mode is used by default. This means that option and non-option + arguments may be intermixed. The getopt() function stops + processing options as soon as a non-option argument is + encountered. + + If the first character of the option string is `+', or if the + environment variable POSIXLY_CORRECT is set, then option + processing stops as soon as a non-option argument is encountered. + + """ + + opts = [] + prog_args = [] + if isinstance(longopts, str): + longopts = [longopts] + else: + longopts = list(longopts) + + # Allow options after non-option arguments? + if shortopts.startswith('+'): + shortopts = shortopts[1:] + all_options_first = True + elif os.environ.get("POSIXLY_CORRECT"): + all_options_first = True + else: + all_options_first = False + + while args: + if args[0] == '--': + prog_args += args[1:] + break + + if args[0][:2] == '--': + opts, args = do_longs(opts, args[0][2:], longopts, args[1:]) + elif args[0][:1] == '-' and args[0] != '-': + opts, args = do_shorts(opts, args[0][1:], shortopts, args[1:]) + else: + if all_options_first: + prog_args += args + break + else: + prog_args.append(args[0]) + args = args[1:] + + return opts, prog_args + +def do_longs(opts, opt, longopts, args): + try: + i = opt.index('=') + except ValueError: + optarg = None + else: + opt, optarg = opt[:i], opt[i+1:] + + has_arg, opt = long_has_args(opt, longopts) + if has_arg: + if optarg is None: + if not args: + raise GetoptError(_('option --%s requires argument') % opt, opt) + optarg, args = args[0], args[1:] + elif optarg is not None: + raise GetoptError(_('option --%s must not have an argument') % opt, opt) + opts.append(('--' + opt, optarg or '')) + return opts, args + +# Return: +# has_arg? +# full option name +def long_has_args(opt, longopts): + possibilities = [o for o in longopts if o.startswith(opt)] + if not possibilities: + raise GetoptError(_('option --%s not recognized') % opt, opt) + # Is there an exact match? + if opt in possibilities: + return False, opt + elif opt + '=' in possibilities: + return True, opt + # No exact match, so better be unique. + if len(possibilities) > 1: + # XXX since possibilities contains all valid continuations, might be + # nice to work them into the error msg + raise GetoptError(_('option --%s not a unique prefix') % opt, opt) + assert len(possibilities) == 1 + unique_match = possibilities[0] + has_arg = unique_match.endswith('=') + if has_arg: + unique_match = unique_match[:-1] + return has_arg, unique_match + +def do_shorts(opts, optstring, shortopts, args): + while optstring != '': + opt, optstring = optstring[0], optstring[1:] + if short_has_arg(opt, shortopts): + if optstring == '': + if not args: + raise GetoptError(_('option -%s requires argument') % opt, + opt) + optstring, args = args[0], args[1:] + optarg, optstring = optstring, '' + else: + optarg = '' + opts.append(('-' + opt, optarg)) + return opts, args + +def short_has_arg(opt, shortopts): + for i in range(len(shortopts)): + if opt == shortopts[i] != ':': + return shortopts.startswith(':', i+1) + raise GetoptError(_('option -%s not recognized') % opt, opt) |