Debian Codegraph @

generator.py

raw
1 #!/usr/bin/env python3
2
3 from pathlib import Path
4 import argparse
5 import subprocess
6 import sys
7 import asyncio
8
9 DEFAULT_GIR_FILES_DIRECTORY = Path("./gir-files")
10 DEFAULT_GIR_DIRECTORY = Path("./gir/") # TODO: This is typically the directory _of this Python script_ (which external projects symlink to)
11
12
13 def run_command(command, folder=None):
14 return subprocess.run(command, cwd=folder, check=True)
15
16
17 async def spawn_process(exe, args):
18 p = await asyncio.create_subprocess_exec(
19 str(exe),
20 *(str(arg) for arg in args),
21 stdout=asyncio.subprocess.PIPE,
22 stderr=asyncio.subprocess.PIPE,
23 )
24
25 stdout, stderr = await p.communicate()
26 stdout = stdout.decode("utf-8")
27 stderr = stderr.decode("utf-8")
28 assert p.returncode == 0, stderr.strip()
29 return stdout, stderr
30
31
32 async def spawn_gir(conf, args):
33 if conf.gir_path:
34 stdout, stderr = await spawn_process(conf.gir_path, args)
35 else:
36 cargo_args = ["run", "--release", "--quiet", "--manifest-path", DEFAULT_GIR_DIRECTORY / "Cargo.toml", "--"]
37 stdout, stderr = await spawn_process("cargo", cargo_args + args)
38
39 # Gir doesn't print anything to stdout. If it does, this is likely out of
40 # order with stderr, unless the printer/logging flushes in between.
41 assert not stdout, "`gir` printed unexpected stdout: {}".format(stdout)
42 if stderr:
43 return "===> stderr:\n\n" + stderr + "\n"
44 return ""
45
46
47 def ask_yes_no_question(question, conf):
48 question = "{} [y/N] ".format(question)
49 if conf.yes:
50 print(question + "y")
51 return True
52 line = input(question)
53 return line.strip().lower() == "y"
54
55
56 def update_submodule(submodule_path, conf):
57 if any(submodule_path.iterdir()):
58 return False
59 print("=> Initializing {} submodule...".format(submodule_path))
60 run_command(["git", "submodule", "update", "--init", submodule_path])
61 print("<= Done!")
62
63 if ask_yes_no_question(
64 "Do you want to update {} submodule?".format(submodule_path), conf
65 ):
66 print("=> Updating submodule...")
67 run_command(["git", "reset", "--hard", "HEAD"], submodule_path)
68 run_command(["git", "pull", "-f", "origin", "main"], submodule_path)
69 print("<= Done!")
70 return True
71 return False
72
73
74 async def regenerate_crate_docs(conf, crate_dir, base_gir_args):
75 doc_path = "docs.md"
76 # Generate into docs.md instead of the default vendor.md
77 doc_args = base_gir_args + ["-m", "doc", "--doc-target-path", doc_path]
78
79 # The above `gir -m doc` generates docs.md relative to the directory containing Gir.toml
80 doc_path = crate_dir / doc_path
81 embed_args = ["-m", "-d", crate_dir / "src"]
82
83 logs = ""
84
85 if conf.strip_docs:
86 logs += "==> Stripping documentation from `{}`...\n".format(crate_dir)
87 # -n dumps stripped docs to stdout
88 _, stderr = await spawn_process("rustdoc-stripper", embed_args + ["-s", "-n"])
89 if stderr:
90 logs += "===> stderr:\n\n" + stderr + "\n"
91
92 if conf.embed_docs:
93 logs += "==> Regenerating documentation for `{}` into `{}`...\n".format(
94 crate_dir, doc_path
95 )
96 logs += await spawn_gir(conf, doc_args)
97
98 logs += "==> Embedding documentation from `{}` into `{}`...\n".format(
99 doc_path, crate_dir
100 )
101 stdout, stderr = await spawn_process(
102 "rustdoc-stripper", embed_args + ["-g", "-o", doc_path]
103 )
104 if stdout:
105 logs += "===> stdout:\n\n" + stdout + "\n"
106 if stderr:
107 logs += "===> stderr:\n\n" + stderr + "\n"
108
109 return logs
110
111
112 def regen_crates(path, conf):
113 processes = []
114 if path.is_dir():
115 for entry in path.rglob("Gir*.toml"):
116 processes += regen_crates(entry, conf)
117 elif path.match("Gir*.toml"):
118 args = ["-c", path, "-o", path.parent] + [
119 d for path in conf.gir_files_paths for d in ("-d", path)
120 ]
121
122 is_sys_crate = path.parent.name.endswith("sys")
123
124 if conf.embed_docs or conf.strip_docs:
125 # Embedding documentation only applies to non-sys crates
126 if is_sys_crate:
127 return processes
128
129 processes.append(regenerate_crate_docs(conf, path.parent, args))
130 else:
131 if is_sys_crate:
132 args.extend(["-m", "sys"])
133
134 async def regenerate_crate(path, args):
135 return "==> Regenerating `{}`...\n".format(path) + await spawn_gir(
136 conf, args
137 )
138
139 processes.append(regenerate_crate(path, args))
140
141 else:
142 raise Exception("`{}` is not a valid Gir*.toml file".format(path))
143
144 return processes
145
146
147 def valid_path(path):
148 path = Path(path)
149 if not path.exists():
150 raise argparse.ArgumentTypeError("`{}` no such file or directory".format(path))
151 return path
152
153
154 def directory_path(path):
155 path = Path(path)
156 if not path.is_dir():
157 raise argparse.ArgumentTypeError("`{}` directory not found".format(path))
158 return path
159
160
161 def file_path(path):
162 path = Path(path)
163 if not path.is_file():
164 raise argparse.ArgumentTypeError("`{}` file not found".format(path))
165 return path
166
167
168 def parse_args():
169 parser = argparse.ArgumentParser(
170 description="Helper to regenerate gtk-rs crates using gir.",
171 formatter_class=argparse.ArgumentDefaultsHelpFormatter,
172 )
173
174 parser.add_argument(
175 "path",
176 nargs="*",
177 default=[Path(".")],
178 type=valid_path,
179 help="Paths in which to look for Gir.toml files",
180 )
181 parser.add_argument(
182 "--gir-files-directories",
183 nargs="+", # If the option is used, we expect at least one folder!
184 dest="gir_files_paths",
185 default=[],
186 type=directory_path,
187 help="Path of the gir-files folder",
188 )
189 parser.add_argument(
190 "--gir-path",
191 type=file_path,
192 help="Path of the gir executable to run",
193 )
194 parser.add_argument(
195 "--yes",
196 action="store_true",
197 help=" Always answer `yes` to any question asked by the script",
198 )
199 parser.add_argument(
200 "--no-fmt",
201 action="store_true",
202 help="If set, this script will not run `cargo fmt`",
203 )
204 parser.add_argument(
205 "--embed-docs",
206 action="store_true",
207 help="Build documentation with `gir -m doc`, and embed it with `rustdoc-stripper -g`",
208 )
209 parser.add_argument(
210 "--strip-docs",
211 action="store_true",
212 help="Remove documentation with `rustdoc-stripper -s -n`. Can be used in conjunction with --embed-docs",
213 )
214
215 return parser.parse_args()
216
217
218 async def main():
219 conf = parse_args()
220
221 if not conf.gir_files_paths:
222 update_submodule(DEFAULT_GIR_FILES_DIRECTORY, conf)
223
224 if conf.gir_path is None:
225 update_submodule(DEFAULT_GIR_DIRECTORY, conf)
226 print("=> Building gir...")
227 run_command(["cargo", "build", "--release", "--manifest-path", DEFAULT_GIR_DIRECTORY / "Cargo.toml"])
228 print("<= Done!")
229
230 print("=> Regenerating crates...")
231 for path in conf.path:
232 print("=> Looking in path `{}`".format(path))
233 # Collect and print the results as soon as they trickle in, one process at a time:
234 for coro in asyncio.as_completed(regen_crates(path, conf)):
235 print(await coro, end="")
236
237 if not conf.no_fmt and not run_command(["cargo", "fmt"]):
238 return 1
239 print("<= Done!")
240 print("Don't forget to check if everything has been correctly generated!")
241 return 0
242
243
244 if __name__ == "__main__":
245 try:
246 asyncio.run(main())
247 except Exception as e:
248 print("Error: {}".format(e), file=sys.stderr)
249 sys.exit(1)