Skip to content

Commit 5c698d4

Browse files
committed
Apply git hooks to existing code base
1 parent 29560e8 commit 5c698d4

File tree

5 files changed

+111
-93
lines changed

5 files changed

+111
-93
lines changed

.gitignore

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -114,4 +114,4 @@ venv.bak/
114114
dmypy.json
115115

116116
# Pyre type checker
117-
.pyre/
117+
.pyre/

LICENSE

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -16,4 +16,4 @@ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
1616
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
1717
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
1818
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
19-
SOFTWARE.
19+
SOFTWARE.

mkdocs_git_committers_plugin_2/exclude.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,8 +2,8 @@
22
Module to assist exclude certain files being processed by plugin.
33
Inspired by https://github.com/apenwarr/mkdocs-exclude
44
"""
5-
import os
65
import fnmatch
6+
import os
77
from typing import List
88

99

Lines changed: 83 additions & 58 deletions
Original file line numberDiff line numberDiff line change
@@ -1,77 +1,78 @@
1-
import os
2-
import sys
1+
import json
32
import logging
4-
from pprint import pprint
3+
import os
4+
import re
5+
import time
6+
from datetime import datetime
57
from timeit import default_timer as timer
6-
from datetime import datetime, timedelta
78

8-
from mkdocs import utils as mkdocs_utils
9-
from mkdocs.config import config_options, Config
9+
import requests
10+
from bs4 import BeautifulSoup as bs
11+
from git import Commit, Repo
12+
from mkdocs.config import config_options
1013
from mkdocs.plugins import BasePlugin
11-
12-
from git import Repo, Commit
13-
import requests, json
1414
from requests.exceptions import HTTPError
15-
import time
16-
import hashlib
17-
import re
18-
from bs4 import BeautifulSoup as bs
1915

2016
from mkdocs_git_committers_plugin_2.exclude import exclude
2117

2218
LOG = logging.getLogger("mkdocs.plugins." + __name__)
2319

24-
class GitCommittersPlugin(BasePlugin):
2520

21+
class GitCommittersPlugin(BasePlugin):
2622
config_scheme = (
27-
('enterprise_hostname', config_options.Type(str, default='')),
28-
('repository', config_options.Type(str, default='')),
29-
('branch', config_options.Type(str, default='master')),
30-
('docs_path', config_options.Type(str, default='docs/')),
31-
('enabled', config_options.Type(bool, default=True)),
32-
('cache_dir', config_options.Type(str, default='.cache/plugin/git-committers')),
23+
("enterprise_hostname", config_options.Type(str, default="")),
24+
("repository", config_options.Type(str, default="")),
25+
("branch", config_options.Type(str, default="master")),
26+
("docs_path", config_options.Type(str, default="docs/")),
27+
("enabled", config_options.Type(bool, default=True)),
28+
("cache_dir", config_options.Type(str, default=".cache/plugin/git-committers")),
3329
("exclude", config_options.Type(list, default=[])),
3430
)
3531

3632
def __init__(self):
3733
self.total_time = 0
38-
self.branch = 'master'
34+
self.branch = "master"
3935
self.enabled = True
4036
self.authors = dict()
4137
self.cache_page_authors = dict()
4238
self.exclude = list()
43-
self.cache_date = ''
39+
self.cache_date = ""
4440

4541
def on_config(self, config):
46-
self.enabled = self.config['enabled']
42+
self.enabled = self.config["enabled"]
4743
if not self.enabled:
4844
LOG.info("git-committers plugin DISABLED")
4945
return config
5046

5147
LOG.info("git-committers plugin ENABLED")
5248

53-
if not self.config['repository']:
49+
if not self.config["repository"]:
5450
LOG.error("git-committers plugin: repository not specified")
5551
return config
56-
if self.config['enterprise_hostname'] and self.config['enterprise_hostname'] != '':
57-
self.githuburl = "https://" + self.config['enterprise_hostname'] + "/"
52+
if (
53+
self.config["enterprise_hostname"]
54+
and self.config["enterprise_hostname"] != ""
55+
):
56+
self.githuburl = "https://" + self.config["enterprise_hostname"] + "/"
5857
else:
5958
self.githuburl = "https://github.com/"
6059
self.localrepo = Repo(".")
61-
self.branch = self.config['branch']
62-
self.excluded_pages = self.config['exclude']
60+
self.branch = self.config["branch"]
61+
self.excluded_pages = self.config["exclude"]
6362
return config
6463

6564
def list_contributors(self, path):
66-
if exclude(path.lstrip(self.config['docs_path']), self.excluded_pages):
65+
if exclude(path.lstrip(self.config["docs_path"]), self.excluded_pages):
6766
return None, None
68-
67+
6968
last_commit_date = ""
7069
path = path.replace("\\", "/")
7170
for c in Commit.iter_items(self.localrepo, self.localrepo.head, path):
7271
if not last_commit_date:
7372
# Use the last commit and get the date
74-
last_commit_date = time.strftime("%Y-%m-%d", time.gmtime(c.authored_date))
73+
last_commit_date = time.strftime(
74+
"%Y-%m-%d", time.gmtime(c.authored_date)
75+
)
7576

7677
# File not committed yet
7778
if last_commit_date == "":
@@ -80,68 +81,92 @@ def list_contributors(self, path):
8081

8182
# Try to leverage the cache
8283
if path in self.cache_page_authors:
83-
if self.cache_date and time.strptime(last_commit_date, "%Y-%m-%d") < time.strptime(self.cache_date, "%Y-%m-%d"):
84-
return self.cache_page_authors[path]['authors'], self.cache_page_authors[path]['last_commit_date']
85-
86-
url_contribs = self.githuburl + self.config['repository'] + "/contributors-list/" + self.config['branch'] + "/" + path
84+
if self.cache_date and time.strptime(
85+
last_commit_date, "%Y-%m-%d"
86+
) < time.strptime(self.cache_date, "%Y-%m-%d"):
87+
return (
88+
self.cache_page_authors[path]["authors"],
89+
self.cache_page_authors[path]["last_commit_date"],
90+
)
91+
92+
url_contribs = (
93+
self.githuburl
94+
+ self.config["repository"]
95+
+ "/contributors-list/"
96+
+ self.config["branch"]
97+
+ "/"
98+
+ path
99+
)
87100
LOG.info("git-committers: fetching contributors for " + path)
88101
LOG.debug(" from " + url_contribs)
89-
authors=[]
102+
authors = []
90103
try:
91104
response = requests.get(url_contribs)
92105
response.raise_for_status()
93106
except HTTPError as http_err:
94-
LOG.error(f'git-committers: HTTP error occurred: {http_err}\n(404 is normal if file is not on GitHub yet or Git submodule)')
107+
LOG.error(
108+
f"git-committers: HTTP error occurred: {http_err}\n(404 is normal if file is not on GitHub yet or Git submodule)"
109+
)
95110
except Exception as err:
96-
LOG.error(f'git-committers: Other error occurred: {err}')
111+
LOG.error(f"git-committers: Other error occurred: {err}")
97112
else:
98113
html = response.text
99114
# Parse the HTML
100115
soup = bs(html, "lxml")
101-
lis = soup.find_all('li')
116+
lis = soup.find_all("li")
102117
for li in lis:
103-
a_tags = li.find_all('a')
104-
login = a_tags[0]['href'].replace("/", "")
118+
a_tags = li.find_all("a")
119+
login = a_tags[0]["href"].replace("/", "")
105120
url = self.githuburl + login
106121
name = login
107-
img_tags = li.find_all('img')
108-
avatar = img_tags[0]['src']
109-
avatar = re.sub(r'\?.*$', '', avatar)
110-
authors.append({'login':login, 'name': name, 'url': url, 'avatar': avatar})
122+
img_tags = li.find_all("img")
123+
avatar = img_tags[0]["src"]
124+
avatar = re.sub(r"\?.*$", "", avatar)
125+
authors.append(
126+
{"login": login, "name": name, "url": url, "avatar": avatar}
127+
)
111128
# Update global cache_page_authors
112-
self.cache_page_authors[path] = {'last_commit_date': last_commit_date, 'authors': authors}
129+
self.cache_page_authors[path] = {
130+
"last_commit_date": last_commit_date,
131+
"authors": authors,
132+
}
113133

114134
return authors, last_commit_date
115135

116136
def on_page_context(self, context, page, config, nav):
117-
context['committers'] = []
137+
context["committers"] = []
118138
if not self.enabled:
119139
return context
120140
start = timer()
121-
git_path = self.config['docs_path'] + page.file.src_path
141+
git_path = self.config["docs_path"] + page.file.src_path
122142
authors, last_commit_date = self.list_contributors(git_path)
123143
if authors:
124-
context['committers'] = authors
144+
context["committers"] = authors
125145
if last_commit_date:
126-
context['last_commit_date'] = last_commit_date
146+
context["last_commit_date"] = last_commit_date
127147
end = timer()
128-
self.total_time += (end - start)
148+
self.total_time += end - start
129149

130150
return context
131151

132152
def on_post_build(self, config):
133153
LOG.info("git-committers: saving page authors cache file")
134-
json_data = json.dumps({'cache_date': datetime.now().strftime("%Y-%m-%d"), 'page_authors': self.cache_page_authors})
135-
os.makedirs(self.config['cache_dir'], exist_ok=True)
136-
f = open(self.config['cache_dir'] + "/page-authors.json", "w")
154+
json_data = json.dumps(
155+
{
156+
"cache_date": datetime.now().strftime("%Y-%m-%d"),
157+
"page_authors": self.cache_page_authors,
158+
}
159+
)
160+
os.makedirs(self.config["cache_dir"], exist_ok=True)
161+
f = open(self.config["cache_dir"] + "/page-authors.json", "w")
137162
f.write(json_data)
138163
f.close()
139164

140165
def on_pre_build(self, config):
141-
if os.path.exists(self.config['cache_dir'] + "/page-authors.json"):
166+
if os.path.exists(self.config["cache_dir"] + "/page-authors.json"):
142167
LOG.info("git-committers: found page authors cache file - loading it")
143-
f = open(self.config['cache_dir'] + "/page-authors.json", "r")
168+
f = open(self.config["cache_dir"] + "/page-authors.json")
144169
cache = json.loads(f.read())
145-
self.cache_date = cache['cache_date']
146-
self.cache_page_authors = cache['page_authors']
170+
self.cache_date = cache["cache_date"]
171+
self.cache_page_authors = cache["page_authors"]
147172
f.close()

setup.py

Lines changed: 25 additions & 32 deletions
Original file line numberDiff line numberDiff line change
@@ -1,44 +1,37 @@
1-
from setuptools import setup, find_packages
2-
1+
from setuptools import find_packages, setup
32

43
setup(
5-
name='mkdocs-git-committers-plugin-2',
6-
version='1.1.2',
7-
description='An MkDocs plugin to create a list of contributors on the page',
8-
long_description='The git-committers plugin will seed the template context with a list of github committers and other useful GIT info such as last modified date',
9-
keywords='mkdocs pdf github',
10-
url='https://github.com/ojacques/mkdocs-git-committers-plugin-2/',
11-
author='Byrne Reese, Olivier Jacques',
12-
13-
license='MIT',
14-
python_requires='>=2.7',
15-
install_requires=[
16-
'mkdocs>=1.0.3',
17-
'gitpython',
18-
'requests',
19-
'beautifulsoup4'
20-
],
4+
name="mkdocs-git-committers-plugin-2",
5+
version="1.1.2",
6+
description="An MkDocs plugin to create a list of contributors on the page",
7+
long_description="The git-committers plugin will seed the template context with a list of github committers and other useful GIT info such as last modified date",
8+
keywords="mkdocs pdf github",
9+
url="https://github.com/ojacques/mkdocs-git-committers-plugin-2/",
10+
author="Byrne Reese, Olivier Jacques",
11+
12+
license="MIT",
13+
python_requires=">=2.7",
14+
install_requires=["mkdocs>=1.0.3", "gitpython", "requests", "beautifulsoup4"],
2115
extras_require={
2216
# tooling
2317
"dev": ["pre-commit"]
2418
},
2519
classifiers=[
26-
'Development Status :: 4 - Beta',
27-
'Intended Audience :: Developers',
28-
'Intended Audience :: Information Technology',
29-
'License :: OSI Approved :: MIT License',
30-
'Programming Language :: Python',
31-
'Programming Language :: Python :: 3 :: Only',
32-
'Programming Language :: Python :: 3.4',
33-
'Programming Language :: Python :: 3.5',
34-
'Programming Language :: Python :: 3.6',
35-
'Programming Language :: Python :: 3.7'
20+
"Development Status :: 4 - Beta",
21+
"Intended Audience :: Developers",
22+
"Intended Audience :: Information Technology",
23+
"License :: OSI Approved :: MIT License",
24+
"Programming Language :: Python",
25+
"Programming Language :: Python :: 3 :: Only",
26+
"Programming Language :: Python :: 3.4",
27+
"Programming Language :: Python :: 3.5",
28+
"Programming Language :: Python :: 3.6",
29+
"Programming Language :: Python :: 3.7",
3630
],
3731
packages=find_packages(),
3832
entry_points={
39-
'mkdocs.plugins': [
40-
'git-committers = mkdocs_git_committers_plugin_2.plugin:GitCommittersPlugin'
33+
"mkdocs.plugins": [
34+
"git-committers = mkdocs_git_committers_plugin_2.plugin:GitCommittersPlugin"
4135
]
42-
}
36+
},
4337
)
44-

0 commit comments

Comments
 (0)