Skip to content

Commit c8e939b

Browse files
committed
magic run format
1 parent 6adf1f1 commit c8e939b

File tree

5 files changed

+66
-61
lines changed

5 files changed

+66
-61
lines changed

lightbug_api/app.mojo

Lines changed: 17 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@ from lightbug_api.openapi.generate import OpenAPIGenerator
99
from lightbug_api.routing import Router
1010
from lightbug_api.docs import DocsApp
1111

12+
1213
@value
1314
struct App[docs_enabled: Bool = False]:
1415
var router: Router
@@ -23,9 +24,9 @@ struct App[docs_enabled: Bool = False]:
2324

2425
fn func(mut self, req: HTTPRequest) raises -> HTTPResponse:
2526
if docs_enabled and req.uri.path == "/docs" and req.method == "GET":
26-
var openapi_spec = self.generate_openapi_spec()
27-
var docs = DocsApp(to_string(openapi_spec))
28-
return docs.func(req)
27+
var openapi_spec = self.generate_openapi_spec()
28+
var docs = DocsApp(to_string(openapi_spec))
29+
return docs.func(req)
2930
for route_ptr in self.router.routes:
3031
var route = route_ptr[]
3132
if route.path == req.uri.path and route.method == req.method:
@@ -47,47 +48,42 @@ struct App[docs_enabled: Bool = False]:
4748
fn update_temporary_files(mut self) raises:
4849
var routes_obj = Object()
4950
var routes = List[Value]()
50-
51+
5152
for route_ptr in self.router.routes:
5253
var route = route_ptr[]
5354
var route_obj = Object()
5455
route_obj["path"] = route.path
5556
route_obj["method"] = route.method
5657
route_obj["handler"] = route.operation_id
5758
routes.append(route_obj)
58-
59+
5960
routes_obj["routes"] = Array.from_list(routes)
6061
var cwd = Path()
6162
var lightbug_dir = cwd / ".lightbug"
6263
self.set_lightbug_dir(lightbug_dir)
63-
64+
6465
if not exists(lightbug_dir):
6566
logger.info("Creating .lightbug directory")
6667
mkdir(lightbug_dir)
67-
68+
6869
with open((lightbug_dir / "routes.json"), "w") as f:
6970
f.write(to_string[pretty=True](routes_obj))
70-
71-
var mojodoc_status = external_call["system", UInt8]("magic run mojo doc ./lightbug.🔥 -o " + str(lightbug_dir) + "/mojodoc.json")
71+
72+
var mojodoc_status = external_call["system", UInt8](
73+
"magic run mojo doc ./lightbug.🔥 -o " + str(lightbug_dir) + "/mojodoc.json"
74+
)
7275
if mojodoc_status != 0:
7376
logger.error("Failed to generate mojodoc.json")
7477
return
7578

7679
fn generate_openapi_spec(self) raises -> JSON:
7780
var generator = OpenAPIGenerator()
78-
79-
var mojo_doc_json = generator.read_mojo_doc(
80-
str(self.lightbug_dir / "mojodoc.json")
81-
)
82-
var router_metadata_json = generator.read_router_metadata(
83-
str(self.lightbug_dir / "routes.json")
84-
)
85-
81+
82+
var mojo_doc_json = generator.read_mojo_doc(str(self.lightbug_dir / "mojodoc.json"))
83+
var router_metadata_json = generator.read_router_metadata(str(self.lightbug_dir / "routes.json"))
84+
8685
var openapi_spec = generator.generate_spec(mojo_doc_json, router_metadata_json)
87-
generator.save_spec(
88-
openapi_spec,
89-
str(self.lightbug_dir / "openapi_spec.json")
90-
)
86+
generator.save_spec(openapi_spec, str(self.lightbug_dir / "openapi_spec.json"))
9187
return openapi_spec
9288

9389
fn start_server(mut self, address: StringLiteral = "0.0.0.0:8080") raises:

lightbug_api/docs.mojo

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,14 @@
11
from lightbug_http import Server, HTTPRequest, HTTPResponse, OK
22
from lightbug_http.utils import logger
33

4+
45
@value
56
struct DocsApp:
67
var openapi_spec: String
78

