public inbox for gcc-cvs@sourceware.org
help / color / mirror / Atom feed
* [gcc/devel/modula-2] Python3 scripts in gcc/m2/tools-src flake8 compliant and use argparse.
@ 2022-11-02 21:47 Gaius Mulley
0 siblings, 0 replies; only message in thread
From: Gaius Mulley @ 2022-11-02 21:47 UTC (permalink / raw)
To: gcc-cvs
https://gcc.gnu.org/g:494609a74926b2a9af933d14ade31a81dd35ef17
commit 494609a74926b2a9af933d14ade31a81dd35ef17
Author: Gaius Mulley <gaiusmod2@gmail.com>
Date: Wed Nov 2 21:46:09 2022 +0000
Python3 scripts in gcc/m2/tools-src flake8 compliant and use argparse.
tidydates.py and boilerplate.py have been changed to use argparse.
All python3 scripts are flake8 compliant.
gcc/m2/ChangeLog:
* tools-src/boilerplate.py: Rewritten.
* tools-src/tidydates.py: Rewritten.
Signed-off-by: Gaius Mulley <gaiusmod2@gmail.com>
Diff:
---
gcc/m2/tools-src/boilerplate.py | 671 +++++++++++++++++++---------------------
gcc/m2/tools-src/tidydates.py | 161 +++++-----
2 files changed, 386 insertions(+), 446 deletions(-)
diff --git a/gcc/m2/tools-src/boilerplate.py b/gcc/m2/tools-src/boilerplate.py
index 03fa210f6fe..5f5f1f6eaf5 100644
--- a/gcc/m2/tools-src/boilerplate.py
+++ b/gcc/m2/tools-src/boilerplate.py
@@ -1,179 +1,179 @@
#!/usr/bin/env python3
-#
+#
# boilerplate.py utility to rewrite the boilerplate with new dates.
-#
+#
# Copyright (C) 2018-2022 Free Software Foundation, Inc.
# Contributed by Gaius Mulley <gaius@glam.ac.uk>.
-#
+#
# This file is part of GNU Modula-2.
-#
+#
# GNU Modula-2 is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3, or (at your option)
# any later version.
-#
+#
# GNU Modula-2 is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# General Public License for more details.
-#
+#
# You should have received a copy of the GNU General Public License
# along with GNU Modula-2; see the file COPYING3. If not see
# <http://www.gnu.org/licenses/>.
#
-import sys
-import os
-import glob
-import sys, getopt, string
+
+import argparse
import datetime
+import os
+import sys
-forceGPL3x, forceGPL3 = False, False
-doModify, verbose = True, False,
-multiFilemode, updateAll, forceCheck = False, False, False
-summaryGiven, contributedBy, outputName = "", "", "-"
errorCount = 0
-startDir = "."
seenFiles = []
+outputName = None
+ISO_COPYRIGHT = "Copyright ISO/IEC"
+COPYRIGHT = "Copyright (C)"
+GNU_PUBLIC_LICENSE = "GNU General Public License"
+GNU_LESSER_GENERAL = "GNU Lesser General"
+GCC_RUNTIME_LIB_EXC = "GCC Runtime Library Exception"
+VERSION_2_1 = "version 2.1"
+VERSION_2 = "version 2"
+VERSION_3 = "version 3"
+Licenses = {VERSION_2_1: "v2.1", VERSION_2: "v2", VERSION_3: "v3"}
+CONTRIBUTED_BY = "ontributed by"
-#
-# printf - keeps C programmers happy :-)
-#
-def printf (fmt, *args):
- print(str (fmt) % args, end=' ')
+def printf(fmt, *args):
+ # printf - keeps C programmers happy :-)
+ print(str(fmt) % args, end=' ')
-#
-# error - issue an error message.
-#
-def error (fmt, *args):
+def error(fmt, *args):
+ # error - issue an error message.
global errorCount
- print(str (fmt) % args, end=' ')
+ print(str(fmt) % args, end=' ')
errorCount += 1
-def haltOnError ():
+def haltOnError():
if errorCount > 0:
- os.sys.exit (1)
+ os.sys.exit(1)
-def basename (f):
- b = f.split ("/")
+def basename(f):
+ b = f.split("/")
return b[-1]
-#
-# analyseComment -
-#
-
-def analyseComment (text, f):
- start_date, end_date, contribution, summary, lic = None, None, None, None, None
- if text.find ("Copyright ISO/IEC") > 0:
+def analyseComment(text, f):
+ # analyseComment determine the license from the top comment.
+ start_date, end_date = None, None
+ contribution, summary, lic = None, None, None
+ if text.find(ISO_COPYRIGHT) > 0:
lic = "BSISO"
- now = datetime.datetime.now ()
- for d in range (1984, now.year+1):
- if text.find (str (d)) > 0:
- if start_date == None:
- start_date = str (d)
- end_date = str (d)
+ now = datetime.datetime.now()
+ for d in range(1984, now.year+1):
+ if text.find(str(d)) > 0:
+ if start_date is None:
+ start_date = str(d)
+ end_date = str(d)
return start_date, end_date, "", "", lic
- elif text.find ("Copyright (C)") > 0:
- if text.find ("GNU General Public License") > 0:
+ elif text.find(COPYRIGHT) > 0:
+ if text.find(GNU_PUBLIC_LICENSE) > 0:
lic = "GPL"
- elif text.find ("GNU Lesser General") > 0:
+ elif text.find(GNU_LESSER_GENERAL) > 0:
lic = "LGPL"
- if text.find ("version 2.1") > 0:
- lic += "v2.1"
- elif text.find ("version 2") > 0:
- lic += "v2"
- elif text.find ("version 3") > 0:
- lic += "v3"
- if text.find ("GCC Runtime Library Exception") > 0:
+ for license in Licenses.keys():
+ if text.find(license) > 0:
+ lic += Licenses[license]
+ if text.find(GCC_RUNTIME_LIB_EXC) > 0:
lic += "x"
- now = datetime.datetime.now ()
- for d in range (1984, now.year+1):
- if text.find (str (d)) > 0:
- if start_date == None:
- start_date = str (d)
- end_date = str (d)
- if text.find ("ontributed by") > 0:
- i = text.find ("ontributed by")
- i += len ("ontributed by")
- j = text.index (". ", i)
+ now = datetime.datetime.now()
+ for d in range(1984, now.year+1):
+ if text.find(str(d)) > 0:
+ if start_date is None:
+ start_date = str(d)
+ end_date = str(d)
+ if text.find(CONTRIBUTED_BY) > 0:
+ i = text.find(CONTRIBUTED_BY)
+ i += len(CONTRIBUTED_BY)
+ j = text.index(". ", i)
contribution = text[i:j]
- if text.find (basename (f)) > 0:
- i = text.find (basename (f))
- j = text.find (". ", i)
+ if text.find(basename(f)) > 0:
+ i = text.find(basename(f))
+ j = text.find(". ", i)
if j < 0:
- error ('summary of the file does not finish with a "."')
+ error('summary of the file does not finish with a "."')
summary = text[i:]
else:
summary = text[i:j]
return start_date, end_date, contribution, summary, lic
-#
-# analyseHeader -
-#
+def analyseHeaderWithoutTerminator(f, start):
+ text = ""
+ for count, l in enumerate(open(f).readlines()):
+ parts = l.split(start)
+ if len(parts) > 1:
+ line = start.join(parts[1:])
+ line = line.strip()
+ text += " "
+ text += line
+ elif (l.rstrip() != "") and (len(parts[0]) > 0):
+ return analyseComment(text, f), count
+ return [None, None, None, None, None], 0
+
-def analyseHeader (f, start, end):
+def analyseHeaderWithTerminator(f, start, end):
+ inComment = False
text = ""
- if end == None:
- for count, l in enumerate (open (f, "r").readlines ()):
- parts = l.split (start)
- if len (parts) > 1:
- line = start.join (parts[1:])
- line = line.rstrip ()
- line = line.lstrip ()
+ for count, line in enumerate(open(f).readlines()):
+ while line != "":
+ line = line.strip()
+ if inComment:
text += " "
- text += line
- elif (l.rstrip () != "") and (len (parts[0]) > 0):
- return analyseComment (text, f), count
- else:
- inComment = False
- for count, l in enumerate (open (f, "r").readlines ()):
- while l != "":
- l = l.strip ()
- l = l.rstrip ()
- if inComment:
- text += " "
- pos = l.find (end)
- if pos >= 0:
- text += l[:pos]
- l = l[pos:]
- inComment = False
- else:
- text += l
- l = ""
+ pos = line.find(end)
+ if pos >= 0:
+ text += line[:pos]
+ line = line[pos:]
+ inComment = False
+ else:
+ text += line
+ line = ""
+ else:
+ pos = line.find(start)
+ if (pos >= 0) and (len(line) > len(start)):
+ before = line[:pos].strip()
+ if before != "":
+ return analyseComment(text, f), count
+ line = line[pos + len(start):]
+ inComment = True
+ elif (line != "") and (line == end):
+ line = ""
else:
- pos = l.find (start)
- if (pos >= 0) and (len (l) > len (start)):
- before = l[:pos]
- before = before.rstrip ()
- before = before.lstrip ()
- if before != "":
- return analyseComment (text, f), count
- l = l[pos + len (start):]
- inComment = True
- elif (l != "") and (l == end):
- l = ""
- else:
- return analyseComment (text, f), count
+ return analyseComment(text, f), count
return [None, None, None, None, None], 0
+def analyseHeader(f, start, end):
+ # analyseHeader -
+ if end is None:
+ return analyseHeaderWithoutTerminator(f, start)
+ else:
+ return analyseHeaderWithTerminator(f, start, end)
+
+
#
# addStop - add a full stop to a sentance.
#
-def addStop (sentence):
+def addStop(sentence):
if sentence is None:
return None
- sentence = sentence.rstrip ()
- if (len (sentence) > 0) and (sentence[-1] != "."):
+ sentence = sentence.rstrip()
+ if (len(sentence) > 0) and (sentence[-1] != "."):
return sentence + "."
return sentence
@@ -264,336 +264,291 @@ Library module defined by the International Standard
Modula-2, Base Language. BS ISO/IEC 10514-1:1996).
"""
-templates = { "GPLv3":GPLv3,
- "GPLv3x":GPLv3x,
- "LGPLv3":LGPLv3,
- "LGPLv2.1":LGPLv3,
- "BSISO":BSISO }
+templates = {}
+templates["GPLv3"] = GPLv3
+templates["GPLv3x"] = GPLv3x
+templates["LGPLv3"] = LGPLv3
+templates["LGPLv2.1"] = LGPLv3
+templates["BSISO"] = BSISO
-def writeTemplate (fo, magic, start, end, dates, contribution, summary, lic):
+def writeTemplate(fo, magic, start, end, dates, contribution, summary, lic):
if lic in templates:
if lic == "BSISO":
- # non gpl but freely distributed for the implementation of a compiler
+ # non gpl but freely distributed for the implementation of a
+ # compiler
text = templates[lic] % (dates)
- text = text.rstrip ()
+ text = text.rstrip()
else:
- summary = summary.lstrip ()
- contribution = contribution.lstrip ()
- summary = addStop (summary)
- contribution = addStop (contribution)
- if magic != None:
- fo.write (magic)
- fo.write ("\n")
+ summary = summary.lstrip()
+ contribution = contribution.lstrip()
+ summary = addStop(summary)
+ contribution = addStop(contribution)
+ if magic is not None:
+ fo.write(magic)
+ fo.write("\n")
text = templates[lic] % (summary, dates, contribution)
- text = text.rstrip ()
- if end == None:
- text = text.split ("\n")
+ text = text.rstrip()
+ if end is None:
+ text = text.split("\n")
for line in text:
- fo.write (start)
- fo.write (" ")
- fo.write (line)
- fo.write ("\n")
+ fo.write(start)
+ fo.write(" ")
+ fo.write(line)
+ fo.write("\n")
else:
- text = text.lstrip ()
- fo.write (start)
- fo.write (" ")
- fo.write (text)
- fo.write (" ")
- fo.write (end)
- fo.write ("\n")
+ text = text.lstrip()
+ fo.write(start)
+ fo.write(" ")
+ fo.write(text)
+ fo.write(" ")
+ fo.write(end)
+ fo.write("\n")
# add a blank comment line for a script for eye candy.
- if start == "#" and end == None:
- fo.write (start)
- fo.write ("\n")
+ if start == "#" and end is None:
+ fo.write(start)
+ fo.write("\n")
else:
- error ("no template found for: %s\n", lic)
- os.sys.exit (1)
+ error("no template found for: %s\n", lic)
+ os.sys.exit(1)
return fo
-def writeBoilerPlate (fo, magic, start, end, start_date, end_date, contribution, summary, gpl):
+def writeBoilerPlate(fo, magic, start, end,
+ start_date, end_date, contribution, summary, gpl):
if start_date == end_date:
dates = start_date
else:
dates = "%s-%s" % (start_date, end_date)
- return writeTemplate (fo, magic, start, end, dates, contribution, summary, gpl)
+ return writeTemplate(fo, magic, start, end,
+ dates, contribution, summary, gpl)
-def rewriteFile (f, magic, start, end, start_date, end_date, contribution, summary, gpl, lines):
- l = open (f, "r").readlines ()[lines:]
- text = "".join (l)
+def rewriteFile(f, magic, start, end, start_date, end_date,
+ contribution, summary, gpl, lines):
+ text = "".join(open(f).readlines()[lines:])
if outputName == "-":
fo = sys.stdout
else:
- fo = open (f, "w")
- fo = writeBoilerPlate (fo, magic, start, end, start_date, end_date, contribution, summary, gpl)
- fo.write (text)
- fo.flush ()
+ fo = open(f, "w")
+ fo = writeBoilerPlate(fo, magic, start, end,
+ start_date, end_date, contribution, summary, gpl)
+ fo.write(text)
+ fo.flush()
if outputName != "-":
- fo.close ()
+ fo.close()
-#
-# handleHeader - keep reading lines of file, f, looking for start, end
-# sequences and comments inside. The comments are checked
-# for: date, contribution, summary
-#
-
-def handleHeader (f, magic, start, end):
- global date, contribution, summary, doModify, forceCheck, errorCount
+def handleHeader(f, magic, start, end):
+ # handleHeader keep reading lines of file, f, looking for start, end
+ # sequences and comments inside. The comments are checked for:
+ # date, contribution, summary
+ global errorCount
errorCount = 0
- [start_date, end_date, contribution, summary, lic], lines = analyseHeader (f, start, end)
- if lic == None:
- error ("%s:1:no GPL found at the top of the file\n", f)
+ [start_date, end_date,
+ contribution, summary, lic], lines = analyseHeader(f, start, end)
+ if lic is None:
+ error("%s:1:no GPL found at the top of the file\n", f)
else:
- if verbose:
- printf ("copyright: %s\n", lic)
- if (start_date != None) and (end_date != None):
+ if args.verbose:
+ printf("copyright: %s\n", lic)
+ if (start_date is not None) and (end_date is not None):
if start_date == end_date:
- printf ("dates = %s\n", start_date)
+ printf("dates = %s\n", start_date)
else:
- printf ("dates = %s-%s\n", start_date, end_date)
- if summary != None:
- printf ("summary: %s\n", summary)
- if contribution != None:
- printf ("contribution: %s\n", contribution)
- if start_date == None:
- error ("%s:1:no date found in the GPL at the top of the file\n", f)
- if contribution == None:
- if contributedBy == "":
- error ("%s:1:no contribution found in the GPL at the top of the file\n", f)
+ printf("dates = %s-%s\n", start_date, end_date)
+ if summary is not None:
+ printf("summary: %s\n", summary)
+ if contribution is not None:
+ printf("contribution: %s\n", contribution)
+ if start_date is None:
+ error("%s:1:no date found in the GPL at the top of the file\n", f)
+ if args.contribution is None:
+ if contribution == "":
+ error("%s:1:no contribution found in the " +
+ "GPL at the top of the file\n", f)
else:
- contribution = contributedBy
- if summary == None:
- if summaryGiven == "":
- error ("%s:1:no single line summary found in the GPL at the top of the file\n", f)
+ contribution = args.contribution
+ if summary is None:
+ if args.summary == "":
+ error("%s:1:no single line summary found in the " +
+ "GPL at the top of the file\n", f)
else:
- summary = summaryGiven
+ summary = args.summary
if errorCount == 0:
- now = datetime.datetime.now ()
- if doModify:
+ now = datetime.datetime.now()
+ if args.no:
+ print(f, "suppressing change as requested: %s-%s %s"
+ % (start_date, end_date, lic))
+ else:
if lic == "BSISO":
# don't change the BS ISO license!
pass
- elif forceGPL3x:
+ elif args.extensions:
lic = "GPLv3x"
- elif forceGPL3:
+ elif args.gpl3:
lic = "GPLv3"
- rewriteFile (f, magic, start, end, start_date, str (now.year), contribution, summary, lic, lines)
- elif forceCheck:
- print(f, "suppressing change as requested", start_date, end_date, lic)
+ rewriteFile(f, magic, start, end, start_date,
+ str(now.year), contribution, summary, lic, lines)
else:
- printf ("too many errors, no modifications will occur\n")
+ printf("too many errors, no modifications will occur\n")
-#
-# bashTidy - tidy up dates using '#' comment
-#
+def bashTidy(f):
+ # bashTidy tidy up dates using '#' comment
+ handleHeader(f, "#!/bin/bash", "#", None)
-def bashTidy (f):
- handleHeader (f, "#!/bin/bash", "#", None)
+def pythonTidy(f):
+ # pythonTidy tidy up dates using '#' comment
+ handleHeader(f, "#!/usr/bin/env python3", '#', None)
-#
-# pythonTidy - tidy up dates using '#' comment
-#
-def pythonTidy (f):
- handleHeader (f, "#!/usr/bin/env python3", '#', None)
+def bnfTidy(f):
+ # bnfTidy tidy up dates using '--' comment
+ handleHeader(f, None, '--', None)
-#
-# bnfTidy - tidy up dates using '--' comment
-#
-
-def bnfTidy (f):
- handleHeader (f, None, '--', None)
-
-
-#
-# cTidy - tidy up dates using '/* */' comments
-#
+def cTidy(f):
+ # cTidy tidy up dates using '/* */' comments
+ handleHeader(f, None, '/*', '*/')
-def cTidy (f):
- handleHeader (f, None, '/*', '*/')
-#
-# m2Tidy - tidy up dates using '(* *)' comments
-#
+def m2Tidy(f):
+ # m2Tidy tidy up dates using '(* *)' comments
+ handleHeader(f, None, '(*', '*)')
-def m2Tidy (f):
- handleHeader (f, None, '(*', '*)')
-#
-# inTidy - tidy up dates using '#' as a comment and check the first line for magic number.
-#
-
-def inTidy (f):
- first = open (f, "r").readlines ()[0]
- if (len (first) > 0) and (first[:2] == "#!"):
+def inTidy(f):
+ # inTidy tidy up dates using '#' as a comment and check
+ # the first line for magic number.
+ first = open(f).readlines()[0]
+ if (len(first) > 0) and (first[:2] == "#!"):
# magic number found, use this
- handleHeader (f, first, "#", None)
+ handleHeader(f, first, "#", None)
else:
- handleHeader (f, None, "#", None)
+ handleHeader(f, None, "#", None)
-#
-# doVisit -
-#
-
-def doVisit (args, dirname, names):
+def doVisit(args, dirname, names):
+ # doVisit helper function to call func on every extension file.
global outputName
func, extension = args
for f in names:
- if len (f) > len (extension) and f[-len (extension):] == extension:
- # print os.path.join (dirname, f)
+ if len(f) > len(extension) and f[-len(extension):] == extension:
outputName = f
- func (os.path.join (dirname, f))
+ func(os.path.join(dirname, f))
-#
-# visitDir - visit
-#
-
-def visitDir (startDir, extension, func):
+def visitDir(startDir, ext, func):
+ # visitDir call func for each file in startDir which has ext.
global outputName, seenFiles
- # os.walk (startDir, doVisit, [func, extension])
for dirName, subdirList, fileList in os.walk(startDir):
for fname in fileList:
- if (len (fname) > len (extension)) and (fname[-len(extension):] == extension):
- fullpath = os.path.join (dirName, fname)
+ if (len(fname) > len(ext)) and (fname[-len(ext):] == ext):
+ fullpath = os.path.join(dirName, fname)
outputName = fullpath
- # printf ("outputName = %s\n", outputName)
if not (fullpath in seenFiles):
seenFiles += [fullpath]
- func (fullpath)
+ func(fullpath)
# Remove the first entry in the list of sub-directories
# if there are any sub-directories present
if len(subdirList) > 0:
del subdirList[0]
-#
-# findFiles - for each file extension call the appropriate tidy
-# routine.
-#
-
-def findFiles ():
- visitDir (startDir, '.h.in', cTidy)
- visitDir (startDir, '.in', inTidy)
- visitDir (startDir, '.sh', inTidy)
- visitDir (startDir, '.py', pythonTidy)
- visitDir (startDir, '.c', cTidy)
- visitDir (startDir, '.h', cTidy)
- visitDir (startDir, '.cc', cTidy)
- visitDir (startDir, '.def', m2Tidy)
- visitDir (startDir, '.mod', m2Tidy)
- visitDir (startDir, '.bnf', bnfTidy)
-
-
-#
-# usage - output very brief usage instructions.
-#
-def usage (code = 0):
- print("boilerplate [-c contributionstring] [ -s summarystring ] [-d] [-v] [-g] [-x] [-o outputfile] inputfile.c")
- print(" -o outputfile (this must be before the final inputfile on the command line).")
- print(" -c a string which will be used as the contribution line.")
- print(" -s a string which will be used as the summary line.")
- print(" -f force a check to insist that the contribution, summary and GPL exists.")
- print(" -g change to GPLv3.")
- print(" -x change to GPLv3 with GCC runtime extension.")
- print(" -r directory recusively scan directory for known file extensions (.def, .mod, .c, .h, .py, .in, .sh).")
- print(" -u update all dates.")
- print(" -v verbose.")
- print(" -N do not modify any file")
- os.sys.exit (code)
+def findFiles():
+ # findFiles for each file extension call the appropriate tidy routine.
+ visitDir(args.recursive, '.h.in', cTidy)
+ visitDir(args.recursive, '.in', inTidy)
+ visitDir(args.recursive, '.sh', inTidy)
+ visitDir(args.recursive, '.py', pythonTidy)
+ visitDir(args.recursive, '.c', cTidy)
+ visitDir(args.recursive, '.h', cTidy)
+ visitDir(args.recursive, '.cc', cTidy)
+ visitDir(args.recursive, '.def', m2Tidy)
+ visitDir(args.recursive, '.mod', m2Tidy)
+ visitDir(args.recursive, '.bnf', bnfTidy)
#
# handleArguments - check the legal arguments.
#
-def handleArguments ():
- global multiFilemode, contributedBy, updateAll, forceCheck, outputName, verbose, startDir, doModify, forceGPL3, forceGPL3x, summaryGiven
- try:
- optlist, l = getopt.getopt (sys.argv[1:],':c:dfgho:r:s:uvxN')
- except getopt.GetoptError:
- usage (1)
- for opt in optlist:
- if opt[0] == '-c':
- contributedBy = opt[1]
- if opt[0] == '-s':
- summaryGiven = opt[1]
- if opt[0] == '-d':
- debugging = True
- if opt[0] == '-f':
- forceCheck = True
- if opt[0] == '-g':
- forceGPL3 = True
- if opt[0] == '-x':
- forceGPL3x = True
- if opt[0] == '-h':
- usage ()
- if opt[0] == '-r':
- multiFilemode = True
- startDir = opt[1]
- if opt[0] == '-o':
- outputName = opt[1]
- if opt[0] == '-u':
- updateAll = True
- if opt[0] == '-v':
- verbose = True
- if opt[0] == '-N':
- doModify = False
- if l == []:
- return None
- return l[0]
-
-
-#
-# hasExt - return True if, name, ends with, ext.
-#
-
-def hasExt (name, ext):
- if len (name) > len (ext):
- return name[-len (ext):] == ext
+def handleArguments():
+ parser = argparse.ArgumentParser()
+ parser.add_argument("-c", "--contribution",
+ help="set the contribution string " +
+ "at the top of the file.",
+ default="", action="store")
+ parser.add_argument("-d", "--debug", help="turn on internal debugging.",
+ default=False, action="store_true")
+ parser.add_argument("-f", "--force",
+ help="force a check to insist that the " +
+ "contribution, summary and GPL exist.",
+ default=False, action="store_true")
+ parser.add_argument("-g", "--gplv3", help="change to GPLv3",
+ default=False, action="store_true")
+ parser.add_argument("-o", "--outputfile", help="set the output file",
+ default="-", action="store")
+ parser.add_argument("-r", "--recursive",
+ help="recusively scan directory for known file " +
+ "extensions (.def, .mod, .c, .h, .py, .in, .sh).",
+ default=".", action="store")
+ parser.add_argument("-s", "--summary",
+ help="set the summary line for the file.",
+ default=None, action="store")
+ parser.add_argument("-u", "--update", help="update all dates.",
+ default=False, action="store_true")
+ parser.add_argument("-v", "--verbose",
+ help="display copyright, " +
+ "date and contribution messages",
+ action="store_true")
+ parser.add_argument("-x", "--extensions",
+ help="change to GPLv3 with GCC runtime extensions.",
+ default=False, action="store_true")
+ parser.add_argument("-N", "--no",
+ help="do not modify any file.",
+ action="store_true")
+ args = parser.parse_args()
+ return args
+
+
+def hasExt(name, ext):
+ # hasExt return True if, name, ends with, ext.
+ if len(name) > len(ext):
+ return name[-len(ext):] == ext
return False
-#
-# singleFile - scan the single file for a GPL boilerplate which
-# has a GPL, contribution field and a summary heading.
-#
-
-def singleFile (i):
- if hasExt (i, ".def") or hasExt (i, ".mod"):
- m2Tidy (i)
- elif hasExt (i, ".h") or hasExt (i, ".c") or hasExt (i, ".cc"):
- cTidy (i)
- elif hasExt (i, ".in"):
- inTidy (i)
- elif hasExt (i, ".sh"):
- inTidy (i) # uses magic number for actual sh/bash
- elif hasExt (i, ".py"):
- pythonTidy (i)
-
-
-#
-# main - handleArguments and then find source files.
-#
-
-def main ():
- i = handleArguments ()
- if multiFilemode:
- findFiles ()
- elif i == None:
+def singleFile(name):
+ # singleFile scan the single file for a GPL boilerplate which
+ # has a GPL, contribution field and a summary heading.
+ if hasExt(name, ".def") or hasExt(name, ".mod"):
+ m2Tidy(name)
+ elif hasExt(name, ".h") or hasExt(name, ".c") or hasExt(name, ".cc"):
+ cTidy(name)
+ elif hasExt(name, ".in"):
+ inTidy(name)
+ elif hasExt(name, ".sh"):
+ inTidy(name) # uses magic number for actual sh/bash
+ elif hasExt(name, ".py"):
+ pythonTidy(name)
+
+
+def main():
+ # main - handleArguments and then find source files.
+ global args, outputName
+ args = handleArguments()
+ outputName = args.outputfile
+ if args.recursive:
+ findFiles()
+ elif args.inputfile is None:
print("an input file must be specified on the command line")
- usage (1)
else:
- singleFile (i)
- haltOnError ()
+ singleFile(args.inputfile)
+ haltOnError()
-main ()
+main()
diff --git a/gcc/m2/tools-src/tidydates.py b/gcc/m2/tools-src/tidydates.py
index 40c5003062d..916e2073907 100644
--- a/gcc/m2/tools-src/tidydates.py
+++ b/gcc/m2/tools-src/tidydates.py
@@ -21,32 +21,33 @@
# Free Software Foundation, 51 Franklin Street, Fifth Floor, Boston, MA
# 02110-1301, USA.
-import os, sys
+import os
+import sys
+import pathlib
+import shutil
maxLineLength = 60
+COPYRIGHT = "Copyright (C)"
-#
-# visitDir - call func for each file below, dir, matching extension, ext.
-#
-def visitDir (dir, ext, func):
- listOfFiles = os.listdir(dir)
+def visitDir(directory, ext, func):
+ # visitDir - call func for each file below, dir, matching extension, ext.
+ listOfFiles = os.listdir(directory)
listOfFiles.sort()
- for file in listOfFiles:
- if os.path.isfile(os.path.join(dir, file)):
- l = len(ext)
- if (len(file)>l) and (file[-l:] == ext):
- func(os.path.join(dir, file))
- elif os.path.isdir(os.path.join(dir, file)):
- visitDir(os.path.join(dir, file), ext, func)
-
-#
-# isYear - returns True if, year, is legal.
-#
-
-def isYear (year):
- if len(year)==5:
+ for filename in listOfFiles:
+ path = pathlib.PurePath(filename)
+ full = os.path.join(directory, filename)
+ if path.is_file(full):
+ if path.suffix == ext:
+ func(full)
+ elif path.is_dir(full):
+ visitDir(full, ext, func)
+
+
+def isYear(year):
+ # isYear - returns True if, year, is legal.
+ if len(year) == 5:
year = year[:-1]
for c in year:
if not c.isdigit():
@@ -54,14 +55,11 @@ def isYear (year):
return True
-#
-# handleCopyright -
-#
-
-def handleCopyright (outfile, lines, n, leader1, leader2):
+def handleCopyright(outfile, lines, n, leader1, leader2):
+ # handleCopyright look for Copyright in the comment.
global maxLineLength
i = lines[n]
- c = i.find('Copyright (C) ')+len('Copyright (C)')
+ c = i.find(COPYRIGHT)+len(COPYRIGHT)
outfile.write(i[:c])
d = i[c:].split()
start = c
@@ -75,20 +73,20 @@ def handleCopyright (outfile, lines, n, leader1, leader2):
else:
e = d[0]
punctuation = ""
- if len(d)==1:
+ if len(d) == 1:
d = []
else:
d = d[1:]
- if c>maxLineLength:
- outfile.write('\n')
+ if c > maxLineLength:
+ outfile.write("\n")
outfile.write(leader1)
outfile.write(leader2)
- outfile.write(' '*(start-2))
+ outfile.write(" "*(start-2))
c = start
if isYear(e):
- if (e[-1]=='.') or (e[-1]==','):
+ if (e[-1] == ".") or (e[-1] == ","):
punctuation = e[-1]
e = e[:-1]
else:
@@ -98,87 +96,74 @@ def handleCopyright (outfile, lines, n, leader1, leader2):
if seenDate:
if not (e in years):
c += len(e) + len(punctuation)
- outfile.write(' ')
+ outfile.write(" ")
outfile.write(e)
outfile.write(punctuation)
years += [e]
else:
if start < c:
- outfile.write('\n')
+ outfile.write("\n")
outfile.write(leader1)
outfile.write(leader2)
- outfile.write(' '*(start-2))
+ outfile.write(" "*(start-2))
- outfile.write(' ')
+ outfile.write(" ")
outfile.write(e)
outfile.write(punctuation)
for w in d:
- outfile.write(' ')
+ outfile.write(" ")
outfile.write(w)
- outfile.write('\n')
+ outfile.write("\n")
return outfile, n+1
-#
-# handleHeader - reads in the header of a file and inserts
-# a line break around the Copyright dates.
-#
-def handleHeader (file, leader1, leader2):
+def handleHeader(filename, leader1, leader2):
+ # handleHeader reads in the header of a file and inserts
+ # a line break around the Copyright dates.
print("------------------------------")
- l = open(file, 'r').readlines()
- if len(l)>20:
- outfile = open('tmptidy', 'w')
- n = 0
- for i in l:
- if i.find('Copyright (C)')>=0:
- outfile, n = handleCopyright(outfile, l, n, leader1, leader2)
- outfile.writelines(l[n:])
- outfile.close()
- print("-> mv tmptidy", file)
- command = "mv tmptidy %s" % file
- os.system(command)
- return
- else:
- outfile.write(l[n])
- n += 1
- outfile.close()
- sys.stdout.write("%s:1:1 needs a Copyright notice..\n" % file)
+ lines = open(filename, "r").readlines()
+ if len(lines) > 20:
+ with open("tmptidy", "w") as outfile:
+ n = 0
+ for i in lines:
+ if i.find("Copyright (C)") >= 0:
+ outfile, n = handleCopyright(outfile, lines,
+ n, leader1, leader2)
+ outfile.writelines(lines[n:])
+ outfile.close()
+ print("-> mv tmptidy", filename)
+ shutil.move("tmptidy", filename)
+ return
+ else:
+ outfile.write(lines[n])
+ n += 1
+ sys.stdout.write("%s:1:1 needs a Copyright notice..\n" % filename)
-#
-# bashTidy - tidy up dates using '#' comment
-#
+def bashTidy(filename):
+ # bashTidy - tidy up dates using "#" comment
+ handleHeader(filename, "#", " ")
-def bashTidy (file):
- handleHeader(file, '#', ' ')
-#
-# cTidy - tidy up dates using '/* */' comments
-#
+def cTidy(filename):
+ # cTidy - tidy up dates using "/* */" comments
+ handleHeader(filename, " ", "*")
-def cTidy (file):
- handleHeader(file, ' ', '*')
-#
-# m2Tidy - tidy up dates using '(* *)' comments
-#
-
-def m2Tidy (file):
- handleHeader(file, ' ', ' ')
+def m2Tidy(filename):
+ # m2Tidy - tidy up dates using "(* *)" comments
+ handleHeader(filename, " ", " ")
-#
-# main - for each file extension call the appropriate tidy
-# routine.
-#
-def main ():
- visitDir('.', '.in', bashTidy)
- visitDir('.', '.py', bashTidy)
- visitDir('.', '.c', cTidy)
- visitDir('.', '.h', cTidy)
- visitDir('.', '.def', m2Tidy)
- visitDir('.', '.mod', m2Tidy)
+def main():
+ # main - for each file extension call the appropriate tidy routine.
+ visitDir(".", ".in", bashTidy)
+ visitDir(".", ".py", bashTidy)
+ visitDir(".", ".c", cTidy)
+ visitDir(".", ".h", cTidy)
+ visitDir(".", ".def", m2Tidy)
+ visitDir(".", ".mod", m2Tidy)
-main ()
+main()
^ permalink raw reply [flat|nested] only message in thread
only message in thread, other threads:[~2022-11-02 21:47 UTC | newest]
Thread overview: (only message) (download: mbox.gz / follow: Atom feed)
-- links below jump to the message on this page --
2022-11-02 21:47 [gcc/devel/modula-2] Python3 scripts in gcc/m2/tools-src flake8 compliant and use argparse Gaius Mulley
This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox;
as well as URLs for read-only IMAP folder(s) and NNTP newsgroup(s).