Browse Source

Reworked pre-commit hook

- Fix cwd assumptions, pre-commit always starts at the repo base
- Fix subprocess calls for python3
- Extract repository info from 'git config'
- Refactored into separate functions and __main__ part
- Use fileinput module to modify README
rfm69
Maxim Prokhorov 6 years ago
parent
commit
180ff97916
1 changed files with 110 additions and 61 deletions
  1. +110
    -61
      pre-commit

+ 110
- 61
pre-commit View File

@ -13,68 +13,117 @@ Travis badge with the current branch. Based on [4].
Copy this file to .git/hooks/
"""
from __future__ import print_function
import os
import sys
import re
import subprocess
BASE = os.path.dirname(os.path.realpath(__file__)) + "/../../"
README = BASE + "README.md"
remote = subprocess.check_output(["git", "remote", "-v"]).strip().split('\n')[0]
parts = re.split('[/\.: ]', remote)
REPO = parts[ len(parts) - 3]
USER = parts[ len(parts) - 4]
BRANCH = subprocess.check_output(["git", "rev-parse", "--abbrev-ref", "HEAD"]).strip()
def getVersion():
file_name = BASE + "code/espurna/config/version.h"
lines = open(file_name).readlines()
for line in lines:
if "APP_VERSION" in line:
parts = line.split('"')
return parts[1]
return "unknown"
VERSION = getVersion()
version = "[![version](https://img.shields.io/badge/version-{VERSION}-brightgreen.svg)](CHANGELOG.md)\n".format(
VERSION = VERSION
)
branch = "[![branch](https://img.shields.io/badge/branch-{BRANCH}-orange.svg)] "
"(https://github.com/{USER}/{REPO}/tree/{BRANCH}/)\n".format(
USER = USER,
REPO = REPO,
BRANCH = BRANCH
)
travis = "[![travis](https://travis-ci.org/{USER}/{REPO}.svg?branch={BRANCH})]" \
"(https://travis-ci.org/{USER}/{REPO})\n".format(
USER = USER,
REPO = REPO,
BRANCH = BRANCH
)
codacy = "[![codacy](https://img.shields.io/codacy/grade/{HASH}/{BRANCH}.svg)]" \
"(https://www.codacy.com/app/{USER}/{REPO}/dashboard)\n".format(
HASH = "c9496e25cf07434cba786b462cb15f49",
USER = USER,
REPO = REPO,
BRANCH = BRANCH
)
lines = open(README).readlines()
with open(README, "w") as fh:
for line in lines:
if "![travis]" in line:
fh.write(travis)
elif "![version]" in line:
fh.write(version)
elif "![branch]" in line:
fh.write(branch)
elif "![codacy]" in line:
fh.write(codacy)
else:
fh.write(line)
subprocess.check_output(["git", "add", README ])
from subprocess import call, check_output
try:
from urllib.parse import urlparse
except ImportError:
from urlparse import urlparse
from fileinput import FileInput
# https://github.com/python/cpython/commit/6cb7b659#diff-78790b53ff259619377058acd4f74672
if sys.version_info[0] < 3:
class FileInputCtx(FileInput):
def __enter__(self):
return self
def __exit__(self, type, value, traceback):
self.close()
FileInput = FileInputCtx
def run(cmd, cwd=None):
out = check_output(cmd, cwd=cwd)
out = out.decode("latin1").strip()
return out
def parse_h_string(define, r_quotes=re.compile("\"(.*)\"")):
string = r_quotes.search(define).group(1)
return string
def git_parse_remote(cwd=None, remote="origin"):
remote_url = run([
"git", "config", "--local",
"--get", "remote.{}.url".format(remote)], cwd)
if remote_url.startswith("git"):
_, _, repo = remote_url.partition(":")
path = repo.replace(".git", "")
elif remote_url.startswith("https"):
parsed = urlparse(remote_url)
path = parsed.path[1:]
return path.split("/")
def git_branch(cwd=None):
return run(["git", "rev-parse", "--abbrev-ref", "HEAD"], cwd)
def espurna_get_version(base, version_h="code/espurna/config/version.h"):
version = "unknown"
path = os.path.join(base, version_h)
with open(path, "r") as version_f:
for line in version_f:
if line.startswith("#define") and "APP_VERSION" in line:
version = parse_h_string(line)
break
return version
SHIELD_TRAVIS = "[![travis](https://travis-ci.org/{USER}/{REPO}.svg?branch={BRANCH})]" \
"(https://travis-ci.org/{USER}/{REPO})"
SHIELD_VERSION = "[![version](https://img.shields.io/badge/version-{VERSION}-brightgreen.svg)](CHANGELOG.md)"
SHIELD_BRANCH = "[![branch](https://img.shields.io/badge/branch-{BRANCH}-orange.svg)]" \
"(https://github.org/{USER}/{REPO}/tree/{BRANCH}/)"
SHIELD_CODACY = "[![codacy](https://img.shields.io/codacy/grade/c9496e25cf07434cba786b462cb15f49/{BRANCH}.svg)]" \
"(https://www.codacy.com/app/{USER}/{REPO}/dashboard)"
README = "README.md"
if __name__ == "__main__":
base = os.getcwd()
user, repo = git_parse_remote()
template = {
"USER": user,
"REPO": repo,
"BRANCH": git_branch(),
"VERSION": espurna_get_version(base)
}
shield_travis = SHIELD_TRAVIS.format(**template)
shield_version = SHIELD_VERSION.format(**template)
shield_branch = SHIELD_BRANCH.format(**template)
shield_codacy = SHIELD_CODACY.format(**template)
path = os.path.join(base, README)
with FileInput(path, inplace=True) as readme:
for line in readme:
if "![travis]" in line:
print(shield_travis)
elif "![version]" in line:
print(shield_version)
elif "![branch]" in line:
print(shield_branch)
elif "![codacy]" in line:
print(shield_codacy)
else:
print(line, end="")
sys.exit(call(["git", "add", README], cwd=base))

Loading…
Cancel
Save