89
fn func(mut self, req: HTTPRequest) raises -> HTTPResponse:
9-
var html_response = String("""
10+
var html_response = String(
11+
"""
1012
<!doctype html>
1113
<html>
1214
<head>
@@ -25,7 +27,8 @@ struct DocsApp:
2527
<script src="https://cdn.jsdelivr.net/npm/@scalar/api-reference"></script>
2628
</body>
2729
</html>
28-
""").format(self.openapi_spec)
30+
"""
31+
).format(self.openapi_spec)
2932
return OK(html_response, "text/html; charset=utf-8")
3033

3134
fn set_openapi_spec(mut self, openapi_spec: String):
@@ -34,4 +37,4 @@ struct DocsApp:
3437
fn start_docs_server(mut self, address: StringLiteral = "0.0.0.0:8888") raises:
3538
logger.info("Starting docs at " + String(address))
3639
var server = Server()
37-
server.listen_and_serve(address, self)
40+
server.listen_and_serve(address, self)

lightbug_api/openapi/generate.mojo

Lines changed: 34 additions & 34 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
from collections.dict import Dict
22
from emberjson import JSON, Value, Array, Object, ParseOptions, parse, to_string
33

4+
45
struct OpenAPIGenerator:
56
var tags: List[Value]
67

@@ -23,53 +24,53 @@ struct OpenAPIGenerator:
2324
var path = route["path"][String].strip('"')
2425
var method = String(route["method"][String].strip('"')).lower()
2526
route_map[handler] = (String(path), method)
26-
27+
2728
for func in mojo_doc["decl"][Object]["functions"][Array]._data:
2829
var func_name = str(func[][Object]["name"]).strip('"')
29-
30+
3031
if func_name not in route_map:
3132
continue
32-
33+
3334
var route_info = route_map[func_name]
3435
var path = route_info.get[0][String]()
3536
var http_method = route_info.get[1][String]()
36-
37+
3738
var endpoint = self.create_endpoint(func[].object(), http_method)
38-
39+
3940
if paths.__contains__(path):
4041
var new_path_item = JSON()
4142
var existing_path_item = paths[path][Object]
42-
43+
4344
for key in existing_path_item._data.keys():
4445
var existing_key = key[]
4546
new_path_item[existing_key] = existing_path_item[existing_key]
46-
47+
4748
new_path_item[http_method] = endpoint.object()
48-
49+
4950
paths[path] = new_path_item.object()
5051
else:
5152
var path_item = JSON()
5253
path_item[http_method] = endpoint.object()
5354
paths[path] = path_item.object()
54-
55+
5556
return paths
5657

5758
fn create_endpoint(mut self, function_data: JSON, http_method: String) raises -> JSON:
5859
var endpoint = JSON()
5960
var func_name = function_data["name"]
6061
endpoint["summary"] = String(str(func_name).strip('"')) + " endpoint"
6162
endpoint["operationId"] = func_name
62-
63+
6364
var responses = JSON()
6465
var response_200 = JSON()
65-
66+
6667
var overloads = Array(function_data["overloads"])._data
6768

6869
var request_description = String("Request body")
6970
var response_description = String("Successful response")
7071

7172
for i in range(len(overloads)):
72-
var overload = overloads[i][Array][0] # first overload only for now
73+
var overload = overloads[i][Array][0] # first overload only for now
7374
if "returnsDoc" in overload[Object]._data:
7475
response_description = String(str(overload[Object]["returnsDoc"]).strip('"'))
7576
if "summary" in overload[Object]._data:
@@ -95,14 +96,14 @@ struct OpenAPIGenerator:
9596
if "description" in arg._data:
9697
request_description = String(str(arg["description"]).strip('"'))
9798
break
98-
99+
99100
response_200["description"] = response_description
100-
101+
101102
var content = JSON()
102103
var text_plain = JSON()
103104
var schema = JSON()
104105
schema["type"] = "string"
105-
106+
106107
text_plain["schema"] = schema.object()
107108
content["text/plain"] = text_plain.object()
108109
response_200["content"] = content.object()
@@ -113,78 +114,78 @@ struct OpenAPIGenerator:
113114
var request_body = JSON()
114115
request_body["required"] = True
115116
request_body["description"] = request_description
116-
117+
117118
var req_content = JSON()
118119
var req_text_plain = JSON()
119120
var req_schema = JSON()
120121
req_schema["type"] = "string"
121-
122+
122123
req_text_plain["schema"] = req_schema.object()
123124
req_content["text/plain"] = req_text_plain.object()
124125
request_body["content"] = req_content.object()
125126
endpoint["requestBody"] = request_body.object()
126-
127+
127128
return endpoint
128129

