Skip to content

Commit 3fa29ea

Browse files
authored
tooling: add black and flake8 for python formatting/linting (tldr-pages#6454)
1 parent f4390b1 commit 3fa29ea

File tree

7 files changed

+190
-125
lines changed

7 files changed

+190
-125
lines changed

.flake8

+5
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
[flake8]
2+
max-line-length = 88
3+
# We ignore E501 as black handles it for us, and in a way that ignores strings
4+
# that go over the line length, as opposed to flake8 which flags such strings.
5+
extend-ignore = E203,E501

.github/workflows/ci.yml

+7
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,10 @@ jobs:
99
name: CI
1010

1111
steps:
12+
- name: Setup Python
13+
uses: actions/setup-python@v2
14+
with:
15+
python-version: 3.8
1216

1317
- name: Checkout
1418
uses: actions/checkout@v2
@@ -22,6 +26,9 @@ jobs:
2226
- name: Install npm dependencies
2327
run: npm ci
2428

29+
- name: Install python dependencies
30+
run: python3 -m pip install -r requirements.txt
31+
2532
- name: Test
2633
run: npm test
2734

requirements.txt

+2
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
black==21.8b0
2+
flake8==3.9.2

scripts/pdf/render.py

+36-15
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,8 @@
1515
import argparse
1616
from datetime import datetime
1717

18-
from weasyprint import HTML, CSS
18+
from weasyprint import HTML
19+
1920

2021
def main(loc, colorscheme):
2122

@@ -30,45 +31,65 @@ def main(loc, colorscheme):
3031
csslist.append(colorscheme + ".css")
3132

3233
# A string that stores all pages in HTML format
33-
html = '<!doctype html><html><head><meta charset="utf-8"></head>' \
34-
+"<body><h1 class=title-main>tldr pages</h1>" \
35-
+ "<h4 class=title-sub>Simplified and community-driven man pages</h4>" \
36-
+ "<h6 class=title-sub><em><small>Generated on " + datetime.now().strftime("%c") + "</small></em></h6>" \
34+
html = (
35+
'<!doctype html><html><head><meta charset="utf-8"></head>'
36+
+ "<body><h1 class=title-main>tldr pages</h1>"
37+
+ "<h4 class=title-sub>Simplified and community-driven man pages</h4>"
38+
+ "<h6 class=title-sub><em><small>Generated on "
39+
+ datetime.now().strftime("%c")
40+
+ "</small></em></h6>"
3741
+ '<p style="page-break-before: always" ></p>'
42+
)
3843

3944
# Writing names of all directories inside 'pages' to a list
4045
for operating_sys in sorted(os.listdir(loc)):
41-
46+
4247
# Required string to create directory title pages
43-
html += "<h2 class=title-dir>" + operating_sys.capitalize() + "</h2>" \
48+
html += (
49+
"<h2 class=title-dir>"
50+
+ operating_sys.capitalize()
51+
+ "</h2>"
4452
+ '<p style="page-break-before: always" ></p>'
53+
)
4554

4655
# Conversion of Markdown to HTML string
47-
for page_number, md in enumerate(sorted(glob.glob(os.path.join(loc, operating_sys, "*.md"))), start=1):
56+
for page_number, md in enumerate(
57+
sorted(glob.glob(os.path.join(loc, operating_sys, "*.md"))), start=1
58+
):
4859
with open(md, "r") as inp:
4960
text = inp.readlines()
5061
for line in text:
51-
if re.match(r'^>', line):
52-
line = line[:0] + '####' + line[1:]
62+
if re.match(r"^>", line):
63+
line = line[:0] + "####" + line[1:]
5364
html += markdown.markdown(line)
5465
html += '<p style="page-break-before: always" ></p>'
5566
print(f"Rendered page {page_number} of the directory {operating_sys}")
56-
67+
5768
html += "</body></html>"
58-
69+
5970
# Writing the PDF to disk
6071
print("\nConverting all pages to PDF...")
6172
HTML(string=html).write_pdf("tldr-pages.pdf", stylesheets=csslist)
6273

6374
if os.path.exists("tldr-pages.pdf"):
6475
print("\nCreated tldr-pages.pdf in the current directory!\n")
6576

77+
6678
if __name__ == "__main__":
6779

6880
# Parsing the arguments
69-
parser = argparse.ArgumentParser(prog="tldr-pages-to-pdf", description="A Python script to generate a single PDF document with all the `tldr` pages.")
70-
parser.add_argument("dir_path", help = "Path to the 'pages' directory")
71-
parser.add_argument("-c", "--color", choices=["solarized-light", "solarized-dark", "basic"], default="basic", help="Color scheme of the PDF")
81+
parser = argparse.ArgumentParser(
82+
prog="tldr-pages-to-pdf",
83+
description="A Python script to generate a single PDF document with all the `tldr` pages.",
84+
)
85+
parser.add_argument("dir_path", help="Path to the 'pages' directory")
86+
parser.add_argument(
87+
"-c",
88+
"--color",
89+
choices=["solarized-light", "solarized-dark", "basic"],
90+
default="basic",
91+
help="Color scheme of the PDF",
92+
)
7293
args = parser.parse_args()
7394

7495
main(args.dir_path, args.color)

scripts/send-to-bot.py

+54-47
Original file line numberDiff line numberDiff line change
@@ -5,9 +5,9 @@
55
import sys
66
import requests
77

8-
BOT_URL = 'https://tldr-bot.starbeamrainbowlabs.com'
8+
BOT_URL = "https://tldr-bot.starbeamrainbowlabs.com"
99

10-
COMMENT_ERROR="""
10+
COMMENT_ERROR = """
1111
The [build](https://github.com/tldr-pages/tldr/actions/runs/{build_id}) for this PR failed with the following error(s):
1212
1313
```
@@ -17,7 +17,7 @@
1717
Please fix the error(s) and push again.
1818
"""
1919

20-
COMMENT_CHECK="""
20+
COMMENT_CHECK = """
2121
Hello! I've noticed something unusual when checking this PR:
2222
2323
{content}
@@ -27,62 +27,69 @@
2727

2828
################################################################################
2929

30+
3031
def post_comment(pr_id, body, once):
31-
endpoint = BOT_URL + '/comment'
32+
endpoint = BOT_URL + "/comment"
33+
34+
if once:
35+
endpoint += "/once"
36+
37+
data = {"pr_id": pr_id, "body": body}
38+
39+
try:
40+
with requests.post(endpoint, json=data) as r:
41+
if r.status_code != requests.codes.ok:
42+
print(
43+
"Error: tldr-bot responded with code",
44+
r.status_code,
45+
file=sys.stderr,
46+
)
47+
print(r.text, file=sys.stderr)
48+
return False
49+
except requests.exceptions.RequestException as e:
50+
print("Error sending data to tldr-bot:", str(e), file=sys.stderr)
51+
return False
3252

33-
if once:
34-
endpoint += '/once'
53+
return True
3554

36-
data = {'pr_id': pr_id, 'body': body}
37-
38-
try:
39-
with requests.post(endpoint, json=data) as r:
40-
if r.status_code != requests.codes.ok:
41-
print('Error: tldr-bot responded with code', r.status_code, file=sys.stderr)
42-
print(r.text, file=sys.stderr)
43-
return False
44-
except requests.exceptions.RequestException as e:
45-
print('Error sending data to tldr-bot:', str(e), file=sys.stderr)
46-
return False
47-
48-
return True
4955

5056
def main(action):
51-
if action not in ('report-errors', 'report-check-results'):
52-
print('Unknown action:', action, file=sys.stderr)
53-
sys.exit(1)
57+
if action not in ("report-errors", "report-check-results"):
58+
print("Unknown action:", action, file=sys.stderr)
59+
sys.exit(1)
60+
61+
content = sys.stdin.read().strip()
5462

55-
content = sys.stdin.read().strip()
63+
if action == "report-errors":
64+
comment_body = COMMENT_ERROR.format(build_id=BUILD_ID, content=content)
65+
comment_once = False
66+
elif action == "report-check-results":
67+
comment_body = COMMENT_CHECK.format(content=content)
68+
comment_once = True
5669

57-
if action == 'report-errors':
58-
comment_body = COMMENT_ERROR.format(build_id=BUILD_ID, content=content)
59-
comment_once = False
60-
elif action == 'report-check-results':
61-
comment_body = COMMENT_CHECK.format(content=content)
62-
comment_once = True
70+
if post_comment(PR_ID, comment_body, comment_once):
71+
print("Success.")
72+
else:
73+
print("Error sending data to tldr-bot!", file=sys.stderr)
6374

64-
if post_comment(PR_ID, comment_body, comment_once):
65-
print('Success.')
66-
else:
67-
print('Error sending data to tldr-bot!', file=sys.stderr)
6875

6976
################################################################################
7077

71-
if __name__ == '__main__':
72-
REPO_SLUG = os.environ.get('GITHUB_REPOSITORY')
73-
PR_ID = os.environ.get('PULL_REQUEST_ID')
74-
BUILD_ID = os.environ.get('GITHUB_RUN_ID')
78+
if __name__ == "__main__":
79+
REPO_SLUG = os.environ.get("GITHUB_REPOSITORY")
80+
PR_ID = os.environ.get("PULL_REQUEST_ID")
81+
BUILD_ID = os.environ.get("GITHUB_RUN_ID")
7582

76-
if PR_ID is None or BUILD_ID is None or REPO_SLUG is None:
77-
print('Needed environment variables are not set.', file=sys.stderr)
78-
sys.exit(1)
83+
if PR_ID is None or BUILD_ID is None or REPO_SLUG is None:
84+
print("Needed environment variables are not set.", file=sys.stderr)
85+
sys.exit(1)
7986

80-
if PR_ID is None or PR_ID == 'false':
81-
print('Not a pull request, refusing to run.', file=sys.stderr)
82-
sys.exit(0)
87+
if PR_ID is None or PR_ID == "false":
88+
print("Not a pull request, refusing to run.", file=sys.stderr)
89+
sys.exit(0)
8390

84-
if len(sys.argv) != 2:
85-
print('Usage:', sys.argv[0], '<ACTION>', file=sys.stderr)
86-
sys.exit(1)
91+
if len(sys.argv) != 2:
92+
print("Usage:", sys.argv[0], "<ACTION>", file=sys.stderr)
93+
sys.exit(1)
8794

88-
main(sys.argv[1])
95+
main(sys.argv[1])

0 commit comments

Comments
 (0)