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 ' 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 ' to identify yourself" echo 'or add the author with: git commit --author=' 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): 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 if doit: dothis = False try: if parser.get('credential', 'helper') != str(gitdir / hooks / 'get_gitea_token'): dothis = True print('need to change gitea credential helper') except Exception: dothis = True print('missing gitea credential helper') try: if parser.get('remote "origin"', 'url') != GITEA_URL % repo: dothis = True print('need to change remote url') except Exception: dothis = True print('missing remote url') if dothis: dirty = True os.system(f'git config credential.helper "{os.getcwd()}/.git/hooks/get_gitea_token"') os.system(f'git remote set-url origin {GITEA_URL}') finally: os.chdir(cwd) return dirty change_to_gitea(False, *GITEA_REPOS)