129130
fn create_components_schema(self) raises -> JSON:
130131
var components = JSON()
131132
var schemas = JSON()
132-
133+
133134
# Define HTTPRequest schema
134135
var http_request = JSON()
135136
var request_properties = JSON()
136-
137+
137138
var body_raw = JSON()
138139
body_raw["type"] = "string"
139-
140+
140141
var uri = JSON()
141142
var uri_properties = JSON()
142143
var path = JSON()
143144
path["type"] = "string"
144145
uri_properties["path"] = path.object()
145146
uri["type"] = "object"
146147
uri["properties"] = uri_properties.object()
147-
148+
148149
var method = JSON()
149150
method["type"] = "string"
150-
151+
151152
request_properties["body_raw"] = body_raw.object()
152153
request_properties["uri"] = uri.object()
153154
request_properties["method"] = method.object()
154-
155+
155156
http_request["type"] = "object"
156157
http_request["properties"] = request_properties.object()
157-
158+
158159
# Define HTTPResponse schema
159160
var http_response = JSON()
160161
var response_properties = JSON()
161162
var body = JSON()
162163
body["type"] = "string"
163164
response_properties["body"] = body.object()
164-
165+
165166
http_response["type"] = "object"
166167
http_response["properties"] = response_properties.object()
167-
168+
168169
schemas["HTTPRequest"] = http_request.object()
169170
schemas["HTTPResponse"] = http_response.object()
170171
components["schemas"] = schemas.object()
171-
172+
172173
return components
173174

174175
fn generate_spec(mut self, mojo_doc: JSON, router_metadata: JSON) raises -> JSON:
175176
var spec = JSON()
176-
177+
177178
spec["openapi"] = "3.0.0"
178-
179+
179180
var info = JSON()
180181
info["title"] = mojo_doc["decl"][Object]["name"]
181182
info["version"] = mojo_doc["version"]
182183
info["description"] = "API generated from Mojo documentation"
183-
184+
184185
spec["info"] = info.object()
185186
spec["paths"] = self.create_paths(mojo_doc, router_metadata).object()
186187
spec["components"] = self.create_components_schema().object()
187-
188+
188189
return spec
189190

190191
fn read_mojo_doc(self, filename: String) raises -> JSON:
@@ -194,8 +195,7 @@ struct OpenAPIGenerator:
194195
fn read_router_metadata(self, filename: String) raises -> JSON:
195196
with open(filename, "r") as router_metadata:
196197
return parse[ParseOptions(fast_float_parsing=True)](router_metadata.read())
197-
198+
198199
fn save_spec(self, spec: JSON, filename: String) raises:
199200
with open(filename, "w") as f:
200201
f.write(to_string[pretty=True](spec))
201-

lightbug_api/routing.mojo

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
from lightbug_http import HTTPRequest, HTTPResponse, NotFound
22
from lightbug_api.service import not_found
33

4+
45
struct APIRoute(CollectionElement):
56
var path: String
67
var method: String
@@ -13,7 +14,9 @@ struct APIRoute(CollectionElement):
1314
self.handler = not_found
1415
self.operation_id = ""
1516

16-
fn __init__(out self, path: String, method: String, handler: fn (HTTPRequest) -> HTTPResponse, operation_id: String):
17+
fn __init__(
18+
out self, path: String, method: String, handler: fn (HTTPRequest) -> HTTPResponse, operation_id: String
19+
):
1720
self.path = path
1821
self.method = method
1922
self.handler = handler
@@ -45,5 +48,7 @@ struct Router:
4548
fn __moveinit__(out self: Router, owned existing: Router):
4649
self.routes = existing.routes
4750

48-
fn add_route(out self, path: String, method: String, handler: fn (HTTPRequest) -> HTTPResponse, operation_id: String):
51+
fn add_route(
52+
out self, path: String, method: String, handler: fn (HTTPRequest) -> HTTPResponse, operation_id: String
53+
):
4954
self.routes.append(APIRoute(path, method, handler, operation_id))

lightbug_api/service.mojo

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
from lightbug_http import HTTPRequest, HTTPResponse, NotFound
22

3+
34
@always_inline
45
fn not_found(req: HTTPRequest) -> HTTPResponse:
5-
return NotFound(req.uri.path)
6+
return NotFound(req.uri.path)

0 commit comments

Comments
 (0)