From: Gilles DAVID Date: Fri, 22 Sep 2017 15:35:17 +0000 (+0200) Subject: Use argparse instead of optparse + avoid keywords as variable names X-Git-Tag: V8_4_0b1~3 X-Git-Url: http://git.salome-platform.org/gitweb/?a=commitdiff_plain;h=9992860094f56dc9aa0183990caba0eb7d1dd930;p=tools%2Fconfiguration.git Use argparse instead of optparse + avoid keywords as variable names --- diff --git a/copyright/insert_copyright b/copyright/insert_copyright index c6117fe..87a44b2 100755 --- a/copyright/insert_copyright +++ b/copyright/insert_copyright @@ -1,7 +1,7 @@ #!/usr/bin/env python -# -*- coding: iso-8859-1 -*- +# -*- coding: utf8 -*- -# Copyright 2016 EDF R&D +# Copyright (C) 2017 CEA/DEN, EDF R&D # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License Version 3 as @@ -21,7 +21,7 @@ Command line tool to insert copyright notice to a file. Usage: type "insert_copyright --help" to learn how to use tool. """ -import optparse +import argparse import os import re import sys @@ -31,18 +31,19 @@ import time # ----------------------------------------------------------------------------- _COMMENTS = { - 'cpp' : '//', - 'shell' : '#', - 'python' : '#', - 'auto' : None, + 'cpp': '//', + 'shell': '#', + 'python': '#', + 'auto': None, } _OWNERS = { - 'cea' : 'CEA/DEN', - 'edf' : 'EDF R&D', - 'occ' : 'OPEN CASCADE' + 'cea': 'CEA/DEN', + 'edf': 'EDF R&D', + 'occ': 'OPEN CASCADE' } + # ----------------------------------------------------------------------------- def error_exit(msg): """ @@ -54,6 +55,7 @@ def error_exit(msg): sys.stderr.write("ERROR: {}\n".format(msg)) sys.exit(-1) + # ----------------------------------------------------------------------------- def warning(msg): """ @@ -64,6 +66,7 @@ def warning(msg): """ sys.stderr.write("WARNING: {}\n".format(msg)) + # ----------------------------------------------------------------------------- def formats(): """ @@ -72,7 +75,8 @@ def formats(): Returns: list[str]: List of formats. """ - return _COMMENTS.keys() + return list(_COMMENTS) + # ----------------------------------------------------------------------------- def search_line(lines, rex, depth=1): @@ -93,6 +97,7 @@ def search_line(lines, rex, depth=1): return i return -1 + # ----------------------------------------------------------------------------- def get_owner(owner): """ @@ -116,8 +121,9 @@ def get_owner(owner): result.append(i) return ', '.join(result) + # ----------------------------------------------------------------------------- -def get_comment(format): +def get_comment(file_format): """ Get comment for given format. @@ -128,7 +134,8 @@ def get_comment(format): str: Comment signature for given format; *None* for unsupported format. """ - return _COMMENTS.get(format) if format else None + return _COMMENTS.get(file_format) if file_format else None + # ----------------------------------------------------------------------------- def get_copyright(comment, owner, year): @@ -144,16 +151,18 @@ def get_copyright(comment, owner, year): list[str]: List of strings with copyright data. """ template = os.path.join(os.path.dirname(sys.argv[0]), 'copyright.template') - copyright = [] + the_copyright = [] try: with open(template) as fid: - copyright = fid.readlines() + the_copyright = fid.readlines() except IOError: error_exit("cannot find copyright template") - copyright = [i.replace('@year@', year) for i in copyright] - copyright = [i.replace('@owner@', owner) for i in copyright] - copyright = [comment + ' ' + i for i in copyright] - return copyright + the_copyright = [i.replace('@year@', year) for i in the_copyright] + the_copyright = [i.replace('@owner@', owner) for i in the_copyright] + the_copyright = [comment + ' ' + i if i.strip() else comment + '\n' + for i in the_copyright] + return the_copyright + # ----------------------------------------------------------------------------- def get_module_owner(module): @@ -178,6 +187,7 @@ def get_module_owner(module): warning("cannot find modules info file") return owner + # ----------------------------------------------------------------------------- def autodetect_owner(filename): """ @@ -211,6 +221,7 @@ def autodetect_owner(filename): directory = os.path.dirname(directory) return None + # ----------------------------------------------------------------------------- def autodetect_format(filename): """ @@ -223,24 +234,25 @@ def autodetect_format(filename): str: Format of comments; *None* if format isn't detected. """ extensions = { - 'cpp' : ('c', 'cpp', 'cxx', 'cc', 'c++', - 'h', 'hxx', 'hpp', 'hh', 'h++', - 'idl', 'i'), - 'shell' : ('sh', 'bash', 'csh', 'cmake', 'txt', 'cfg', 'ini', 'm4'), - 'python' : ('py',), + 'cpp': ('c', 'cpp', 'cxx', 'cc', 'c++', + 'h', 'hxx', 'hpp', 'hh', 'h++', + 'idl', 'i'), + 'shell': ('sh', 'bash', 'csh', 'cmake', 'txt', 'cfg', 'ini', 'm4'), + 'python': ('py',), } if filename and os.path.isfile(filename): extension = os.path.splitext(filename)[1][1:].lower() if extension in ('in',): name = os.path.splitext(filename)[0] extension = os.path.splitext(name)[1][1:].lower() - for format in extensions: - if extension in extensions[format]: + for file_format in extensions: + if extension in extensions[file_format]: return format return None + # ----------------------------------------------------------------------------- -def insert_copyright(filename, owner, year, format): +def insert_copyright(filename, owner, year, file_format): """ Insert copyright note to a file. @@ -248,7 +260,7 @@ def insert_copyright(filename, owner, year, format): filename (str): File path. owner (str): Copyright owner. year (str): Copyright year(s). - format (str): Format of comments. + file_format (str): Format of comments. """ try: with open(filename) as fid: @@ -257,28 +269,28 @@ def insert_copyright(filename, owner, year, format): warning("cannot read file: {}".format(filename)) return - if format in ('auto',): - format = autodetect_format(filename) + if file_format in ('auto',): + file_format = autodetect_format(filename) if owner.lower() in ('auto',): owner = autodetect_owner(filename) or get_owner('all') else: owner = get_owner(owner) - comment = get_comment(format) + comment = get_comment(file_format) if comment is None: warning("cannot detect format") return shell_row = search_line(lines, r'^#!') \ - if format in ('sh', 'bash', 'csh', 'py', 'python') else -1 - coding_row = search_line(lines, r'-\*- coding:', 3) \ - if format in ('py', 'python') else -1 - insert_point = max(0, shell_row+1, coding_row+1) - - copyright = get_copyright(comment, owner, year) - if copyright: - lines = lines[:insert_point] + copyright + ['\n'] \ + if file_format in ('sh', 'bash', 'csh', 'py', 'python') else -1 + coding_row = search_line(lines, r'coding:', 3) \ + if file_format in ('py', 'python') else -1 + insert_point = max(0, shell_row + 1, coding_row + 1) + + the_copyright = get_copyright(comment, owner, year) + if the_copyright: + lines = lines[:insert_point] + the_copyright + ['\n'] \ + lines[insert_point:] try: with open(filename, 'w') as fid: @@ -288,46 +300,47 @@ def insert_copyright(filename, owner, year, format): warning("cannot write file: {}".format(filename)) return + # ----------------------------------------------------------------------------- def main(): """Main function.""" # Parse command line. - usage = "%prog [options] [FILE] ..." description = "Command line tool to insert copyright notice to a file." - parser = optparse.OptionParser(usage=usage, description=description) + parser = argparse.ArgumentParser(description=description) help_string = "copyright owner; if not specified, tool tries to " \ "autodetect an owner from the file path; if auto-detection fails, " \ "an owner is set to '{owner}'" owner = 'auto' - parser.add_option("-o", "--owner", action="store", - dest="owner", default=owner, - help=help_string.format(owner=get_owner('all'))) + parser.add_argument("-o", "--owner", action="store", + dest="owner", default=owner, + help=help_string.format(owner=get_owner('all'))) help_string = "copyright year(s); default: current year ({year})" year = str(time.localtime().tm_year) - parser.add_option("-y", "--year", action="store", - dest="year", default=year, - help=help_string.format(year=year)) - help_string = "format of comments ({choices}); default: {format}" - format = 'auto' - parser.add_option("-f", "--format", action="store", - type='choice', choices=formats(), - dest="format", default=format, - help=help_string.format(format=format, - choices="|".join(formats()))) - - options, files = parser.parse_args(sys.argv[1:]) - - owner = options.owner - year = options.year - format = options.format + parser.add_argument("-y", "--year", action="store", + dest="year", default=year, + help=help_string.format(year=year)) + help_string = "format of comments ({choices}); default: {file_format}" + file_format = 'auto' + parser.add_argument("-f", "--format", action="store", choices=formats(), + dest="format", default=file_format, + help=help_string.format(file_format=file_format, + choices="|".join(formats()))) + parser.add_argument('files', nargs='*') + + args = parser.parse_args(sys.argv[1:]) + + owner = args.owner + year = args.year + file_format = args.format + files = args.files if not files: error_exit('file is not specified') for filename in files: - insert_copyright(filename, owner, year, format) + insert_copyright(filename, owner, year, file_format) return 0