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.

149 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. CI badge [3] 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://github.com/xoseperez/espurna/actions
  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. "![ci]": "![ci](https://github.com/{USER}/{REPO}/workflows/ESPurna%20build/badge.svg?branch={BRANCH})\n"
  69. "![version]": "[![version](https://img.shields.io/badge/version-{VERSION:escape_hyphen}-brightgreen.svg)]"
  70. "(CHANGELOG.md)\n",
  71. "![branch]": "[![branch](https://img.shields.io/badge/branch-{BRANCH:escape_hyphen}-orange.svg)]"
  72. "(https://github.com/{USER}/{REPO}/tree/{BRANCH}/)\n",
  73. }
  74. README = "README.md"
  75. if __name__ == "__main__":
  76. base = os.getcwd()
  77. user, repo = git_parse_remote()
  78. parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter)
  79. parser.add_argument("-b", "--branch", help="git branch name", default=git_branch())
  80. parser.add_argument("-u", "--user", help="git user name", default=user)
  81. parser.add_argument("-r", "--repo", help="git repo name", default=repo)
  82. parser.add_argument("-v", "--version", help="ESPurna version", default=espurna_get_version(base))
  83. args = parser.parse_args()
  84. fmt = {
  85. "USER": args.user,
  86. "REPO": args.repo,
  87. "BRANCH": args.branch,
  88. "VERSION": args.version
  89. }
  90. formatter = CustomFormatter()
  91. templates = [
  92. (k, formatter.format(tmpl, **fmt))
  93. for k, tmpl in TEMPLATES.items()
  94. ]
  95. def fmt_line(line):
  96. for match, tmpl in templates:
  97. if match in line:
  98. return tmpl
  99. return line
  100. path = os.path.join(base, README)
  101. with FileInput(path, inplace=True) as readme:
  102. for line in readme:
  103. sys.stdout.write(fmt_line(line))
  104. if call(["git", "add", README]):
  105. sys.exit(1)
  106. sys.exit(0)