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
|
use crate::{
CMDCompletion, ErrorDispatcherNotFound, Next, PackageManagerSetup, ProjectManagerSetup,
ThisProgram,
display::markdown,
eformat_cargo, eprintln_cargo, hformat_cargo,
pkg_mgr::{CMDInstall, CMDListNamespace, CMDRemoveNamespace},
res::{ResCurrentDir, ResManifestPath},
};
use colored::Colorize;
use mingling::{
Program,
hook::ProgramHook,
macros::{chain, help, pack, program_setup, r_println, renderer},
res::ResExitCode,
setup::{ExitCodeSetup, GeneralRendererSetup, HelpFlagSetup, QuietFlagSetup},
};
use std::{env::current_dir, path::PathBuf, process::exit, str::FromStr};
pub fn run() {
#[cfg(windows)]
colored::control::set_virtual_terminal(true).unwrap();
// Preprocess args to handle cargo-mling invocations
let mut args: Vec<String> = std::env::args().collect();
if args.first().is_some_and(|a| a.contains("cargo-mling")) {
args[0] = "cargo-mling".to_string();
}
if args.get(1).is_some_and(|a| a == "mling") {
args.remove(1);
}
// Build program with preprocessed args
let mut program = Program::<ThisProgram>::new_with_args(args);
// Intercept Version
program.global_flag(["-V", "--version"], |_| {
eprintln!(include_str!("helps/version.txt"));
exit(0)
});
// Intercept Help
program.with_hook(ProgramHook::empty().on_post_dispatch(|c| match c {
// When dispatcher is not found
ThisProgram::ErrorDispatcherNotFound
// And user requests Help
if ThisProgram::this().user_context.help => {
// Print help
eprintln!("{}", markdown(include_str!("helps/mling_help.txt")));
exit(0)
}
_ => {}
}));
// Commands
program.with_dispatcher(CMDCompletion);
// Setups
program.with_setup(HelpFlagSetup::new(["-h", "--help"]));
program.with_setup(GeneralRendererSetup);
program.with_setup(ExitCodeSetup::default());
program.with_setup(StandardOutputSetup);
program.with_setup(PackageManagerSetup);
program.with_setup(ProjectManagerSetup);
// Resources
program.with_resource(ResCurrentDir {
path: current_dir().unwrap(),
});
let manifest_path = program.pick_global_argument(["-P", "--manifest-path"]);
program.with_resource(ResManifestPath {
raw: manifest_path,
resolved: None,
});
// Manifest Path Check
program.with_hook(ProgramHook::empty().on_post_dispatch(|c| match c {
// Skip completion (bypass completion)
ThisProgram::CompletionContext => {}
_ => {
let p = ThisProgram::this();
p.modify_res(|manifest_path: &mut ResManifestPath| {
manifest_path.resolved = Some(resolve_manifest_path(manifest_path.raw.clone()));
});
}
}));
// Execute
let quiet = program.stdout_setting.quiet;
let error_output = program.stdout_setting.error_output && !quiet;
let render_output = program.stdout_setting.render_output && !quiet;
let result = program.exec_without_render().unwrap();
if !result.is_empty() {
if result.exit_code == 0 && render_output {
println!("{}", result.trim());
} else if error_output {
eprintln!("{}", result.trim());
}
}
exit(result.exit_code);
}
#[program_setup]
fn standard_output_setup(program: &mut Program<ThisProgram>) {
program.with_setup(QuietFlagSetup::new("--silence"));
program.global_flag(["--no-error"], |program| {
program.stdout_setting.error_output = false;
});
program.global_flag(["--no-result"], |program| {
program.stdout_setting.render_output = false;
});
program.global_flag(["--silence", "--quiet"], |program| {
program.stdout_setting.quiet = true;
});
}
fn resolve_manifest_path(provided: Option<String>) -> PathBuf {
let p = ThisProgram::this();
let disable_error_output =
// --no-error
!p.stdout_setting.error_output ||
// or --quiet/--silence
p.stdout_setting.quiet;
if let Some(path) = provided {
let p = PathBuf::from_str(&path).unwrap();
if p.is_dir() {
let candidate = p.join("Cargo.toml");
if candidate.exists() {
return candidate;
}
if !disable_error_output {
eprintln_cargo!("`{}` is not a crate root", p.display());
}
exit(1);
}
return p;
}
// Walk up from current directory to find nearest Cargo.toml
let mut dir = current_dir().unwrap();
loop {
let candidate = dir.join("Cargo.toml");
if candidate.exists() {
return candidate;
}
if !dir.pop() {
// Reached filesystem root without finding Cargo.toml
if !disable_error_output {
eprintln_cargo!("`{}` is not a crate root", current_dir().unwrap().display());
}
exit(1);
}
}
}
pack!(ResultMlingHelp = ());
pack!(ResultUnknownCommand = String);
#[chain]
pub fn handle_error_dispatcher_not_found(err: ErrorDispatcherNotFound) -> Next {
if err.is_empty() {
ResultMlingHelp::default().to_render()
} else {
ResultUnknownCommand::new(err.join(" ")).to_render()
}
}
#[renderer]
pub fn render_mling_help(_prev: ResultMlingHelp, ec: &mut ResExitCode) {
r_println!("{}", markdown(include_str!("helps/mling_help.txt")));
ec.exit_code = 0;
}
#[renderer]
pub fn render_unknown_command(prev: ResultUnknownCommand, ec: &mut ResExitCode) {
r_println!(
"{}",
eformat_cargo!("no such command: `{}`", prev.bright_yellow().bold())
);
r_println!();
r_println!(
"{}",
hformat_cargo!("view all commands with `cargo help mling`")
);
ec.exit_code = 101;
}
|