-
Notifications
You must be signed in to change notification settings - Fork 9
/
__main__.py
257 lines (205 loc) · 8.52 KB
/
__main__.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
"""Render JSON resumes to rich ANSI text for terminal output.
Comes with a server serving either an API or a single file, and a CLI to render files
locally.
"""
from pathlib import Path
from typing import Optional
import typer
app = typer.Typer(no_args_is_help=True, help=__doc__)
server_app = typer.Typer(no_args_is_help=True, help="Interacts with the web server.")
app.add_typer(server_app, name="serve")
@server_app.command()
def api(
host: str = typer.Option("0.0.0.0", help="Hostname to bind to."),
port: int = typer.Option(8080, help="Port to bind to."),
path: Optional[str] = typer.Option(
None, help="File system path for an HTTP server UNIX domain socket."
),
) -> None:
"""Starts the web server and serves the API."""
import os
from ancv.reflection import METADATA
from ancv.web.server import APIHandler, ServerContext
context = ServerContext(host=host, port=port, path=path)
api = APIHandler(
# https://docs.github.com/en/rest/overview/resources-in-the-rest-api#user-agent-required :
requester=os.environ.get("GH_REQUESTER", METADATA.name),
# Not specifying a token works just as well, but has a much lower request
# ceiling:
token=os.environ.get("GH_TOKEN"),
terminal_landing_page=os.environ.get(
"HOMEPAGE", str(METADATA.home_page) or "NO HOMEPAGE SET"
),
# When visiting this endpoint in a browser, we want to redirect to the homepage.
# That page cannot be this same path under the same hostname again, else we get
# a loop.
browser_landing_page=os.environ.get(
"LANDING_PAGE",
METADATA.project_url[0] if METADATA.project_url else "https://github.com/",
),
)
api.run(context)
@server_app.command()
def file(
file: Path = typer.Argument(Path("resume.json")),
host: str = typer.Option("0.0.0.0", help="Hostname to bind to."),
port: int = typer.Option(8080, help="Port to bind to."),
path: Optional[str] = typer.Option(
None, help="File system path for an HTTP server UNIX domain socket."
),
) -> None:
"""Starts the web server and serves a single, rendered resume file."""
from ancv.web.server import FileHandler, ServerContext
context = ServerContext(host=host, port=port, path=path)
FileHandler(file).run(context)
@app.command()
def render(
path: Path = typer.Argument(
Path("resume.json"),
help="File path to the JSON resume file.",
),
) -> None:
"""Locally renders the JSON resume at the given file path."""
from ancv.visualization.templates import Template
template = Template.from_file(path)
output = template.render()
print(output)
return None
@app.command()
def validate(
path: Path = typer.Argument(
Path("resume.json"),
help="File path to the JSON resume file.",
),
) -> None:
"""Checks the validity of the given JSON resume without rendering."""
from pydantic import ValidationError
from ancv.exceptions import ResumeConfigError
from ancv.visualization.templates import Template
try:
Template.from_file(path)
except (ValidationError, ResumeConfigError) as e:
print(str(e))
raise typer.Exit(code=1)
else:
print("Pass!")
@app.command()
def version() -> None:
"""Prints the application version."""
from ancv.reflection import METADATA
print(f"ancv {METADATA.version}")
@app.command()
def list() -> None:
"""Lists all available components (templates, themes and translations)."""
# This is pretty raw, but it works. Could make it prettier using more of `rich`.
from rich import print
from rich.tree import Tree
from ancv.visualization.templates import Template
from ancv.visualization.themes import THEMES
from ancv.visualization.translations import TRANSLATIONS
tree = Tree("Components")
template_tree = Tree("Templates")
for template in Template.subclasses().keys():
template_tree.add(template)
tree.add(template_tree)
theme_tree = Tree("Themes")
for theme in THEMES:
theme_tree.add(theme)
tree.add(theme_tree)
translation_tree = Tree("Translations")
for translation in TRANSLATIONS:
translation_tree.add(translation)
tree.add(translation_tree)
print(tree)
@app.command()
def generate_schema() -> None:
"""Generates and prints the current JSON schema.
ATTENTION: This schema is defined manually, independently of the actual models
contained within this package. As such, the two *might* end up out of sync. This
approach was chosen as a temporary solution, since syncing the JSON Schema and the
pydantic models is a lot of work with a lot of tiny blockers.
"""
import json
from ancv.reflection import METADATA
from ancv.visualization.templates import Template
from ancv.visualization.themes import THEMES
from ancv.visualization.translations import TRANSLATIONS
schema = {
"$schema": "http:https://json-schema.org/draft-04/schema#",
"allOf": [
{
"$ref": "https://raw.githubusercontent.com/jsonresume/resume-schema/v1.0.0/schema.json"
},
{
"type": "object",
"properties": {
"meta": {
"allOf": [
{
"$ref": "https://raw.githubusercontent.com/jsonresume/resume-schema/v1.0.0/schema.json#/properties/meta"
}
],
"properties": {
METADATA.name: {
"type": "object",
"description": f"{METADATA.name}-specific ({METADATA.home_page}) properties",
"properties": {
"template": {
"type": "string",
"description": "The template (ordering, alignment, positioning, ...) to use",
"enum": sorted(Template.subclasses().keys()),
},
"theme": {
"type": "string",
"description": "The theme (colors, emphasis, ...) to use",
"enum": sorted(THEMES.keys()),
},
"language": {
"type": "string",
"description": "The language aka translation (for section titles like 'Education' etc.) to use",
"enum": sorted(TRANSLATIONS.keys()),
},
"ascii_only": {
"type": "boolean",
"description": "Whether to only use ASCII characters in the template (you are responsible for not using non-ASCII characters in your resume)",
},
"dec31_as_year": {
"type": "boolean",
"description": "Whether to display dates of 'December 31st of some year' as that year only, without month or day info",
},
},
}
},
}
},
},
],
}
print(json.dumps(schema, indent=4))
@app.callback()
def main(
verbose: bool = typer.Option(
False, "--verbose", "-v", help="Turn on verbose logging output."
),
) -> None:
"""CLI-wide, global options.
https://typer.tiangolo.com/tutorial/commands/callback/
"""
import logging
import os
import structlog
from structlog.processors import JSONRenderer, TimeStamper, add_log_level
structlog.configure( # This is global state
processors=[ # https://www.structlog.org/en/stable/api.html#procs
TimeStamper(fmt="iso", utc=True, key="ts"),
add_log_level,
JSONRenderer(sort_keys=True),
],
wrapper_class=structlog.make_filtering_bound_logger(
logging.DEBUG if verbose else logging.INFO
),
)
log = structlog.get_logger()
log.debug(f"Starting up with environment: {os.environ}")
if __name__ == "__main__":
app()