-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathcli.rs
149 lines (126 loc) · 4.5 KB
/
cli.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
//! parse config from config.toml and read work-dir argument if provided.
//!
//!
//! Arguments:
//! - __work-dir__(optional): specify the work dir, where to download crates, rust toolchains and storage logs, default: $HOME/.freighter
//!
//! example:
//!
//! ```bash
//! freighter --work-dir /mnt/data/
//! or
//! freighter -c /mnt/data/
//! ```
//!
use std::path::{PathBuf, Path};
use std::str::FromStr;
use clap::{arg, crate_version, ArgMatches};
use log4rs::append::console::ConsoleAppender;
use log4rs::append::rolling_file::policy::compound::roll::delete::DeleteRoller;
use log4rs::append::rolling_file::policy::compound::trigger::size::SizeTrigger;
use log4rs::append::rolling_file::policy::compound::CompoundPolicy;
use log4rs::append::rolling_file::RollingFileAppender;
use log4rs::config::runtime::Config as Log4rsConfig;
use log4rs::config::Logger;
use log4rs::config::{Appender, Root};
use log4rs::encode::pattern::PatternEncoder;
use tracing::log::LevelFilter;
use crate::commands::{self};
use crate::config::{Config, LogConfig};
use crate::errors::{FreightResult, FreighterError};
///
///
///
///
///
pub type App = clap::Command;
///
///
pub fn main(config: &mut Config) -> FreightResult {
// log4rs::init_file("log4rs.yaml", Default::default()).unwrap();
let args = cli().try_get_matches().unwrap_or_else(|e| e.exit());
let config_parent = args.get_one::<String>("config-path").cloned().map(PathBuf::from);
let mut config = config.load(config_parent);
let (cmd, subcommand_args) = match args.subcommand() {
Some((cmd, args)) => (cmd, args),
_ => {
// No subcommand provided.
cli().print_help()?;
return Ok(());
}
};
execute_subcommand(&mut config, cmd, subcommand_args)
}
///
///
fn cli() -> App {
let usage = "freighter [SUBCOMMAND]";
App::new("freighter")
.version(crate_version!())
.disable_colored_help(true)
.disable_help_subcommand(true)
.override_usage(usage)
.author("Open Rust Initiative")
.arg(arg!(-c --"config-path" <FILE> "specify the config path, default: $HOME/freighter/config.toml")
)
.help_template(
"\
Freighter - A crate registry from the Open Rust Initiative Community
USAGE:
{usage}
Some common freighter commands are (see all commands with --list):
crates Sync the index and crate files from the upstream to local, cloud or registry
rustup Sync the rustup files from the upstream to local, cloud or registry
channel Sync the toolchain files from the upstream to local, cloud or registry
server Start git and file http server
See 'freighter help <command>' for more information on a specific command.\n"
)
.subcommands(commands::builtin())
}
///
///
pub fn execute_subcommand(config: &mut Config, cmd: &str, args: &ArgMatches) -> FreightResult {
if let Some(f) = commands::builtin_exec(cmd) {
f(config, args)
} else {
Err(FreighterError::unknown_command(cmd.to_string()))
}
}
/// read values(log format encoder, log limit and level) from config file
/// and then initialize config for log4rs, log will preserve in /log_path/log by default
pub fn init_log(config: &LogConfig, log_path: &Path, sub_command: &str) -> FreightResult {
// attach file name
let binding = log_path.join(format!("{}.log", sub_command));
let log_path = binding.to_str().unwrap();
let level = LevelFilter::from_str(&config.level).unwrap();
let encoder = PatternEncoder::new(&config.encoder);
let stdout = ConsoleAppender::builder()
.encoder(Box::new(encoder.clone()))
.build();
let policy = CompoundPolicy::new(
Box::new(SizeTrigger::new(config.limit * 1024 * 1024)),
Box::<DeleteRoller>::default(),
);
let file = RollingFileAppender::builder()
.encoder(Box::new(encoder))
.build(log_path, Box::new(policy))
.unwrap();
let log4rs_config = Log4rsConfig::builder()
.appender(Appender::builder().build("stdout", Box::new(stdout)))
.appender(Appender::builder().build("file", Box::new(file)))
.logger(
Logger::builder()
.appender("file")
.additive(false)
.build("app::file", level),
)
.build(
Root::builder()
.appender("stdout")
.appender("file")
.build(level),
)
.unwrap();
log4rs::init_config(log4rs_config).unwrap();
Ok(())
}