template for a before-commit hook script
(1.3) By Kirill M (Kirill) on 2022-01-09 17:18:07 edited from 1.2 [source]
I've successfully deployed a before-commit hook which will check if DNS zone files have syntax errors. I'm sharing the generic part of it, which parses most of the auxiliary info file. I haven't bothered with tags yet. Checkin data are kept in a dict called checkin
, its contents are printed for debugging purposes. Changed files are kept as lists in dict in checkin['status']
, with key being type of the change (e.g. checkin['status']['ADDED']
).
#!/usr/local/bin/python3
import sys
from pathlib import Path
from pprint import pprint
auxfile = Path(sys.argv[1])
print(f'*** Running before-commit hook ({auxfile}) ***')
checkin = {'cwd': Path.cwd(), 'status': {}}
for line in auxfile.read_text().split('\n'):
if 'message' in checkin:
checkin['message'].append(line)
continue
for field in ['checkout', 'repository', 'user', 'branch', 'tags']:
if line.startswith(field):
f, d = line.split(None, 1)
checkin[f] = Path(d) if field in ['checkout', 'repository'] else d
for flag in ['private-branch', 'integrate']:
checkin[flag] = True if line == flag else False
if line == 'checkin-comment':
checkin['message'] = []
continue
if line[0].isupper():
s, f = line.split(None, 1)
if s not in checkin['status']:
checkin['status'][s] = []
checkin['status'][s].append(checkin['checkout'].joinpath(f))
continue
checkin['comment'] = '\n'.join(checkin['message']).strip()
del(checkin['message'])
pprint(checkin)
# do stuff here -- sys.exit(1) if error
sys.exit(0)
Here's how it might be looking when run:
*** Running before-commit hook (/home/km/navn/commit-description-23fb2fb405fea9c7.txt) ***
{'branch': 'trunk',
'checkout': PosixPath('/home/km/navn'),
'comment': 'Catch UPDATED files.',
'cwd': PosixPath('/home/km/navn'),
'integrate': False,
'private-branch': False,
'repository': PosixPath('/home/km/navn.fossil'),
'status': {'EDITED': [PosixPath('/home/km/navn/bin/before-commit')]},
'tags': 'trunk',
'user': 'km'}
New_Version: 933b27eb4a35d2f6b97d84764906f884d6c9a72cfd4b81e63df229154152fe9a
(2) By MBL (RoboManni) on 2022-01-12 15:31:55 in reply to 1.3 [link] [source]
Hello, some time ago I started with similar work and did that with Lua:
print("Time", os.date() )
print( "Program", arg[-1] ) -- first parameter (not counted)
print( "Script", arg[0] ) -- 2nd parameter (not counted, too)
local rc = 0
for n,item in ipairs( arg ) do -- print all counted parameters
print( n, item )
end
if arg[#arg]=="--" then -- check if last parameter indicates 'stdin used'
for line in io.lines() do -- read all lines from stdin
print( line )
end
rc = tonumber(arg[#arg-1]) or 0 -- use last parameter as return value
else
rc = tonumber(arg[#arg]) or 0 -- use last parameter as return value (no stdin usage)
end
local function listFile(id,fname)
if id == "before-commit" then
for line in io.lines(fname) do
print( line )
end
end
end
listFile( arg[1], arg[3] )
print( "return", rc )
return rc