Repository navigation
Expand file tree
/
Copy pathbuild.rs
More file actions
169 lines (149 loc) · 5.89 KB
/
Copy pathbuild.rs
File metadata and controls
169 lines (149 loc) · 5.89 KB
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
//! Generates man pages and shell completions into `OUT_DIR` at build time so
//! packagers can install them. End users can also get completions at runtime via
//! `comline completions <shell>`.
//!
//! `src/cli.rs` is intentionally dependency-light so it can be shared here.
use std::env;
use std::fs;
use std::io::Error;
use std::path::{Path, PathBuf};
use std::process::Command as ProcessCommand;
use clap::{Command, CommandFactory};
use clap_complete::Shell;
#[path = "src/cli.rs"]
mod cli;
fn main() -> Result<(), Error> {
println!("cargo:rerun-if-changed=src/cli.rs");
println!("cargo:rerun-if-changed=build.rs");
emit_version_info();
emit_core_rev();
let Some(out_dir) = env::var_os("OUT_DIR").map(PathBuf::from) else {
return Ok(());
};
let man_dir = out_dir.join("man");
fs::create_dir_all(&man_dir)?;
render_man_pages(&man_dir, &cli::Cli::command())?;
let completions_dir = out_dir.join("completions");
fs::create_dir_all(&completions_dir)?;
let mut command = cli::Cli::command();
for shell in [
Shell::Bash,
Shell::Zsh,
Shell::Fish,
Shell::PowerShell,
Shell::Elvish,
] {
clap_complete::generate_to(shell, &mut command, "comline", &completions_dir)?;
}
Ok(())
}
/// Sets `COMLINE_GIT_HASH` / `COMLINE_GIT_BRANCH` / `COMLINE_COMMIT_COUNT` /
/// `COMLINE_BUILD_DATE` for `cli.rs`'s `LONG_VERSION` to pull in via
/// `env!()`. Every one of these degrades to `"unknown"` rather than
/// failing the build — a source tarball with no `.git` directory, or a
/// machine with no `git`/`date` on PATH, still produces a working binary.
///
/// Re-run (and so re-captured) whenever the current commit or branch
/// changes; a build with no new commits reuses the cached binary anyway, so
/// there's nothing to refresh in that case.
fn emit_version_info() {
println!("cargo:rerun-if-changed=.git/HEAD");
println!("cargo:rerun-if-changed=.git/refs");
let hash =
run(&["git", "rev-parse", "--short=12", "HEAD"]).unwrap_or_else(|| "unknown".to_string());
let dirty = run(&["git", "status", "--porcelain"]).is_some_and(|s| !s.is_empty());
let branch =
run(&["git", "rev-parse", "--abbrev-ref", "HEAD"]).unwrap_or_else(|| "unknown".to_string());
let commit_count =
run(&["git", "rev-list", "--count", "HEAD"]).unwrap_or_else(|| "unknown".to_string());
let build_date =
run(&["date", "-u", "+%Y-%m-%d %H:%M:%S UTC"]).unwrap_or_else(|| "unknown".to_string());
println!(
"cargo:rustc-env=COMLINE_GIT_HASH={}{}",
hash,
if dirty { "-dirty" } else { "" }
);
println!("cargo:rustc-env=COMLINE_GIT_BRANCH={branch}");
println!("cargo:rustc-env=COMLINE_COMMIT_COUNT={commit_count}");
println!("cargo:rustc-env=COMLINE_BUILD_DATE={build_date}");
}
/// Sets `COMLINE_CORE_REV` to the `comline-core` commit this build links, for
/// `--version`'s `core-rev:` line (`main.rs`). It is the `#<sha>` of the
/// `comline-core` git source in `Cargo.lock`; a build that doesn't see a
/// lock (`cargo install` without `--locked`) reads the full `rev` of
/// `Cargo.toml`'s `comline-core` line instead, and a build with neither says
/// `unknown`.
fn emit_core_rev() {
println!("cargo:rerun-if-changed=Cargo.toml");
println!("cargo:rerun-if-changed=Cargo.lock");
let rev = fs::read_to_string("Cargo.lock")
.ok()
.and_then(|lock| core_rev_from_lock(&lock))
.or_else(|| {
let manifest = fs::read_to_string("Cargo.toml").ok()?;
core_rev_from_manifest(&manifest)
})
.unwrap_or_else(|| "unknown".to_string());
println!("cargo:rustc-env=COMLINE_CORE_REV={rev}");
}
fn is_sha(s: &str) -> bool {
s.len() == 40 && s.bytes().all(|b| b.is_ascii_hexdigit())
}
/// `source = "git+https://github.com/ComlineProject/core?rev=...#<sha>"` of
/// the `comline-core` package.
fn core_rev_from_lock(lock: &str) -> Option<String> {
let mut package = "";
for line in lock.lines() {
if let Some(name) = line.strip_prefix("name = \"") {
package = name.trim_end_matches('"');
} else if package == "comline-core" {
if let Some(source) = line.strip_prefix("source = \"git+") {
let sha = source.rsplit('#').next()?.trim_end_matches('"');
return is_sha(sha).then(|| sha.to_ascii_lowercase());
}
}
}
None
}
/// `comline-core = { git = "...", rev = "<sha>", ... }`.
fn core_rev_from_manifest(manifest: &str) -> Option<String> {
let line = manifest
.lines()
.find(|l| l.trim_start().starts_with("comline-core"))?;
let rest = line.split("rev = \"").nth(1)?;
let sha = rest.split('"').next()?;
is_sha(sha).then(|| sha.to_ascii_lowercase())
}
/// Run a command, returning trimmed stdout on success - `None` on any
/// failure (missing binary, non-zero exit, not a git repo, ...).
fn run(args: &[&str]) -> Option<String> {
let output = ProcessCommand::new(args[0])
.args(&args[1..])
.output()
.ok()?;
if !output.status.success() {
return None;
}
let text = String::from_utf8(output.stdout).ok()?;
let text = text.trim();
(!text.is_empty()).then(|| text.to_string())
}
fn render_man_pages(dir: &Path, command: &Command) -> Result<(), Error> {
let name = command.get_name().to_string();
write_man(&dir.join(format!("{name}.1")), command.clone(), &name)?;
for sub in command.get_subcommands() {
if sub.get_name() == "help" {
continue;
}
let page = format!("{name}-{}", sub.get_name());
write_man(&dir.join(format!("{page}.1")), sub.clone(), &page)?;
}
Ok(())
}
fn write_man(path: &Path, command: Command, title: &str) -> Result<(), Error> {
let mut buffer = Vec::new();
clap_mangen::Man::new(command)
.title(title.to_uppercase())
.render(&mut buffer)?;
fs::write(path, buffer)
}