cargo_zng/
util.rs

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
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
use std::{
    collections::HashMap,
    fs,
    io::{self, BufReader, Read},
    path::{Path, PathBuf},
    process::{Command, Stdio},
    sync::atomic::AtomicBool,
};

use semver::{Version, VersionReq};
use serde::Deserialize;

/// Print warning message.
macro_rules! warn {
    ($($format_args:tt)*) => {
        if $crate::util::deny_warnings() {
            error!($($format_args)*);
        }else {
            eprintln!("{} {}", $crate::util::WARN_PREFIX, format_args!($($format_args)*));
        }
    };
}

pub fn deny_warnings() -> bool {
    std::env::var("RUSTFLAGS")
        .map(|f| {
            ["--deny=warnings", "-Dwarnings", "-D warnings", "--deny warnings"]
                .iter()
                .any(|d| f.contains(d))
        })
        .unwrap_or(false)
}

/// Print error message and flags the current process as failed.
///
/// Note that this does not exit the process, use `fatal!` to exit.
macro_rules! error {
    ($($format_args:tt)*) => {
        {
            $crate::util::set_failed_run(true);
            eprintln!("{} {}", $crate::util::ERROR_PREFIX, format_args!($($format_args)*));
        }
    };
}

pub static WARN_PREFIX: &str = color_print::cstr!("<bold><yellow>warning</yellow>:</bold>");
pub static ERROR_PREFIX: &str = color_print::cstr!("<bold><red>error</red>:</bold>");

/// Print error message and exit the current process with error code.
macro_rules! fatal {
    ($($format_args:tt)*) => {
        {
            error!($($format_args)*);
            $crate::util::exit();
        }
    };
}

static RUN_FAILED: AtomicBool = AtomicBool::new(false);

/// Gets if the current process will exit with error code.
pub fn is_failed_run() -> bool {
    RUN_FAILED.load(std::sync::atomic::Ordering::SeqCst)
}

/// Sets if the current process will exit with error code.
pub fn set_failed_run(failed: bool) {
    RUN_FAILED.store(failed, std::sync::atomic::Ordering::SeqCst);
}

/// Exit the current process, with error code `102` if [`is_failed_run`].
pub fn exit() -> ! {
    if is_failed_run() {
        std::process::exit(102)
    } else {
        std::process::exit(0)
    }
}

/// Run the command with args, inherits stdout and stderr.
pub fn cmd(line: &str, args: &[&str], env: &[(&str, &str)]) -> io::Result<()> {
    cmd_impl(line, args, env, false)
}
/// Run the command with args.
pub fn cmd_silent(line: &str, args: &[&str], env: &[(&str, &str)]) -> io::Result<()> {
    cmd_impl(line, args, env, true)
}
fn cmd_impl(line: &str, args: &[&str], env: &[(&str, &str)], silent: bool) -> io::Result<()> {
    let mut line_parts = line.split(' ');
    let program = line_parts.next().expect("expected program to run");
    let mut cmd = Command::new(program);
    cmd.args(
        line_parts
            .map(|a| {
                let a = a.trim();
                if a.starts_with('"') {
                    a.trim_matches('"')
                } else {
                    a
                }
            })
            .filter(|a| !a.is_empty()),
    );
    cmd.args(args.iter().filter(|a| !a.is_empty()));
    for (key, val) in env.iter() {
        cmd.env(key, val);
    }

    if silent {
        let output = cmd.output()?;
        if output.status.success() {
            Ok(())
        } else {
            let mut cmd = format!("cmd failed: {line}");
            for arg in args {
                cmd.push(' ');
                cmd.push_str(arg);
            }
            cmd.push('\n');
            cmd.push_str(&String::from_utf8_lossy(&output.stderr));
            Err(io::Error::new(io::ErrorKind::Other, cmd))
        }
    } else {
        let status = cmd.status()?;
        if status.success() {
            Ok(())
        } else {
            let mut cmd = format!("cmd failed: {line}");
            for arg in args {
                cmd.push(' ');
                cmd.push_str(arg);
            }
            Err(io::Error::new(io::ErrorKind::Other, cmd))
        }
    }
}

pub fn workspace_dir() -> Option<PathBuf> {
    let output = std::process::Command::new("cargo")
        .arg("locate-project")
        .arg("--workspace")
        .arg("--message-format=plain")
        .output()
        .ok()?;

    if output.status.success() {
        let cargo_path = Path::new(std::str::from_utf8(&output.stdout).unwrap().trim());
        Some(cargo_path.parent().unwrap().to_owned())
    } else {
        None
    }
}

