Fork of the espurna firmware for `mhsw` switches
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

150 lines
4.1 KiB

5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
  1. #!/usr/bin/env python
  2. """
  3. Referencing current branch in github README.md [1]
  4. This pre-commit hook [2] updates the README.md file's
  5. Travis badge with the current branch. Based on [4].
  6. [1] http://stackoverflow.com/questions/18673694/referencing-current-branch-in-github-readme-md
  7. [2] http://www.git-scm.com/book/en/v2/Customizing-Git-Git-Hooks
  8. [3] https://docs.travis-ci.com/user/status-images/
  9. [4] https://gist.github.com/dandye/dfe0870a6a1151c89ed9
  10. Copy this file to .git/hooks/
  11. """
  12. import os
  13. import re
  14. import string
  15. import sys
  16. import argparse
  17. from subprocess import call, check_output
  18. try:
  19. from urllib.parse import urlparse
  20. except ImportError:
  21. from urlparse import urlparse
  22. from fileinput import FileInput
  23. # TODO: drop after platform.io supports python 3
  24. # https://github.com/python/cpython/commit/6cb7b659#diff-78790b53ff259619377058acd4f74672
  25. if sys.version_info[0] < 3:
  26. class FileInputCtx(FileInput):
  27. def __enter__(self):
  28. return self
  29. def __exit__(self, type, value, traceback):
  30. self.close()
  31. FileInput = FileInputCtx
  32. class CustomFormatter(string.Formatter):
  33. def format_field(self, value, spec):
  34. if spec == "escape_hyphen":
  35. return value.replace("-", "--")
  36. else:
  37. return super(CustomFormatter, self).format_field(value, spec)
  38. def run(cmd, cwd=None):
  39. out = check_output(cmd, cwd=cwd)
  40. out = out.decode("latin1").strip()
  41. return out
  42. def parse_h_string(define, r_quotes=re.compile("\"(.*)\"")):
  43. string = r_quotes.search(define).group(1)
  44. return string
  45. def git_parse_remote(cwd=None, remote="origin"):
  46. remote_url = run([
  47. "git", "config", "--local",
  48. "--get", "remote.{}.url".format(remote)], cwd)
  49. if remote_url.startswith("git"):
  50. _, _, repo = remote_url.partition(":")
  51. path = repo.replace(".git", "")
  52. elif remote_url.startswith("https"):
  53. parsed = urlparse(remote_url)
  54. path = parsed.path[1:]
  55. return path.split("/")
  56. def git_branch(cwd=None):
  57. return run(["git", "rev-parse", "--abbrev-ref", "HEAD"], cwd)
  58. def espurna_get_version(base, version_h="code/espurna/config/version.h"):
  59. version = "unknown"
  60. path = os.path.join(base, version_h)
  61. with open(path, "r") as version_f:
  62. for line in version_f:
  63. if line.startswith("#define") and "APP_VERSION" in line:
  64. version = parse_h_string(line)
  65. break
  66. return version
  67. TEMPLATES = {
  68. "![travis]": "[![travis](https://travis-ci.org/{USER}/{REPO}.svg?branch={BRANCH})]"
  69. "(https://travis-ci.org/{USER}/{REPO})\n",
  70. "![version]": "[![version](https://img.shields.io/badge/version-{VERSION:escape_hyphen}-brightgreen.svg)]"
  71. "(CHANGELOG.md)\n",
  72. "![branch]": "[![branch](https://img.shields.io/badge/branch-{BRANCH:escape_hyphen}-orange.svg)]"
  73. "(https://github.com/{USER}/{REPO}/tree/{BRANCH}/)\n",
  74. }
  75. README = "README.md"
  76. if __name__ == "__main__":
  77. base = os.getcwd()
  78. user, repo = git_parse_remote()
  79. parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter)
  80. parser.add_argument("-b", "--branch", help="git branch name", default=git_branch())
  81. parser.add_argument("-u", "--user", help="git user name", default=user)
  82. parser.add_argument("-r", "--repo", help="git repo name", default=repo)
  83. parser.add_argument("-v", "--version", help="ESPurna version", default=espurna_get_version(base))
  84. args = parser.parse_args()
  85. fmt = {
  86. "USER": args.user,
  87. "REPO": args.repo,
  88. "BRANCH": args.branch,
  89. "VERSION": args.version
  90. }
  91. formatter = CustomFormatter()
  92. templates = [
  93. (k, formatter.format(tmpl, **fmt))
  94. for k, tmpl in TEMPLATES.items()
  95. ]
  96. def fmt_line(line):
  97. for match, tmpl in templates:
  98. if match in line:
  99. return tmpl
  100. return line
  101. path = os.path.join(base, README)
  102. with FileInput(path, inplace=True) as readme:
  103. for line in readme:
  104. sys.stdout.write(fmt_line(line))
  105. if call(["git", "add", README]):
  106. sys.exit(1)
  107. sys.exit(0)