Skip to main content

cargo_zng/res/
built_in.rs

1//! Built-in tools
2
3use std::{
4    env, fs,
5    io::{self, BufRead as _},
6    path::{Path, PathBuf},
7};
8
9use crate::util;
10
11/// Env var set to the Cargo workspace directory that is parent to the res source.
12///
13/// Note that the tool also runs with this dir as working directory (`current_dir`).
14pub const ZR_WORKSPACE_DIR: &str = "ZR_WORKSPACE_DIR";
15/// Env var set to the resources source directory.
16pub const ZR_SOURCE_DIR: &str = "ZR_SOURCE_DIR";
17/// Env var set to the resources build target directory.
18///
19/// Note that this is the 'root' of the built resources, use [`ZR_TARGET_DD`] to get the
20/// parent dir of the target file inside the target directory.
21pub const ZR_TARGET_DIR: &str = "ZR_TARGET_DIR";
22/// Env var set to dir that the tool can use to store intermediary data for the specific request.
23///
24/// The cache key (dir name) is a hash of source, target, request and request content only.
25pub const ZR_CACHE_DIR: &str = "ZR_CACHE_DIR";
26
27/// Env var set to the request file that called the tool.
28pub const ZR_REQUEST: &str = "ZR_REQUEST";
29/// Env var set to the request file parent dir.
30pub const ZR_REQUEST_DD: &str = "ZR_REQUEST_DD";
31/// Env var set to the target file implied by the request file name.
32///
33/// That is, the request filename without ` '{tool}` and in the equivalent target subdirectory.
34pub const ZR_TARGET: &str = "ZR_TARGET";
35/// Env var set to the target file parent dir.
36pub const ZR_TARGET_DD: &str = "ZR_TARGET_DD";
37
38/// Env var set when it needs the tool print the help text shown in `cargo zng res --tools`.
39pub const ZR_HELP: &str = "ZR_HELP";
40
41/// Env var set when running with `--verbose`.
42///
43/// Note that empty value indicates not verbose. Any value indicates verbose, currently
44/// value is "v", "vv", ...
45pub const ZR_VERBOSE: &str = "ZR_VERBOSE";
46
47/// Env var set to package.metadata.zng.about.app_id or "qualifier.org.app" in snake_case
48pub const ZR_APP_ID: &str = "ZR_APP_ID";
49/// Env var set to package.metadata.zng.about.app or package.name
50pub const ZR_APP: &str = "ZR_APP";
51/// Env var set to package.metadata.zng.about.org or the first package.authors
52pub const ZR_ORG: &str = "ZR_ORG";
53/// Env var set to package.version
54pub const ZR_VERSION: &str = "ZR_VERSION";
55/// Env var set to package.description
56pub const ZR_DESCRIPTION: &str = "ZR_DESCRIPTION";
57/// Env var set to package.homepage
58pub const ZR_HOMEPAGE: &str = "ZR_HOMEPAGE";
59/// Env var set to package.license
60pub const ZR_LICENSE: &str = "ZR_LICENSE";
61/// Env var set to package.name
62pub const ZR_PKG_NAME: &str = "ZR_PKG_NAME";
63/// Env var set to package.authors
64pub const ZR_PKG_AUTHORS: &str = "ZR_PKG_AUTHORS";
65/// Env var set to package.name in snake_case
66pub const ZR_CRATE_NAME: &str = "ZR_CRATE_NAME";
67/// Env var set to package.metadata.zng.about.qualifier or the first components `ZR_APP_ID` except the last two
68pub const ZR_QUALIFIER: &str = "ZR_QUALIFIER";
69
70/// Print the help and exit if is help request.
71pub fn help(help: &str) {
72    if env::var(ZR_HELP).is_ok() {
73        println!("{help}");
74        std::process::exit(0);
75    };
76}
77
78/// Get a `ZR_` path var.
79pub fn path(var: &str) -> PathBuf {
80    env::var(var).unwrap_or_else(|_| panic!("missing {var}")).into()
81}
82
83/// Format the path in the standard way used by cargo-zng.
84pub fn display_path(p: &Path) -> String {
85    let base = path(ZR_WORKSPACE_DIR);
86    let r = if let Ok(local) = p.strip_prefix(base) {
87        local.display().to_string()
88    } else {
89        p.display().to_string()
90    };
91
92    #[cfg(windows)]
93    return r.replace('\\', "/");
94
95    #[cfg(not(windows))]
96    r
97}
98
99fn read_line(path: &Path, expected: &str) -> io::Result<String> {
100    match read_lines(path).next() {
101        Some(r) => r.map(|(_, l)| l),
102        None => Err(io::Error::new(
103            io::ErrorKind::InvalidInput,
104            format!("expected {expected} in tool file content"),
105        )),
106    }
107}
108
109fn read_lines(path: &Path) -> impl Iterator<Item = io::Result<(usize, String)>> {
110    enum State {
111        Open(io::Result<fs::File>),
112        Lines(usize, io::Lines<io::BufReader<fs::File>>),
113        End,
114    }
115    // start -> open
116    let mut state = State::Open(fs::File::open(path));
117    std::iter::from_fn(move || {
118        loop {
119            match std::mem::replace(&mut state, State::End) {
120                State::Lines(count, mut lines) => {
121                    if let Some(l) = lines.next() {
122                        match l {
123                            // lines -> lines
124                            Ok(l) => {
125                                state = State::Lines(count + 1, lines);
126                                let test = l.trim();
127                                if !test.is_empty() && !test.starts_with('#') {
128                                    return Some(Ok((count, l)));
129                                }
130                            }
131                            // lines -> end
132                            Err(e) => {
133                                return Some(Err(e));
134                            }
135                        }
136                    }
137                }
138                State::Open(r) => match r {
139                    // open -> lines
140                    Ok(f) => state = State::Lines(1, io::BufReader::new(f).lines()),
141                    // open -> end
142                    Err(e) => return Some(Err(e)),
143                },
144                // end -> end
145                State::End => return None,
146            }
147        }
148    })
149}
150
151fn read_path(request_file: &Path) -> io::Result<PathBuf> {
152    read_line(request_file, "path").map(PathBuf::from)
153}
154
155pub(crate) fn symlink_warn(path: &Path) {
156    warn!("symlink ignored in `{}`, use cargo res tools to 'link'", path.display());
157}
158
159pub const ENV_TOOL: &str = "ZNG_RES_TOOL";
160
161macro_rules! built_in {
162    ($($tool:tt),+ $(,)?) => {
163        $(
164            mod $tool;
165            use $tool::$tool;
166        )+
167
168        pub static BUILT_INS: &[&str] = &[
169            $(stringify!($tool),)+
170        ];
171        static BUILT_IN_FNS: &[fn()] = &[
172            $($tool,)+
173        ];
174    };
175}
176// When adding new tools:
177//
178// * Position in sorted order.
179// * Add a new section for it in cargo-zng/README.md
180built_in! { apk, copy, fail, glob, l10n, rp, sfx, sh, tar, warn, z }
181
182pub(crate) use l10n::release_langs;
183pub(crate) use sh::sh_run;
184
185pub fn run() {
186    if let Ok(tool) = env::var(ENV_TOOL) {
187        // SAFETY: cargo-zng is single threaded
188        //
189        // Remove in case the tool calls cargo-zng again
190        unsafe {
191            env::remove_var(ENV_TOOL);
192        }
193
194        if let Some(i) = BUILT_INS.iter().position(|n| *n == tool.as_str()) {
195            (BUILT_IN_FNS[i])();
196            std::process::exit(0);
197        } else {
198            fatal!("`tool` is not a built-in tool");
199        }
200    }
201}