pub fn ansi_enabled() -> bool {
    std::env::var("NO_COLOR").is_err()
}

pub fn clean_value(value: &str, required: bool) -> io::Result<String> {
    let mut first_char = false;
    let clean_value: String = value
        .chars()
        .filter(|c| {
            if first_char {
                first_char = c.is_ascii_alphabetic();
                first_char
            } else {
                *c == ' ' || *c == '-' || *c == '_' || c.is_ascii_alphanumeric()
            }
        })
        .collect();
    let clean_value = clean_value.trim().to_owned();

    if required && clean_value.is_empty() {
        if clean_value.is_empty() {
            return Err(io::Error::new(
                io::ErrorKind::InvalidInput,
                format!("cannot derive clean value from `{value}`, must contain at least one ascii alphabetic char"),
            ));
        }
        if clean_value.len() > 62 {
            return Err(io::Error::new(
                io::ErrorKind::InvalidInput,
                format!("cannot derive clean value from `{value}`, must contain <= 62 ascii alphanumeric chars"),
            ));
        }
    }
    Ok(clean_value)
}

pub fn manifest_path_from_package(package: &str) -> Option<String> {
    let metadata = match Command::new("cargo")
        .args(["metadata", "--format-version", "1", "--no-deps"])
        .stderr(Stdio::inherit())
        .output()
    {
        Ok(m) => {
            if !m.status.success() {
                fatal!("cargo metadata error")
            }
            String::from_utf8_lossy(&m.stdout).into_owned()
        }
        Err(e) => fatal!("cargo metadata error, {e}"),
    };

    #[derive(Deserialize)]
    struct Metadata {
        packages: Vec<Package>,
    }
    #[derive(Deserialize)]
    struct Package {
        name: String,
        manifest_path: String,
    }
    let metadata: Metadata = serde_json::from_str(&metadata).unwrap_or_else(|e| fatal!("unexpected cargo metadata format, {e}"));

    for p in metadata.packages {
        if p.name == package {
            return Some(p.manifest_path);
        }
    }
    None
}

/// Workspace crates Cargo.toml paths.
pub fn workspace_manifest_paths() -> Vec<PathBuf> {
    let metadata = match Command::new("cargo")
        .args(["metadata", "--format-version", "1", "--no-deps"])
        .stderr(Stdio::inherit())
        .output()
    {
        Ok(m) => {
            if !m.status.success() {
                fatal!("cargo metadata error")
            }
            String::from_utf8_lossy(&m.stdout).into_owned()
        }
        Err(e) => fatal!("cargo metadata error, {e}"),
    };

    #[derive(Deserialize)]
    struct Metadata {
        packages: Vec<Package>,
    }
    #[derive(Debug, Deserialize)]
    struct Package {
        manifest_path: PathBuf,
    }

    let metadata: Metadata = serde_json::from_str(&metadata).unwrap_or_else(|e| fatal!("unexpected cargo metadata format, {e}"));

    metadata.packages.into_iter().map(|p| p.manifest_path).collect()
}

