-
-
Notifications
You must be signed in to change notification settings - Fork 51
/
lib.rs
471 lines (420 loc) · 15.7 KB
/
lib.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
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
//! > Yet another `node_modules/` package manager, I guess.
//!
//! [![crates.io](https://img.shields.io/crates/v/orogene.svg)](https://crates.io/crates/orogene)
//! [![GitHub checks
//! state](https://img.shields.io/github/checks-status/orogene/orogene/main)](https://github.com/orogene/orogene/actions/workflows/ci.yml?query=branch%3Amain)
//! [![Project
//! Roadmap](https://img.shields.io/badge/Roadmap-Project%20Roadmap-informational)](https://github.com/orgs/orogene/projects/2/views/1)
//!
//! Orogene is a next-generation package manager for tools that use
//! `node_modules/`, such as bundlers, CLI tools, and Node.js-based
//! applications. It's fast, robust, and meant to be easily integrated into
//! your workflows such that you never have to worry about whether your
//! `node_modules/` is up to date.
//!
//! > *Note*: Orogene is still under heavy development and shouldn't be
//! > considered much more than a tech demo or proof of concept. Do not use in
//! > production yet.
//!
//! ### Performance
//!
//! Orogene is pretty fast and uses fewer resources than other package
//! managers! For details and benchmarks, see [the benchmarks]
//!
//! ## Contributing
//!
//! For information and help on how to contribute to Orogene, please see
//! [CONTRIBUTING.md].
//!
//! ## License
//!
//! Orogene and all its sub-crates are licensed under the terms of the [Apache
//! 2.0 License].
//!
//! [the benchmarks]: https://orogene.dev/BENCHMARKS.html
//! [CONTRIBUTING.md]: https://github.com/orogene/orogene/blob/main/CONTRIBUTING.md
//! [Apache 2.0 License]: https://github.com/orogene/orogene/blob/main/LICENSE
use std::path::{Path, PathBuf};
use async_trait::async_trait;
use clap::{Args, CommandFactory, FromArgMatches as _, Parser, Subcommand};
use directories::ProjectDirs;
use miette::{IntoDiagnostic, Result};
use oro_config::{OroConfig, OroConfigLayerExt, OroConfigOptions};
use tracing_appender::non_blocking::WorkerGuard;
use tracing_indicatif::IndicatifLayer;
use tracing_subscriber::{
filter::{Directive, LevelFilter, Targets},
fmt,
prelude::*,
EnvFilter,
};
use url::Url;
use commands::OroCommand;
mod commands;
const MAX_RETAINED_LOGS: usize = 5;
#[derive(Debug, Parser)]
#[command(author, version, about, long_about = None)]
#[command(propagate_version = true)]
pub struct Orogene {
/// Path to the project to operate on.
///
/// By default, Orogene will look up from the current working directory
/// until it finds a directory with a `package.json` file or a
/// `node_modules/` directory.
#[arg(
help_heading = "Global Options",
global = true,
long,
// NB(zkat): this is actually a dummy value. The real root default is
// handled by the config system, and is a special case.
default_value = "."
)]
root: PathBuf,
/// Registry used for unscoped packages.
#[arg(
help_heading = "Global Options",
global = true,
long,
default_value = "https://registry.npmjs.org"
)]
registry: Url,
/// Location of disk cache.
///
/// Default location varies by platform.
#[arg(help_heading = "Global Options", global = true, long)]
cache: Option<PathBuf>,
/// File to read configuration values from.
///
/// When specified, global configuration loading is disabled and
/// configuration values will only be read from this location.
#[arg(help_heading = "Global Options", global = true, long)]
config: Option<PathBuf>,
/// Log output level/directive.
///
/// Supports plain loglevels (off, error, warn, info, debug, trace) as
/// well as more advanced directives in the format
/// `target[span{field=value}]=level`.
#[arg(
help_heading = "Global Options",
global = true,
long,
default_value = "info"
)]
loglevel: String,
/// Disable all output.
#[arg(help_heading = "Global Options", global = true, long, short)]
quiet: bool,
/// Format output as JSON.
#[arg(help_heading = "Global Options", global = true, long)]
json: bool,
/// Whether to display a progress bar for long operations. Use
/// `--no-progress` to disable.
#[arg(
help_heading = "Global Options",
global = true,
long,
default_value_t = true
)]
progress: bool,
/// Whether to display emoji. Use `--no-emoji` to disable.
///
/// By default, this will show emoji when outputting to a TTY that
/// supports unicode.
#[arg(help_heading = "Global Options", global = true, long, default_value_t = supports_unicode::on(supports_unicode::Stream::Stderr))]
emoji: bool,
#[command(subcommand)]
subcommand: OroCmd,
}
impl Orogene {
fn setup_logging(&self, log_file: Option<&Path>) -> Result<Option<WorkerGuard>> {
let builder = EnvFilter::builder();
let filter = if self.quiet {
builder
.with_default_directive(LevelFilter::OFF.into())
.from_env_lossy()
} else {
let dir_str = self.loglevel.clone();
let directives = dir_str
.split(',')
.filter(|s| !s.is_empty())
.filter_map(|s| {
let dir: Result<Directive, _> = s.parse();
match dir {
Ok(dir) => Some(dir),
Err(_) => None,
}
});
let mut filter = builder.from_env_lossy();
for directive in directives {
filter = filter.add_directive(directive);
}
filter
};
let ilayer = IndicatifLayer::new();
let builder = tracing_subscriber::registry();
if let Some(log_file) = &log_file {
let targets = Targets::new()
.with_target("hyper", LevelFilter::WARN)
.with_target("reqwest", LevelFilter::WARN)
.with_target("tokio_util", LevelFilter::WARN)
.with_target("async_io", LevelFilter::WARN)
.with_target("want", LevelFilter::WARN)
.with_target("async_std", LevelFilter::WARN)
.with_target("mio", LevelFilter::WARN)
.with_target("polling", LevelFilter::WARN)
.with_default(LevelFilter::TRACE);
let logs_dir = log_file.parent().expect("must have parent");
clean_old_logs(logs_dir)?;
let file_appender = tracing_appender::rolling::never(
logs_dir,
log_file.file_name().expect("must have file name"),
);
let (non_blocking, guard) = tracing_appender::non_blocking(file_appender);
if self.quiet || !self.progress {
builder
.with(
tracing_subscriber::fmt::layer()
.without_time()
.with_target(false)
.with_filter(filter),
)
.with(
fmt::layer()
.with_timer(tracing_subscriber::fmt::time::uptime())
.with_writer(non_blocking)
.with_target(false)
.with_filter(targets),
)
.init();
} else {
builder
.with(
tracing_subscriber::fmt::layer()
.without_time()
.with_writer(ilayer.get_stderr_writer())
.with_target(false)
.with_filter(filter),
)
.with(ilayer.with_filter(LevelFilter::DEBUG))
.with(
fmt::layer()
.with_timer(tracing_subscriber::fmt::time::uptime())
.with_writer(non_blocking)
.with_target(false)
.with_filter(targets),
)
.init();
};
Ok(Some(guard))
} else {
if self.quiet || !self.progress {
builder
.with(
tracing_subscriber::fmt::layer()
.without_time()
.with_target(false)
.with_filter(filter),
)
.init();
} else {
builder
.with(
tracing_subscriber::fmt::layer()
.without_time()
.with_target(false)
.with_writer(ilayer.get_stderr_writer())
.with_filter(filter),
)
.with(ilayer)
.init();
};
Ok(None)
}
}
fn build_config(&self) -> Result<OroConfig> {
let dirs = ProjectDirs::from("", "", "orogene");
let cwd = std::env::current_dir().into_diagnostic()?;
let root = if let Some(root) = pkg_root(&cwd) {
root
} else {
&cwd
};
let mut cfg_builder = OroConfigOptions::new()
.set_default("root", &root.to_string_lossy())?
.env(true);
if let Some(cache) = dirs.as_ref().map(|d| d.cache_dir().to_owned()) {
cfg_builder = cfg_builder.set_default("cache", &cache.to_string_lossy())?;
}
let cfg = if let Some(file) = &self.config {
cfg_builder.global_config_file(Some(file.clone())).load()?
} else {
cfg_builder
.global_config_file(dirs.map(|d| d.config_dir().to_owned().join("oro.kdl")))
.pkg_root(Some(self.root.clone()))
.load()?
};
Ok(cfg)
}
pub async fn load() -> Result<()> {
let start = std::time::Instant::now();
// We have to instantiate Orogene twice: once to pick up "base" config
// options, like `root` and `config`, which affect our overall config
// parsing, and then a second time to pick up config options from the
// config file(s).
let matches = Orogene::command().with_negations().get_matches();
let oro = Orogene::from_arg_matches(&matches).into_diagnostic()?;
let config = oro.build_config()?;
let oro = Orogene::from_arg_matches(&Orogene::command().layered_matches(&config)?)
.into_diagnostic()?;
let log_file = oro
.cache
.clone()
.or_else(|| config.get::<String>("cache").ok().map(PathBuf::from))
.map(|c| c.join("_logs").join(log_file_name()));
let _guard = oro.setup_logging(log_file.as_deref())?;
oro.execute().await.map_err(|e| {
if let Some(log_file) = log_file.as_deref() {
tracing::error!("A debug log was written to {}", log_file.display());
}
e
})?;
tracing::debug!("Ran in {}s", start.elapsed().as_millis() as f32 / 1000.0);
Ok(())
}
}
fn pkg_root(start_dir: &Path) -> Option<&Path> {
for path in start_dir.ancestors() {
let node_modules = path.join("node_modules");
let pkg_json = path.join("package.json");
if node_modules.is_dir() {
return Some(path);
}
if pkg_json.is_file() {
return Some(path);
}
}
None
}
fn log_file_name() -> PathBuf {
let now = chrono::Local::now();
let prefix = format!("oro-debug-{}", now.format("%Y-%m-%d-%H-%M-%S%.3f"));
for i in 0.. {
let name = PathBuf::from(format!("{}-{}.log", prefix, i));
if !name.exists() {
return name;
}
}
PathBuf::from(format!("{}-0.log", prefix))
}
fn clean_old_logs(logs_dir: &Path) -> Result<()> {
if let Ok(readdir) = logs_dir.read_dir() {
let mut logs = readdir.filter_map(|e| e.ok()).collect::<Vec<_>>();
logs.sort_by_key(|e| e.file_name());
while logs.len() >= MAX_RETAINED_LOGS {
let log = logs.remove(0);
std::fs::remove_file(log.path()).into_diagnostic()?;
}
}
Ok(())
}
fn log_command_line() {
let mut args = std::env::args();
let mut cmd = String::new();
if let Some(arg) = args.next() {
cmd.push_str(&arg);
}
for arg in args {
cmd.push(' ');
cmd.push_str(&arg);
}
tracing::debug!("Running command: {cmd}");
}
#[derive(Debug, Subcommand)]
pub enum OroCmd {
Ping(commands::ping::PingCmd),
Restore(commands::restore::RestoreCmd),
View(commands::view::ViewCmd),
#[clap(hide = true)]
HelpMarkdown(HelpMarkdownCmd),
}
#[async_trait]
impl OroCommand for Orogene {
async fn execute(self) -> Result<()> {
log_command_line();
match self.subcommand {
OroCmd::Ping(cmd) => cmd.execute().await,
OroCmd::Restore(cmd) => cmd.execute().await,
OroCmd::View(cmd) => cmd.execute().await,
OroCmd::HelpMarkdown(cmd) => cmd.execute().await,
}
}
}
#[derive(Debug, Args)]
pub struct HelpMarkdownCmd {
#[arg()]
command_name: String,
}
#[async_trait]
impl OroCommand for HelpMarkdownCmd {
// Based on:
// https://github.com/axodotdev/cargo-dist/blob/b79a12e0942021ec304c5dcbf5e0cfcda3e6a4bb/cargo-dist/src/main.rs#L320
async fn execute(self) -> Result<()> {
let mut app = Orogene::command();
// HACK: This is a hack that forces clap to print global options for
// subcommands when calling `write_long_help` on them.
let mut _help_buf = Vec::new();
app.write_long_help(&mut _help_buf).into_diagnostic()?;
for subcmd in app.get_subcommands_mut() {
let name = subcmd.get_name();
if name != self.command_name {
continue;
}
println!("# oro {name}");
println!();
let mut help_buf = Vec::new();
subcmd.write_long_help(&mut help_buf).into_diagnostic()?;
let help = String::from_utf8(help_buf).into_diagnostic()?;
for line in help.lines() {
if let Some(usage) = line.strip_prefix("Usage: ") {
println!("### Usage:");
println!();
println!("```");
println!("oro {usage}");
println!("```");
let aliases = subcmd.get_visible_aliases().collect::<Vec<_>>();
if !aliases.is_empty() {
println!();
println!(
"[alias{}: {}]",
if aliases.len() == 1 { "" } else { "es" },
aliases.join(", ")
);
}
continue;
}
if let Some(heading) = line.strip_suffix(':') {
if !line.starts_with(' ') {
println!("### {heading}");
println!();
continue;
}
}
let line = line.trim();
if line.starts_with("- ") {
} else if line.starts_with('-') || line.starts_with('<') {
println!("#### `{line}`");
println!();
continue;
}
if line.starts_with('[') {
println!("\\{line}");
continue;
}
println!("{line}");
}
println!();
return Ok(());
}
Err(miette::miette!("Command not found: {self.command_name}"))
}
}