-
Notifications
You must be signed in to change notification settings - Fork 0
/
compile.py
executable file
·253 lines (211 loc) · 6.59 KB
/
compile.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
#!/usr/bin/env python3
"""
# Rust Project Builder Assistant
> Easier huh?
## Description
What I do for you:
+ provide a quick and efficient way to execute complexe commands without having to
memorized them
+ compile your project in `debug` or `release`
+ execute unit and integration tests
+ choice between quick or complete tests
+ build the documentation
+ publish the crate
## Usage
To build and run the program, tests or examples:
Usage: ./compile.py [OPTIONS] COMMAND [ARGS]...
Rust Project Builder Assistant.
By default, compile the binary from the main program in debug mode, and
run it. If you want to compile in release mode, for the main command or
any subcommand, use the release option.
Options:
-v, --version Show version.
-r, --release Enable release mode.
-h, --help Show this message and exit.
Commands:
doc Build documentation.
example Compile and run an example.
publish Publish your library on crates.io.
tests Compile and execute unit and integration tests.
update-versions Update versions in all files according to the manifest.
"""
from pathlib import Path
from typing import Optional, Any
from dotmap import DotMap
import envtoml
import subprocess
import termcolor
import re
import os
import sys
import click
from pudb import set_trace as bp # noqa
# Constants.
PWD = os.getcwd()
# Parameters.
TEST_FLAGS = "-- --color always --nocapture "
RUST_BACKTRACE = "full"
RUSTDOCFLAGS = f"--html-in-header {PWD}/rsc/html/docs-header.html"
# Initialization.
MANIFEST_FILE = Path("Cargo.toml")
MANIFEST = DotMap(envtoml.load(MANIFEST_FILE.open()))
_NAME = MANIFEST.package.name
VERSION = MANIFEST.package.version
CONTEXT_SETTINGS = dict(help_option_names=["-h", "--help"])
REGEX_VERSION = dict()
REGEX_VERSION.update(
dict.fromkeys(
["src/lib.rs", "README.md"],
{
"pattern": rf'(\[dependencies\][\r]?\n{_NAME}\s=\s)("[\d.]+")',
"repl": rf'\g<1>"{VERSION}"',
},
)
)
def export_environment_variables() -> None:
"""Export environment variables."""
os.environ["RUST_BACKTRACE"] = RUST_BACKTRACE
os.environ["RUSTDOCFLAGS"] = RUSTDOCFLAGS
def build(command: str, flags: str = "") -> None:
"""Proceed to build with following the given flags."""
try:
subprocess.check_call(f"cargo {command} {flags}", shell=True)
except subprocess.CalledProcessError:
# The publishing might fail, the error is explained by Cargo.
sys.exit(1)
def check_release(flags: str = "", release: bool = False) -> str:
"""
Add to flags if the build is meant to be in release mode.
The argument `flags` is mutable in the scope of the function.
"""
if release:
flags += "--release "
return flags
def print_version(ctx: click.Context, param: Any, value: bool) -> None:
"""Show version."""
if not value or ctx.resilient_parsing:
return
click.echo(VERSION)
ctx.exit()
@click.group(context_settings=CONTEXT_SETTINGS, invoke_without_command=True)
@click.pass_context
@click.option(
"-v",
"--version",
is_flag=True,
callback=print_version,
expose_value=False,
is_eager=True,
help="Show version.",
)
@click.option(
"-r",
"--release",
is_flag=True,
help="Enable release mode.",
)
def cli(ctx: click.Context, release: bool) -> None:
"""
Rust Project Builder Assistant.
By default, compile the binary from the main program in debug mode, and run it. If
you want to compile in release mode, for the main command or any subcommand, use the
release option.
"""
# Ensure that ctx.obj exists.
ctx.ensure_object(dict)
# Share default command options.
ctx.obj["RELEASE"] = release
# Environment variable.
export_environment_variables()
# Default command.
if ctx.invoked_subcommand is None:
flags = check_release(release=release)
build("run", flags)
@cli.command()
@click.pass_context
@click.argument("name", required=False)
def example(ctx: click.Context, name: Optional[str] = None) -> None:
"""Compile and run an example."""
flags = check_release(release=ctx.obj["RELEASE"])
flags += "--example "
if name is not None:
flags += name
build("run", flags)
else:
# Get list of available examples.
list_examples = [example.stem for example in Path("examples").glob("*.rs")]
# Prepare string format.
example_files = " " + "\n ".join(list_examples)
# Organize error message.
error_title = termcolor.colored("missing the name of the example", "red")
raised_error = f"{error_title}.\n\nAvailable examples:\n{example_files}"
# Raise error.
raise TypeError(raised_error)
@cli.command()
@click.pass_context
@click.option(
"-a",
"--all",
"all_",
is_flag=True,
help="Test all targets: lib, bins, tests, benches, examples.",
)
def tests(ctx: click.Context, all_: bool) -> None:
"""Compile and execute unit and integration tests."""
flags = check_release(release=ctx.obj["RELEASE"])
if all_:
flags += "--all-targets "
else:
flags += "--test lib "
flags += TEST_FLAGS
build("test", flags)
@cli.command()
@click.pass_context
@click.option(
"-o",
"--open",
"open_",
is_flag=True,
help="Open the documentation in your browser after the build.",
)
def doc(ctx: click.Context, open_: bool) -> None:
"""Build documentation."""
flags = ""
if open_:
flags += "--open "
build("doc", flags)
@cli.command()
@click.pass_context
@click.option(
"-c",
"--check",
is_flag=True,
help="Check any warning or error before publishing.",
)
def publish(ctx: click.Context, check: bool) -> None:
"""Publish your library on crates.io."""
flags = ""
if check:
flags += "--dry-run "
build("publish", flags)
@cli.command()
@click.pass_context
def update_versions(ctx: click.Context) -> None:
"""Update versions in all files according to the manifest."""
for file_to_check, regex in REGEX_VERSION.items():
path = Path(file_to_check)
contents = path.read_text()
# Check result is unique.
result = re.findall(regex["pattern"], contents)
if len(result) != 1:
raise ValueError(
f"More than one match for the match pattern of {path.name} file"
)
# Apply version correction.
contents = re.sub(regex["pattern"], regex["repl"], contents)
with path.open("w") as f:
f.write(contents)
def main() -> None:
cli(prog_name=__file__)
if __name__ == "__main__":
main()