-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbuild.rs
More file actions
196 lines (170 loc) · 6.91 KB
/
build.rs
File metadata and controls
196 lines (170 loc) · 6.91 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
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
//! Build script for Netsuke.
//!
//! This script performs two main tasks:
//! - Generate the CLI manual page into `target/generated-man/<target>/<profile>` for release
//! packaging.
//! - Audit localization keys declared in `src/localization/keys.rs` against the Fluent bundles
//! in `locales/*/messages.ftl`, failing the build if any declared key is missing from a
//! locale.
use clap::{ArgMatches, CommandFactory};
use clap_mangen::Man;
use std::{
env,
ffi::OsString,
fs,
path::{Path, PathBuf},
sync::Arc,
};
use time::{OffsetDateTime, format_description::well_known::Iso8601};
const FALLBACK_DATE: &str = "1970-01-01";
#[path = "src/cli/mod.rs"]
mod cli;
#[path = "src/cli_localization.rs"]
mod cli_localization;
#[path = "src/cli_l10n.rs"]
mod cli_l10n;
#[path = "src/host_pattern.rs"]
mod host_pattern;
#[path = "src/localization/mod.rs"]
mod localization;
#[path = "src/output_mode.rs"]
mod output_mode;
#[path = "src/theme.rs"]
mod theme;
mod build_l10n_audit;
use host_pattern::{HostPattern, HostPatternError};
type LocalizedParseFn = fn(
Vec<OsString>,
&Arc<dyn ortho_config::Localizer>,
) -> Result<(cli::Cli, ArgMatches), clap::Error>;
type ResolveThemeFn = fn(
Option<theme::ThemePreference>,
theme::ThemeContext,
fn(&str) -> Option<String>,
) -> theme::ResolvedTheme;
type ThemeContextCtor = fn(
Option<bool>,
Option<cli::config::ColourPolicy>,
output_mode::OutputMode,
) -> theme::ThemeContext;
fn manual_date() -> String {
let Ok(raw) = env::var("SOURCE_DATE_EPOCH") else {
return FALLBACK_DATE.into();
};
let Ok(ts) = raw.parse::<i64>() else {
println!(
"cargo:warning=Invalid SOURCE_DATE_EPOCH '{raw}'; expected integer seconds since Unix epoch; falling back to {FALLBACK_DATE}"
);
return FALLBACK_DATE.into();
};
let Ok(dt) = OffsetDateTime::from_unix_timestamp(ts) else {
println!(
"cargo:warning=Invalid SOURCE_DATE_EPOCH '{raw}'; not a valid Unix timestamp; falling back to {FALLBACK_DATE}"
);
return FALLBACK_DATE.into();
};
dt.format(&Iso8601::DATE).unwrap_or_else(|_| {
println!(
"cargo:warning=Invalid SOURCE_DATE_EPOCH '{raw}'; formatting failed; falling back to {FALLBACK_DATE}"
);
FALLBACK_DATE.into()
})
}
fn out_dir_for_target_profile() -> PathBuf {
let target = env::var("TARGET").unwrap_or_else(|_| "unknown-target".into());
let profile = env::var("PROFILE").unwrap_or_else(|_| "unknown-profile".into());
PathBuf::from(format!("target/generated-man/{target}/{profile}"))
}
fn write_man_page(data: &[u8], dir: &Path, page_name: &str) -> std::io::Result<PathBuf> {
fs::create_dir_all(dir)?;
let destination = dir.join(page_name);
let tmp = dir.join(format!("{page_name}.tmp"));
fs::write(&tmp, data)?;
if destination.exists() {
fs::remove_file(&destination)?;
}
fs::rename(&tmp, &destination)?;
Ok(destination)
}
/// Anchors all shared-module symbols so they remain linked when the build script is compiled
/// without tests.
const fn assert_symbols_linked() {
const _: usize = std::mem::size_of::<HostPattern>();
const _: fn(&[OsString]) -> Option<String> = cli::locale_hint_from_args;
const _: fn(&[OsString]) -> Option<bool> = cli::diag_json_hint_from_args;
const _: fn(&str) -> Option<bool> = cli_l10n::parse_bool_hint;
const _: fn(&cli::Cli, &ArgMatches) -> bool = cli::resolve_merged_diag_json;
const _: fn(&cli::Cli, &ArgMatches) -> ortho_config::OrthoResult<cli::Cli> =
cli::merge_with_config;
const _: LocalizedParseFn = cli::parse_with_localizer_from;
const _: fn(&cli::Cli) -> cli::config::CliConfig = cli::Cli::config;
const _: fn(&cli::Cli) -> bool = cli::Cli::resolved_diag_json;
const _: fn(&cli::Cli) -> bool = cli::Cli::resolved_progress;
const _: fn(&str) -> Result<HostPattern, HostPatternError> = HostPattern::parse;
const _: fn(&HostPattern, host_pattern::HostCandidate<'_>) -> bool = HostPattern::matches;
const _: fn(Option<bool>, Option<cli::config::ColourPolicy>) -> output_mode::OutputMode =
output_mode::resolve;
const _: fn(&cli::config::CliConfig) -> bool = cli::config::CliConfig::resolved_diag_json;
const _: fn(&cli::config::CliConfig) -> bool = cli::config::CliConfig::resolved_progress;
const _: ThemeContextCtor = theme::ThemeContext::new;
const _: ResolveThemeFn = theme::resolve_theme;
}
/// Emits Cargo rerun directives for all inputs that affect the build output.
fn emit_rerun_directives() {
println!("cargo:rerun-if-changed=src/cli/mod.rs");
println!("cargo:rerun-if-changed=src/cli/parsing.rs");
println!("cargo:rerun-if-env-changed=CARGO_PKG_VERSION");
println!("cargo:rerun-if-env-changed=CARGO_PKG_NAME");
println!("cargo:rerun-if-env-changed=CARGO_BIN_NAME");
println!("cargo:rerun-if-env-changed=CARGO_PKG_DESCRIPTION");
println!("cargo:rerun-if-env-changed=CARGO_PKG_AUTHORS");
println!("cargo:rerun-if-env-changed=SOURCE_DATE_EPOCH");
println!("cargo:rerun-if-env-changed=TARGET");
println!("cargo:rerun-if-env-changed=PROFILE");
println!("cargo:rerun-if-changed=src/localization/keys.rs");
println!("cargo:rerun-if-changed=locales/en-US/messages.ftl");
println!("cargo:rerun-if-changed=locales/es-ES/messages.ftl");
}
fn main() -> Result<(), Box<dyn std::error::Error>> {
assert_symbols_linked();
emit_rerun_directives();
build_l10n_audit::audit_localization_keys()?;
// Packagers expect man pages under target/generated-man/<target>/<profile>.
let out_dir = out_dir_for_target_profile();
// The top-level page documents the entire command interface.
let cmd = cli::Cli::command();
let name = cmd
.get_bin_name()
.unwrap_or_else(|| cmd.get_name())
.to_owned();
let cargo_bin = env::var("CARGO_BIN_NAME")
.or_else(|_| env::var("CARGO_PKG_NAME"))
.unwrap_or_else(|_| name.clone());
if name != cargo_bin {
return Err(format!(
"CLI name {name} differs from Cargo bin/package name {cargo_bin}; packaging expects {cargo_bin}.1"
)
.into());
}
let version = env::var("CARGO_PKG_VERSION").map_err(
|_| "CARGO_PKG_VERSION must be set by Cargo; cannot render manual page without it.",
)?;
let man = Man::new(cmd)
.section("1")
.source(format!("{cargo_bin} {version}"))
.date(manual_date());
let mut buf = Vec::new();
man.render(&mut buf)?;
let page_name = format!("{cargo_bin}.1");
write_man_page(&buf, &out_dir, &page_name)?;
if let Some(extra_dir) = env::var_os("OUT_DIR") {
let extra_dir_path = PathBuf::from(extra_dir);
if let Err(err) = write_man_page(&buf, &extra_dir_path, &page_name) {
println!(
"cargo:warning=Failed to stage manual page in OUT_DIR ({}): {err}",
extra_dir_path.display()
);
}
}
Ok(())
}