-
-
Notifications
You must be signed in to change notification settings - Fork 51
/
apply.rs
399 lines (350 loc) Β· 12.8 KB
/
apply.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
use std::path::{Path, PathBuf};
use async_trait::async_trait;
use clap::Args;
use indicatif::ProgressStyle;
use miette::{IntoDiagnostic, Result};
use node_maintainer::{NodeMaintainer, NodeMaintainerOptions};
use rand::seq::IteratorRandom;
use tracing::{Instrument, Span};
use tracing_indicatif::span_ext::IndicatifSpanExt;
use url::Url;
use crate::commands::OroCommand;
/// Applies the current project's requested dependencies to `node_modules/`,
/// adding, removing, and updating dependencies as needed. This command is
/// intended to be an idempotent way to make sure your `node_modules` is in
/// the right state to execute, based on your declared dependencies.
#[derive(Debug, Args)]
#[clap(visible_aliases(["a", "ap", "app"]))]
pub struct ApplyCmd {
/// When extracting packages, prefer to copy files files instead of
/// linking them.
///
/// This option has no effect if hard linking fails (for example, if the
/// cache is on a different drive), or if the project is on a filesystem
/// that supports Copy-on-Write (zfs, btrfs, APFS (macOS), etc).
#[arg(long)]
prefer_copy: bool,
/// Validate the integrity of installed files.
///
/// When this is true, orogene will verify all files extracted from the
/// cache, as well as verify that any files in the existing `node_modules`
/// are unmodified. If verification fails, the packages will be
/// reinstalled.
#[arg(short, long)]
validate: bool,
/// Whether to skip restoring packages into `node_modules` and just
/// resolve the tree and write the lockfile.
#[arg(long)]
lockfile_only: bool,
/// Skip running install scripts.
#[arg(long)]
ignore_scripts: bool,
/// Default dist-tag to use when resolving package versions.
#[arg(long, default_value = "latest")]
default_tag: String,
/// Controls number of concurrent operations during various apply steps
/// (resolution fetches, extractions, etc).
///
/// Tuning this might help reduce memory usage (if lowered), or improve
/// performance (if increased).
#[arg(long, default_value_t = node_maintainer::DEFAULT_CONCURRENCY)]
concurrency: usize,
/// Controls number of concurrent script executions while running
/// `run_script`.
///
/// This option is separate from `concurrency` because executing
/// concurrent scripts is a much heavier operation.
#[arg(long, default_value_t = node_maintainer::DEFAULT_SCRIPT_CONCURRENCY)]
script_concurrency: usize,
/// Whether to write the lockfile after operations complete. Disable by
/// using `--no-lockfile`.
///
/// Note that lockfiles are only written after all operations complete
/// successfully.
#[arg(long)]
lockfile: bool,
/// Use the hoisted installation mode, where all dependencies and their
/// transitive dependencies are installed as high up in the `node_modules`
/// tree as possible.
///
/// This can potentially mean that packages have access to dependencies
/// they did not specify in their package.json, but it might be useful for
/// compatibility.
///
/// By default, dependencies are installed in "isolated" mode, using a
/// symlink/junction structure to simulate a dependency tree.
#[arg(long)]
hoisted: bool,
#[arg(from_global)]
registry: Url,
#[arg(from_global)]
scoped_registries: Vec<(String, Url)>,
#[arg(from_global)]
json: bool,
#[arg(from_global)]
root: PathBuf,
#[arg(from_global)]
cache: Option<PathBuf>,
#[arg(from_global)]
emoji: bool,
}
#[async_trait]
impl OroCommand for ApplyCmd {
async fn execute(self) -> Result<()> {
let total_time = std::time::Instant::now();
let root = &self.root;
let maintainer = self.resolve(root, self.configured_maintainer()).await?;
if !self.lockfile_only {
self.prune(&maintainer).await?;
self.extract(&maintainer).await?;
self.rebuild(&maintainer).await?;
} else {
tracing::info!(
"{}Skipping installing node_modules/, only writing lockfile.",
self.emoji_package()
);
}
if self.lockfile {
maintainer
.write_lockfile(root.join("package-lock.kdl"))
.await?;
}
tracing::info!(
"{}Wrote lockfile to package-lock.kdl.",
self.emoji_writing()
);
tracing::info!(
"{}Done in {}s. {}",
self.emoji_tada(),
total_time.elapsed().as_millis() as f32 / 1000.0,
hackerish_encouragement()
);
Ok(())
}
}
impl ApplyCmd {
fn configured_maintainer(&self) -> NodeMaintainerOptions {
let root = &self.root;
let mut nm = NodeMaintainerOptions::new();
nm = nm
.registry(self.registry.clone())
.default_tag(&self.default_tag)
.concurrency(self.concurrency)
.script_concurrency(self.script_concurrency)
.root(root)
.prefer_copy(self.prefer_copy)
.validate(self.validate)
.hoisted(self.hoisted)
.on_resolution_added(move || {
Span::current().pb_inc_length(1);
})
.on_resolve_progress(move |pkg| {
let span = Span::current();
span.pb_inc(1);
span.pb_set_message(&format!("{:?}", pkg.resolved()));
})
.on_prune_progress(move |path| {
let span = Span::current();
span.pb_inc(1);
span.pb_set_message(&format!("{}", path.display()));
})
.on_extract_progress(move |pkg| {
let span = Span::current();
span.pb_inc(1);
span.pb_set_message(&format!("{:?}", pkg.resolved()))
})
.on_script_start(|pkg, event| {
let span = Span::current();
span.pb_set_style(
&ProgressStyle::default_bar()
.template(&format!(
"{{span_child_prefix}}{{spinner}} {}::{event} ({{elapsed}}): {{wide_msg:.dim}}",
pkg.name(),
))
.unwrap(),
);
})
.on_script_line(|line| {
let span = Span::current();
span.pb_inc(1);
span.pb_set_message(line);
});
for (scope, registry) in &self.scoped_registries {
nm = nm.scope_registry(scope, registry.clone());
}
if let Some(cache) = self.cache.as_deref() {
nm = nm.cache(cache);
}
nm
}
async fn resolve(&self, root: &Path, builder: NodeMaintainerOptions) -> Result<NodeMaintainer> {
// Set up progress bar and timing stuff.
let resolve_time = std::time::Instant::now();
let resolve_span = tracing::debug_span!("resolving");
resolve_span.pb_set_style(
&ProgressStyle::default_bar()
.template(&format!(
"{}Resolving {}",
self.emoji_magnifying_glass(),
"{bar:40} [{pos}/{len}] {wide_msg:.dim}"
))
.unwrap(),
);
resolve_span.pb_set_length(0);
let resolve_span_enter = resolve_span.enter();
// Actually do a resolve.
let resolved_nm = builder
.resolve_spec(root.canonicalize().into_diagnostic()?.to_string_lossy())
.await?;
// Wrap up progress bar and print messages.
std::mem::drop(resolve_span_enter);
std::mem::drop(resolve_span);
tracing::info!(
"{}Resolved {} packages in {}s.",
self.emoji_magnifying_glass(),
resolved_nm.package_count(),
resolve_time.elapsed().as_millis() as f32 / 1000.0
);
Ok(resolved_nm)
}
async fn prune(&self, maintainer: &NodeMaintainer) -> Result<usize> {
// Set up progress bar and timing stuff.
let prune_time = std::time::Instant::now();
let prune_span = tracing::debug_span!("prune");
prune_span.pb_set_style(
&ProgressStyle::default_bar()
.template(&format!(
"{}Pruning extraneous {}",
self.emoji_broom(),
"{bar:40} [{pos}] {wide_msg:.dim}"
))
.unwrap(),
);
prune_span.pb_set_length(maintainer.package_count() as u64);
let prune_span_enter = prune_span.enter();
// Actually do the pruning.
let pruned = maintainer.prune().await?;
// Wrap up progress bar and message.
std::mem::drop(prune_span_enter);
std::mem::drop(prune_span);
tracing::info!(
"{}Pruned {pruned} packages in {}s.",
self.emoji_broom(),
prune_time.elapsed().as_millis() as f32 / 1000.0
);
Ok(pruned)
}
async fn extract(&self, maintainer: &NodeMaintainer) -> Result<usize> {
// Set up progress bar and timing stuff.
let extract_time = std::time::Instant::now();
let extract_span = tracing::debug_span!("extract");
extract_span.pb_set_style(
&ProgressStyle::default_bar()
.template(&format!(
"{}Extracting {}",
self.emoji_package(),
"{bar:40} [{pos}/{len}] {wide_msg:.dim}"
))
.unwrap(),
);
extract_span.pb_set_length(maintainer.package_count() as u64);
let extract_span_enter = extract_span.enter();
// Actually do the extraction.
let extracted = maintainer.extract().await?;
// Wrap up progress bar and message.
std::mem::drop(extract_span_enter);
std::mem::drop(extract_span);
tracing::info!(
"{}Extracted {extracted} package{} in {}s.",
self.emoji_package(),
if extracted == 1 { "" } else { "s" },
extract_time.elapsed().as_millis() as f32 / 1000.0
);
Ok(extracted)
}
async fn rebuild(&self, maintainer: &NodeMaintainer) -> Result<()> {
let script_time = std::time::Instant::now();
let script_span = if self.ignore_scripts {
tracing::debug_span!("Building")
} else {
tracing::info_span!("Building")
};
if !self.ignore_scripts {
script_span.pb_set_style(
&ProgressStyle::default_bar()
.template(&format!(
"{{spinner}} {}Running scripts {{wide_msg:.dim}}",
self.emoji_run(),
))
.unwrap(),
);
}
maintainer
.rebuild(self.ignore_scripts)
.instrument(script_span)
.await?;
if self.ignore_scripts {
tracing::info!(
"{}Linked script bins in {}s.",
self.emoji_link(),
script_time.elapsed().as_millis() as f32 / 1000.0
);
} else {
tracing::info!(
"{}Ran lifecycle scripts in {}s.",
self.emoji_run(),
script_time.elapsed().as_millis() as f32 / 1000.0
);
}
Ok(())
}
fn emoji_run(&self) -> &'static str {
self.maybe_emoji("π ")
}
fn emoji_package(&self) -> &'static str {
self.maybe_emoji("π¦ ")
}
fn emoji_magnifying_glass(&self) -> &'static str {
self.maybe_emoji("π ")
}
fn emoji_broom(&self) -> &'static str {
self.maybe_emoji("π§Ή ")
}
fn emoji_writing(&self) -> &'static str {
self.maybe_emoji("π ")
}
fn emoji_tada(&self) -> &'static str {
self.maybe_emoji("π ")
}
fn emoji_link(&self) -> &'static str {
self.maybe_emoji("π ")
}
fn maybe_emoji(&self, emoji: &'static str) -> &'static str {
if self.emoji {
emoji
} else {
""
}
}
}
// Inspired and brazenly taken from SLIME:
// https://github.com/slime/slime/blob/e193bc5f3431a2f71f1d7a0e3f28e6dc4dd5de2d/slime.el#L1360-L1375
fn hackerish_encouragement() -> &'static str {
let encouragements = [
"Let the hacking commence!",
"Hacks and glory await!",
"Hack and be merry!",
"Your hacking starts... NOW!",
"May the source be with you.",
"Fasterthanlime-fame is but a hack away!",
"Hack the planet!",
"Hackuna Matata~",
"Are we JavaScript yet?",
"[Scientifically-proven optimal words of hackerish encouragement here]",
];
let mut rng = rand::thread_rng();
encouragements
.iter()
.choose(&mut rng)
.expect("Iterator should not be empty.")
}