-
-
Notifications
You must be signed in to change notification settings - Fork 17
Expand file tree
/
Copy pathapp.rs
More file actions
346 lines (308 loc) · 12.6 KB
/
app.rs
File metadata and controls
346 lines (308 loc) · 12.6 KB
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
pub mod sub;
pub use sub::Sub;
use crate::{
args::{Args, ColorWhen, Quantity, Threads},
bytes_format::BytesFormat,
get_size::{GetApparentSize, GetSize},
hardlink,
json_data::{JsonData, JsonDataBody, JsonShared, JsonTree},
ls_colors::LsColors,
reporter::{ErrorOnlyReporter, ErrorReport, ProgressAndErrorReporter, ProgressReport},
runtime_error::RuntimeError,
size,
visualizer::{BarAlignment, ColumnWidthDistribution, Direction, Visualizer},
};
use clap::Parser;
use hdd::any_path_is_in_hdd;
use pipe_trait::Pipe;
use std::{
io::{stdin, stdout, IsTerminal},
time::Duration,
};
use sub::JsonOutputParam;
use sysinfo::Disks;
#[cfg(unix)]
use crate::get_size::{GetBlockCount, GetBlockSize};
/// The main application.
pub struct App {
/// The CLI arguments.
args: Args,
}
impl App {
/// Initialize the application from the environment.
pub fn from_env() -> Self {
App {
args: Args::parse(),
}
}
/// Run the application.
pub fn run(mut self) -> Result<(), RuntimeError> {
// DYNAMIC DISPATCH POLICY:
//
// Errors rarely occur, therefore, using dynamic dispatch to report errors have an acceptable
// impact on performance.
//
// The other operations which are invoked frequently should not utilize dynamic dispatch.
let column_width_distribution = self.args.column_width_distribution();
if self.args.json_input {
if !self.args.files.is_empty() {
return Err(RuntimeError::JsonInputArgConflict);
}
let Args {
bytes_format,
top_down,
align_right,
..
} = self.args;
let direction = Direction::from_top_down(top_down);
let bar_alignment = BarAlignment::from_align_right(align_right);
let body = stdin()
.pipe(serde_json::from_reader::<_, JsonData>)
.map_err(RuntimeError::DeserializationFailure)?
.body;
trait VisualizeJsonTree: size::Size + Into<u64> + Send {
fn visualize_json_tree(
tree: JsonTree<Self>,
bytes_format: Self::DisplayFormat,
column_width_distribution: ColumnWidthDistribution,
direction: Direction,
bar_alignment: BarAlignment,
) -> Result<String, RuntimeError> {
let JsonTree { tree, shared } = tree;
let data_tree = tree
.par_try_into_tree()
.map_err(|error| RuntimeError::InvalidInputReflection(error.to_string()))?;
let visualizer = Visualizer {
data_tree: &data_tree,
bytes_format,
column_width_distribution,
direction,
bar_alignment,
coloring: None,
};
let JsonShared { details, summary } = shared;
let summary = summary.or_else(|| details.map(|details| details.summarize()));
let visualization = if let Some(summary) = summary {
let summary = summary.display(bytes_format);
// visualizer already ends with "\n"
format!("{visualizer}{summary}\n")
} else {
visualizer.to_string()
};
Ok(visualization)
}
}
impl<Size: size::Size + Into<u64> + Send> VisualizeJsonTree for Size {}
macro_rules! visualize {
($tree:expr, $bytes_format:expr) => {
VisualizeJsonTree::visualize_json_tree(
$tree,
$bytes_format,
column_width_distribution,
direction,
bar_alignment,
)
};
}
let visualization = match body {
JsonDataBody::Bytes(tree) => visualize!(tree, bytes_format),
JsonDataBody::Blocks(tree) => visualize!(tree, ()),
}?;
print!("{visualization}"); // it already ends with "\n", println! isn't needed here.
return Ok(());
}
#[cfg(not(unix))]
if self.args.deduplicate_hardlinks {
return crate::runtime_error::UnsupportedFeature::DeduplicateHardlink
.pipe(RuntimeError::UnsupportedFeature)
.pipe(Err);
}
let threads = match self.args.threads {
Threads::Auto => {
let disks = Disks::new_with_refreshed_list();
if any_path_is_in_hdd::<hdd::RealApi>(&self.args.files, &disks) {
eprintln!("warning: HDD detected, the thread limit will be set to 1");
eprintln!("hint: You can pass --threads=max disable this behavior");
Some(1)
} else {
None
}
}
Threads::Max => None,
Threads::Fixed(threads) => Some(threads.get()),
};
if let Some(threads) = threads {
rayon::ThreadPoolBuilder::new()
.num_threads(threads)
.build_global()
.unwrap_or_else(|_| eprintln!("warning: Failed to set thread limit to {threads}"));
}
if cfg!(unix) && self.args.deduplicate_hardlinks && self.args.files.len() > 1 {
// Hardlinks deduplication doesn't work properly if there are more than 1 paths pointing to
// the same tree or if a path points to a subtree of another path. Therefore, we must find
// and remove such overlapping paths before they cause problems.
use overlapping_arguments::{remove_overlapping_paths, RealApi};
remove_overlapping_paths::<RealApi>(&mut self.args.files);
}
let report_error = if self.args.silent_errors {
ErrorReport::SILENT
} else {
ErrorReport::TEXT
};
let color = match self.args.color {
ColorWhen::Always => Some(LsColors::from_env()),
ColorWhen::Never => None,
ColorWhen::Auto => stdout().is_terminal().then(LsColors::from_env),
};
trait GetSizeUtils: GetSize<Size: size::Size> {
const INSTANCE: Self;
const QUANTITY: Quantity;
fn formatter(bytes_format: BytesFormat) -> <Self::Size as size::Size>::DisplayFormat;
}
impl GetSizeUtils for GetApparentSize {
const INSTANCE: Self = GetApparentSize;
const QUANTITY: Quantity = Quantity::ApparentSize;
#[inline]
fn formatter(bytes_format: BytesFormat) -> BytesFormat {
bytes_format
}
}
#[cfg(unix)]
impl GetSizeUtils for GetBlockSize {
const INSTANCE: Self = GetBlockSize;
const QUANTITY: Quantity = Quantity::BlockSize;
#[inline]
fn formatter(bytes_format: BytesFormat) -> BytesFormat {
bytes_format
}
}
#[cfg(unix)]
impl GetSizeUtils for GetBlockCount {
const INSTANCE: Self = GetBlockCount;
const QUANTITY: Quantity = Quantity::BlockCount;
#[inline]
fn formatter(_: BytesFormat) {}
}
trait CreateReporter<const REPORT_PROGRESS: bool>: GetSizeUtils {
type Reporter;
fn create_reporter(report_error: fn(ErrorReport)) -> Self::Reporter;
}
impl<SizeGetter> CreateReporter<false> for SizeGetter
where
Self: GetSizeUtils,
{
type Reporter = ErrorOnlyReporter<fn(ErrorReport)>;
#[inline]
fn create_reporter(report_error: fn(ErrorReport)) -> Self::Reporter {
ErrorOnlyReporter::new(report_error)
}
}
impl<SizeGetter> CreateReporter<true> for SizeGetter
where
Self: GetSizeUtils,
Self::Size: Into<u64> + Send + Sync,
ProgressReport<Self::Size>: Default + 'static,
u64: Into<Self::Size>,
{
type Reporter = ProgressAndErrorReporter<Self::Size, fn(ErrorReport)>;
#[inline]
fn create_reporter(report_error: fn(ErrorReport)) -> Self::Reporter {
ProgressAndErrorReporter::new(
ProgressReport::TEXT,
Duration::from_millis(100),
report_error,
)
}
}
trait CreateHardlinksHandler<const DEDUPLICATE_HARDLINKS: bool, const REPORT_PROGRESS: bool>:
CreateReporter<REPORT_PROGRESS>
{
type HardlinksHandler: hardlink::RecordHardlinks<Self::Size, Self::Reporter>
+ sub::HardlinkSubroutines<Self::Size>;
fn create_hardlinks_handler() -> Self::HardlinksHandler;
}
impl<const REPORT_PROGRESS: bool, SizeGetter> CreateHardlinksHandler<false, REPORT_PROGRESS>
for SizeGetter
where
Self: CreateReporter<REPORT_PROGRESS>,
Self::Size: Send + Sync,
{
type HardlinksHandler = hardlink::HardlinkIgnorant;
#[inline]
fn create_hardlinks_handler() -> Self::HardlinksHandler {
hardlink::HardlinkIgnorant
}
}
#[cfg(unix)]
impl<const REPORT_PROGRESS: bool, SizeGetter> CreateHardlinksHandler<true, REPORT_PROGRESS>
for SizeGetter
where
Self: CreateReporter<REPORT_PROGRESS>,
Self::Size: Send + Sync + 'static,
Self::Reporter: crate::reporter::Reporter<Self::Size>,
{
type HardlinksHandler = hardlink::HardlinkAware<Self::Size>;
#[inline]
fn create_hardlinks_handler() -> Self::HardlinksHandler {
hardlink::HardlinkAware::new()
}
}
macro_rules! run {
($(
$(#[$variant_attrs:meta])*
$size_getter:ident, $progress:literal, $hardlinks:ident;
)*) => { match self.args {$(
$(#[$variant_attrs])*
Args {
quantity: <$size_getter as GetSizeUtils>::QUANTITY,
progress: $progress,
#[cfg(unix)] deduplicate_hardlinks: $hardlinks,
#[cfg(not(unix))] deduplicate_hardlinks: _,
files,
json_output,
bytes_format,
top_down,
align_right,
max_depth,
min_ratio,
no_sort,
omit_json_shared_details,
omit_json_shared_summary,
..
} => Sub {
direction: Direction::from_top_down(top_down),
bar_alignment: BarAlignment::from_align_right(align_right),
size_getter: <$size_getter as GetSizeUtils>::INSTANCE,
hardlinks_handler: <$size_getter as CreateHardlinksHandler<{ cfg!(unix) && $hardlinks }, $progress>>::create_hardlinks_handler(),
reporter: <$size_getter as CreateReporter<$progress>>::create_reporter(report_error),
bytes_format: <$size_getter as GetSizeUtils>::formatter(bytes_format),
files,
json_output: JsonOutputParam::from_cli_flags(json_output, omit_json_shared_details, omit_json_shared_summary),
column_width_distribution,
max_depth,
min_ratio,
no_sort,
color,
}
.run(),
)*} };
}
run! {
GetApparentSize, false, false;
GetApparentSize, true, false;
#[cfg(unix)] GetBlockSize, false, false;
#[cfg(unix)] GetBlockSize, true, false;
#[cfg(unix)] GetBlockCount, false, false;
#[cfg(unix)] GetBlockCount, true, false;
#[cfg(unix)] GetApparentSize, false, true;
#[cfg(unix)] GetApparentSize, true, true;
#[cfg(unix)] GetBlockSize, false, true;
#[cfg(unix)] GetBlockSize, true, true;
#[cfg(unix)] GetBlockCount, false, true;
#[cfg(unix)] GetBlockCount, true, true;
}
}
}
mod hdd;
mod mount_point;
mod overlapping_arguments;