generated from EmbarkStudios/opensource-template
-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathls.rs
356 lines (301 loc) · 11.6 KB
/
ls.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
use crate::{color::ColorCtx, util};
use nu_ansi_term::Color;
use tame_gcs::{
common::StandardQueryParameters,
objects::{ListOptional, ListResponse, Metadata},
};
#[derive(clap::Parser, Debug)]
pub struct Args {
/// Recurse into directories, may want to take care with this
/// as it could consume a lot of memory depending on the contents
/// you query
#[structopt(short = 'R', long)]
recurse: bool,
/// Displays extended metadata as a table
#[structopt(short, long)]
long: bool,
/// The gs:// url list out
url: url::Url,
}
/// Does an ls of a gs bucket minus the prefix specified by the user, this
/// tries to mimic [exa](https://github.com/ogham/exa) when it can. Would also
/// be good to support <https://github.com/ogham/exa/blob/master/src/info/filetype.rs> at some point
pub async fn cmd(ctx: &util::RequestContext, args: Args) -> anyhow::Result<()> {
let oid = util::gs_url_to_object_id(&args.url)?;
let delimiter = if args.recurse { None } else { Some("/") };
let mut prefix = oid.object().map_or("", |on| on.as_ref()).to_owned();
if !prefix.is_empty() && !prefix.ends_with('/') {
prefix.push('/');
}
let prefix_len = prefix.len();
let prefix = Some(prefix);
let display = if args.long {
Display::Long
} else {
Display::Normal
};
let cc = ColorCtx::from_env();
let mut recurse = if args.recurse {
Some(RecursePrinter {
cc,
display,
prefix_len,
items: Vec::new(),
current_year: time::OffsetDateTime::now_utc().year(),
})
} else {
None
};
let normal = if !args.recurse {
Some(NormalPrinter {
cc,
display,
prefix_len,
})
} else {
None
};
let fields = match display {
Display::Normal => "items(name), prefixes, nextPageToken",
Display::Long => "items(name, updated, size), prefixes, nextPageToken",
};
let mut page_token: Option<String> = None;
loop {
let ls_req = ctx.obj.list(
oid.bucket(),
Some(ListOptional {
delimiter,
page_token: page_token.as_ref().map(|pt| pt.as_ref()),
prefix: prefix.as_ref().map(|s| s.as_ref()),
standard_params: StandardQueryParameters {
fields: Some(fields),
..Default::default()
},
..Default::default()
}),
)?;
let ls_res: ListResponse = util::execute(ctx, ls_req).await?;
if let Some(ref np) = normal {
np.print(ls_res.objects, ls_res.prefixes);
} else if let Some(ref mut rec) = recurse {
rec.append(ls_res.objects);
}
// If we have a page token it means there may be more items
// that fulfill the parameters
page_token = ls_res.page_token;
if page_token.is_none() {
break;
}
}
if let Some(ref rec) = recurse {
rec.print();
}
Ok(())
}
#[derive(Copy, Clone)]
enum Display {
Normal,
Long,
}
struct NormalPrinter {
cc: ColorCtx,
display: Display,
prefix_len: usize,
}
fn print_dir(cc: &ColorCtx, display: Display, dir: &str) {
match display {
Display::Normal => println!("{}", cc.paint(Color::Blue.bold(), dir)),
Display::Long => println!(
" {} {} {} {}",
cc.paint(Color::White.dimmed(), "-"),
cc.paint(Color::White.dimmed(), " -"),
cc.paint(Color::White.dimmed(), "-- --- --:--"),
cc.paint(Color::Blue.bold(), dir),
),
}
}
impl NormalPrinter {
fn print(&self, items: Vec<Metadata>, prefixes: Vec<String>) {
let cc = &self.cc;
let indices = {
// Determine at which indices we should place the "directories"
let mut indices = Vec::with_capacity(prefixes.len());
// So yah...just assume these are always in sorted order...
for prefix in &prefixes {
if let Err(i) = items.binary_search_by(|om| om.name.as_ref().unwrap().cmp(prefix)) {
indices.push(i);
}
}
indices
};
let mut next_dir_iter = indices.iter().enumerate();
let mut next_dir = next_dir_iter.next();
let current_year = time::OffsetDateTime::now_utc().year();
for (i, item) in items.into_iter().enumerate() {
if let Some(dir) = next_dir {
if *dir.1 == i {
let dir = &(&prefixes[dir.0])[self.prefix_len..];
let dir = &dir[..dir.len() - 1]; // Remove trailing delimiter
print_dir(&self.cc, self.display, dir);
next_dir = next_dir_iter.next();
}
}
let filename = &item.name.unwrap()[self.prefix_len..];
match self.display {
Display::Normal => println!("{}", cc.paint(Color::White, filename)),
Display::Long => {
use number_prefix::NumberPrefix;
let size_str = match NumberPrefix::decimal(item.size.unwrap_or_default() as f64)
{
NumberPrefix::Standalone(b) => b.to_string(),
NumberPrefix::Prefixed(p, n) => {
if n < 10f64 {
format!("{:.1}{}", n, p.symbol())
} else {
format!("{:.0}{}", n, p.symbol())
}
}
};
let updated = item.updated.unwrap();
let updated_str = timestamp_str(updated, current_year);
println!(
" {}{} {} {} {}",
if size_str.len() < 4 { " " } else { "" },
cc.paint(Color::Green, size_str),
cc.paint(Color::Yellow, "gcs"),
cc.paint(Color::Blue, updated_str),
cc.paint(Color::White, filename),
);
}
}
}
while let Some(dir) = next_dir {
let dir = &(&prefixes[dir.0])[self.prefix_len..];
let dir = &dir[..dir.len() - 1]; // Remove trailing delimiter
print_dir(&self.cc, self.display, dir);
next_dir = next_dir_iter.next();
}
}
}
fn timestamp_str(ts: time::OffsetDateTime, current_year: i32) -> String {
const RECENT: &[time::format_description::FormatItem<'_>] =
time::macros::format_description!("[day] [month repr:short] [hour]:[minute]");
const OLD: &[time::format_description::FormatItem<'_>] =
time::macros::format_description!("[day] [month repr:short] [year]");
if ts.year() == current_year {
ts.format(&RECENT)
} else {
ts.format(&OLD)
}
.unwrap()
}
struct SimpleMetadata {
name: String,
size: u64,
updated: String,
}
struct RecursePrinter {
cc: ColorCtx,
display: Display,
prefix_len: usize,
items: Vec<Vec<SimpleMetadata>>,
current_year: i32,
}
use std::io::Write;
impl RecursePrinter {
fn append(&mut self, items: Vec<Metadata>) {
let items = items
.into_iter()
.map(|md| SimpleMetadata {
name: String::from(&md.name.unwrap()[self.prefix_len..]),
size: md.size.unwrap_or_default(),
updated: md
.updated
.map(|dt| timestamp_str(dt, self.current_year))
.unwrap_or_default(),
})
.collect();
self.items.push(items);
}
fn print(&self) {
let mut stdout = std::io::stdout().lock();
let mut dirs = vec![String::new()];
while let Some(dir) = dirs.pop() {
if !dir.is_empty() {
writeln!(stdout, "\n{}:", &dir[..dir.len() - 1]).unwrap();
}
dirs.extend(self.print_dir(dir, &mut stdout));
}
}
fn print_dir(&self, dir: String, out: &mut std::io::StdoutLock<'static>) -> Vec<String> {
let cc = &self.cc;
let mut new_dirs = Vec::new();
for set in &self.items {
for item in set {
if item.name.starts_with(&dir) {
let scoped_name = &item.name[dir.len()..];
match scoped_name.find('/') {
Some(sep) => {
let dir_name = &scoped_name[..=sep];
if new_dirs
.iter()
.any(|d: &String| &d[dir.len()..] == dir_name)
{
continue;
}
match self.display {
Display::Normal => writeln!(
out,
"{}",
cc.paint(Color::Blue.bold(), &dir_name[..dir_name.len() - 1])
)
.unwrap(),
Display::Long => writeln!(
out,
" {} {} {} {}",
cc.paint(Color::White.dimmed(), "-"),
cc.paint(Color::White.dimmed(), " -"),
cc.paint(Color::White.dimmed(), "-- --- --:--"),
cc.paint(Color::Blue.bold(), &dir_name[..dir_name.len() - 1]),
)
.unwrap(),
}
new_dirs.push(format!("{}{}", dir, dir_name));
}
None => match self.display {
Display::Normal => {
writeln!(out, "{}", cc.paint(Color::White, scoped_name)).unwrap();
}
Display::Long => {
use number_prefix::NumberPrefix;
let size_str = match NumberPrefix::decimal(item.size as f64) {
NumberPrefix::Standalone(b) => b.to_string(),
NumberPrefix::Prefixed(p, n) => {
if n < 10f64 {
format!("{:.1}{}", n, p.symbol())
} else {
format!("{:.0}{}", n, p.symbol())
}
}
};
writeln!(
out,
" {}{} {} {} {}",
if size_str.len() < 4 { " " } else { "" },
cc.paint(Color::Green, size_str),
cc.paint(Color::Yellow, "gcs"),
cc.paint(Color::Blue, &item.updated),
cc.paint(Color::White, scoped_name),
)
.unwrap();
}
},
}
}
}
}
// The directories act as a queue, so reverse them so they are sorted correctly
new_dirs.reverse();
new_dirs
}
}