cargo_pants/
common.rs

1// Copyright 2021 Sonatype and Glenn Mohre.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15use dirs::home_dir;
16use std::fs::OpenOptions;
17use std::sync::Mutex;
18use tracing_subscriber::filter::EnvFilter;
19
20pub static CARGO_DEFAULT_TOMLFILE: &str = "Cargo.toml";
21
22pub fn banner(name: String, version: String) {
23    println!("{}", std::include_str!("banner.txt"));
24    println!("{} version: {}", name, version);
25}
26
27pub fn print_dev_dependencies_info(dev: bool) {
28    if dev {
29        println!("Scanning all dependencies for project due to use of --dev");
30    } else {
31        println!("Scanning only runtime dependencies for project (use --dev to include all dependencies)");
32    }
33    println!();
34}
35
36pub fn parse_log_level(verbosity: u64) -> EnvFilter {
37    match verbosity {
38        0 => env_filter_at_level("error"),
39        1 => env_filter_at_level("warn"),
40        2 => env_filter_at_level("info"),
41        3 => env_filter_at_level("debug"),
42        4 => env_filter_at_level("trace"),
43        _ => EnvFilter::from_default_env(),
44    }
45}
46
47fn env_filter_at_level(level: &str) -> EnvFilter {
48    EnvFilter::default()
49        .add_directive(
50            format!("cargo_pants={}", level)
51                .parse()
52                .expect("Failed to parse level directive"),
53        )
54        .add_directive(
55            format!("cargo_iq={}", level)
56                .parse()
57                .expect("Failed to parse level directive"),
58        )
59}
60
61pub fn construct_logger(folder: &str, log_level_filter: EnvFilter) {
62    let home = home_dir().unwrap();
63
64    let log_folder = home.join(folder);
65    std::fs::create_dir_all(&log_folder).expect("Could not create the log folder");
66
67    let log_location = log_folder.join("cargo-pants.combined.log");
68
69    let log_file = OpenOptions::new()
70        .create(true)
71        .append(true)
72        .open(&log_location)
73        .expect("Failed to open log file for writing");
74
75    tracing_subscriber::fmt()
76        .with_env_filter(log_level_filter)
77        .json()
78        .with_writer(Mutex::new(log_file))
79        .init();
80
81    println!();
82    println!("Logging to: {:?}", log_location.clone());
83    println!();
84}