107 lines
3.0 KiB
Python
107 lines
3.0 KiB
Python
import os
|
|
from pathlib import Path
|
|
from configparser import ConfigParser
|
|
|
|
GITEA_REPOS = ['boxtools']
|
|
|
|
GITEA_URL = 'https://gitea.psi.ch/linse/%s.git'
|
|
|
|
GET_GITEA_TOKEN = """#!/bin/bash
|
|
if [ -z "$GITEA_TOKEN" ]; then
|
|
echo "" 1>&2
|
|
echo "you try to push without setting GITEA_TOKEN" 1>&2
|
|
echo "please use 'setuser <initials>' to identify yourself" 1>&2
|
|
echo "" 1>&2
|
|
echo quit=1
|
|
else
|
|
if [ "$1" == "get" ]; then
|
|
echo "connecting with gitea token for $GIT_AUTHOR_NAME" 1>&2
|
|
fi
|
|
echo username=_
|
|
echo "password=$GITEA_TOKEN"
|
|
fi
|
|
"""
|
|
|
|
PRE_COMMIT_HOOK = """#!/bin/bash
|
|
if [ "$GIT_AUTHOR_NAME" == "PREVENT_DEFAULT" ]; then
|
|
echo ''
|
|
echo 'You tried to commit without specified author'
|
|
echo "please execute 'setuser <initials>' to identify yourself"
|
|
echo 'or add the author with: git commit --author=<your name>'
|
|
echo ''
|
|
exit 1
|
|
else
|
|
echo "Author: $GIT_AUTHOR_NAME<$GIT_AUTHOR_EMAIL>"
|
|
fi
|
|
"""
|
|
|
|
|
|
def write_when_new(doit, filename, content):
|
|
if content is None:
|
|
lines = []
|
|
else:
|
|
if not content.endswith('\n'):
|
|
content += '\n'
|
|
lines = content.split('\n')
|
|
try:
|
|
with open(filename) as fil:
|
|
old = fil.read()
|
|
except FileNotFoundError:
|
|
old = None
|
|
if old == content:
|
|
return False
|
|
if doit:
|
|
if lines:
|
|
with open(filename, 'w') as fil:
|
|
fil.write(content)
|
|
else:
|
|
os.remove(filename)
|
|
return True
|
|
elif old:
|
|
print(filename, 'needs an update')
|
|
else:
|
|
print(filename, 'is missing')
|
|
|
|
|
|
def change_to_gitea(doit, *repos):
|
|
if not repos:
|
|
repos = GITEA_REPOS
|
|
dirty = False
|
|
cwd = os.getcwd()
|
|
try:
|
|
for repo in repos:
|
|
os.chdir(Path('~').expanduser() / repo)
|
|
try:
|
|
parser = ConfigParser()
|
|
parser.read('.git/config')
|
|
except FileNotFoundError:
|
|
continue
|
|
if write_when_new(doit, '.git/hooks/get_gitea_token', GET_GITEA_TOKEN):
|
|
dirty = True
|
|
if write_when_new(doit, '.git/hooks/pre-commit', PRE_COMMIT_HOOK):
|
|
dirty = True
|
|
helper_script = parser.get('credential', 'helper', fallback=None)
|
|
new_helper = f'{os.getcwd()}/.git/hooks/get_gitea_token'
|
|
if helper_script != new_helper:
|
|
dirty = True
|
|
if doit:
|
|
os.system(f'git config credential.helper "{new_helper}"')
|
|
elif helper_script:
|
|
print('need to change gitea credential helper')
|
|
else:
|
|
print('missing gitea credential helper')
|
|
url = parser.get('remote "origin"', 'url', fallback=None)
|
|
if url != GITEA_URL % repo:
|
|
dirty = True
|
|
if doit:
|
|
os.system(f'git remote set-url origin {GITEA_URL}')
|
|
else:
|
|
print('need to change remote url')
|
|
finally:
|
|
os.chdir(cwd)
|
|
return dirty
|
|
|
|
|
|
if __name__ == '__main__':
|
|
change_to_gitea(False)
|