Skip to content

Commit

Permalink
Documentation: Return a non-zero exit code for modified header
Browse files Browse the repository at this point in the history
If a header in a python file is modified, the `tools/add_header` script with the
`--check` argument will now return a non-zero exit code. This means that
`tools/add_header` can be used as a pre-commit check or inside the CI/CD.
  • Loading branch information
joeldierkes committed Oct 12, 2021
1 parent 7e3866b commit 84d738a
Showing 1 changed file with 16 additions and 10 deletions.
26 changes: 16 additions & 10 deletions tools/add_header
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@
# - Mario Lassnig <mario.lassnig@cern.ch>, 2021
# - Radu Carpa <radu.carpa@cern.ch>, 2021
# - David Población Criado <david.poblacion.criado@cern.ch>, 2021
# - Joel Dierkes <joel.dierkes@cern.ch>, 2021

"""
Utility script to generate header file
Expand Down Expand Up @@ -92,6 +93,7 @@ def main(arguments):
status, email = commands.getstatusoutput(cmd)
email = email.strip()
email = '<%s>' % email
exit_code = 0

for MyFile in arguments.MyFiles:
# Query log history
Expand Down Expand Up @@ -207,20 +209,21 @@ def main(arguments):
else:
header += '# - %(name)s %(mail)s, %(min)s-%(max)s\n' % authors[author]

try:
with open(MyFile, 'r') as original:
lines = original.readlines()
except UnicodeDecodeError as e:
raise RuntimeError('Cannot read file ' + str(MyFile)) from e

if arguments.check and header not in "".join(lines):
print("Header was modified in file", MyFile, file=sys.stderr)
exit_code = 1

if not arguments.dry_run:
if not arguments.in_place:
with open(MyFile, 'r') as original:
data = original.read()

with open(MyFile, 'w') as modified:
modified.write(header + '\n' + data)
modified.write(header + '\n' + "".join(lines))
else:
try:
with open(MyFile, 'r') as original:
lines = original.readlines()
except UnicodeDecodeError as e:
raise RuntimeError('Cannot read file ' + str(MyFile)) from e

with open(MyFile, 'w') as modified:
if not lines:
print('Empty lines at file', MyFile, file=sys.stderr)
Expand All @@ -243,6 +246,7 @@ def main(arguments):

else:
print(header)
exit(exit_code)


if __name__ == '__main__':
Expand All @@ -252,6 +256,8 @@ if __name__ == '__main__':
parser.add_argument('--in-place', '-i', action='store_true', default=False,
help='Edit files in-place (otherwise prepend).')
parser.add_argument('--dry-run', '-d', action='store_true', help='Dry run mode')
parser.add_arguemnt('--check', '-c', action='store_true',
help='Checks if the script would change anything (non-zero exit code equals change).')
parser.add_argument(dest='MyFiles', action='store', nargs='+', default=None, help='The files')

main(parser.parse_args())

0 comments on commit 84d738a

Please sign in to comment.