/// Workspace root and dependencies of manifest_path
pub fn dependencies(manifest_path: &str) -> (PathBuf, Vec<DependencyManifest>) {
    let metadata = match Command::new("cargo")
        .args(["metadata", "--format-version", "1", "--manifest-path"])
        .arg(manifest_path)
        .stderr(Stdio::inherit())
        .output()
    {
        Ok(m) => {
            if !m.status.success() {
                fatal!("cargo metadata error")
            }
            String::from_utf8_lossy(&m.stdout).into_owned()
        }
        Err(e) => fatal!("cargo metadata error, {e}"),
    };

    #[derive(Deserialize)]
    struct Metadata {
        packages: Vec<Package>,
        workspace_root: PathBuf,
    }
    #[derive(Debug, Deserialize)]
    struct Package {
        name: String,
        version: Version,
        dependencies: Vec<Dependency>,
        manifest_path: String,
    }
    #[derive(Debug, Deserialize)]
    struct Dependency {
        name: String,
        kind: Option<String>,
        req: VersionReq,
    }

    let metadata: Metadata = serde_json::from_str(&metadata).unwrap_or_else(|e| fatal!("unexpected cargo metadata format, {e}"));

    let manifest_path = dunce::canonicalize(manifest_path).unwrap();

    let mut dependencies: &[Dependency] = &[];

    for pkg in &metadata.packages {
        let pkg_path = Path::new(&pkg.manifest_path);
        if pkg_path == manifest_path {
            dependencies = &pkg.dependencies;
            break;
        }
    }
    if !dependencies.is_empty() {
        let mut map = HashMap::new();
        for pkg in &metadata.packages {
            map.entry(pkg.name.as_str()).or_insert_with(Vec::new).push((&pkg.version, pkg));
        }

        let mut r = vec![];
        fn collect(map: &mut HashMap<&str, Vec<(&Version, &Package)>>, dependencies: &[Dependency], r: &mut Vec<DependencyManifest>) {
            for dep in dependencies {
                if dep.kind.is_some() {
                    // skip build/dev-dependencies
                    continue;
                }
                if let Some(versions) = map.remove(dep.name.as_str()) {
                    for (version, pkg) in versions.iter() {
                        if dep.req.comparators.is_empty() || dep.req.matches(version) {
                            r.push(DependencyManifest {
                                name: pkg.name.clone(),
                                version: pkg.version.clone(),
                                manifest_path: pkg.manifest_path.as_str().into(),
                            });

                            // collect dependencies of dependencies
                            collect(map, &pkg.dependencies, r)
                        }
                    }
                }
            }
        }
        collect(&mut map, dependencies, &mut r);
        return (metadata.workspace_root, r);
    }

    (metadata.workspace_root, vec![])
}

pub struct DependencyManifest {
    pub name: String,
    pub version: Version,
    pub manifest_path: PathBuf,
}

pub fn check_or_create_dir(check: bool, path: impl AsRef<Path>) -> io::Result<()> {
    if check {
        let path = path.as_ref();
        if !path.is_dir() {
            fatal!("expected `{}` dir", path.display());
        }
        Ok(())
    } else {
        fs::create_dir(path)
    }
}

pub fn check_or_create_dir_all(check: bool, path: impl AsRef<Path>) -> io::Result<()> {
    if check {
        let path = path.as_ref();
        if !path.is_dir() {
            fatal!("expected `{}` dir", path.display());
        }
        Ok(())
    } else {
        fs::create_dir_all(path)
    }
}

pub fn check_or_write(check: bool, path: impl AsRef<Path>, contents: impl AsRef<[u8]>, verbose: bool) -> io::Result<()> {
    let path = path.as_ref();
    let contents = contents.as_ref();
    if check {
        if !path.is_file() {
            fatal!("expected `{}` file", path.display());
        }
        let file = fs::File::open(path).unwrap_or_else(|e| fatal!("cannot read `{}`, {e}", path.display()));
        let mut bytes = vec![];
        BufReader::new(file)
            .read_to_end(&mut bytes)
            .unwrap_or_else(|e| fatal!("cannot read `{}`, {e}", path.display()));

        if bytes != contents {
            fatal!("file `{}` contents changed", path.display());
        } else if verbose {
            println!("file `{}` contents did not change", path.display());
        }

        Ok(())
    } else {
        if verbose {
            println!("writing `{}`", path.display());
        }
        fs::write(path, contents)
    }
}

pub fn check_or_copy(check: bool, from: impl AsRef<Path>, to: impl AsRef<Path>, verbose: bool) -> io::Result<u64> {
    let from = from.as_ref();
    let to = to.as_ref();
    if check {
        if !to.is_file() {
            fatal!("expected `{}` file", to.display());
        }

        let mut bytes = vec![];
        for path in [from, to] {
            let file = fs::File::open(path).unwrap_or_else(|e| fatal!("cannot read `{}`, {e}", path.display()));
            let mut b = vec![];
            BufReader::new(file)
                .read_to_end(&mut b)
                .unwrap_or_else(|e| fatal!("cannot read `{}`, {e}", path.display()));

            bytes.push(b);
        }

        if bytes[0] != bytes[1] {
            fatal!("file `{}` contents changed", to.display());
        } else if verbose {
            println!("file `{}` contents did not change", to.display());
        }

        Ok(bytes[1].len() as u64)
    } else {
        if verbose {
            println!("copying\n  from: `{}`\n    to: `{}`", from.display(), to.display());
        }
        fs::copy(from, to)
    }
}