pub struct FileSum { /* private fields */ }
Expand description
Reduction of counts, dates and sizes on a file or directory
Implementations§
source§impl FileSum
impl FileSum
sourcepub fn new(real_size: u64, sparse: bool, count: usize, modified: u32) -> Self
pub fn new(real_size: u64, sparse: bool, count: usize, modified: u32) -> Self
Examples found in repository?
src/file_sum/mod.rs (line 51)
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
pub fn zero() -> Self {
Self::new(0, false, 0, 0)
}
pub fn incr(&mut self) {
self.count += 1;
}
/// return the sum of the given file, which is assumed
/// to be a normal file (ie not a directory)
pub fn from_file(path: &Path) -> Self {
sum_computation::compute_file_sum(path)
}
/// Return the sum of the directory, either by computing it of by
/// fetching it from cache.
/// If the lifetime expires before complete computation, None is returned.
pub fn from_dir(path: &Path, dam: &Dam, con: &AppContext) -> Option<Self> {
let mut sum_cache = SUM_CACHE.lock().unwrap();
match sum_cache.get(path) {
Some(sum) => Some(*sum),
None => {
let sum = time!(
"sum computation",
path,
sum_computation::compute_dir_sum(path, &mut sum_cache, dam, con),
);
if let Some(sum) = sum {
sum_cache.insert(PathBuf::from(path), sum);
}
sum
}
}
}
pub fn part_of_size(self, total: Self) -> f32 {
if total.real_size == 0 {
0.0
} else {
self.real_size as f32 / total.real_size as f32
}
}
/// return the number of files (normally at least 1)
pub fn to_count(self) -> usize {
self.count
}
/// return the number of seconds from Epoch to last modification,
/// or 0 if the computation failed
pub fn to_seconds(self) -> u32 {
self.modified
}
/// return the size in bytes
pub fn to_size(self) -> u64 {
self.real_size
}
pub fn to_valid_seconds(self) -> Option<i64> {
if self.modified != 0 {
Some(self.modified as i64)
} else {
None
}
}
/// tell whether the file has holes (in which case the size displayed by
/// other tools may be greater than the "real" one returned by broot).
/// Not computed (return false) on windows or for directories.
pub fn is_sparse(self) -> bool {
self.sparse
}
}
impl AddAssign for FileSum {
#[allow(clippy::suspicious_op_assign_impl)]
fn add_assign(&mut self, other: Self) {
*self = Self::new(
self.real_size + other.real_size,
self.sparse | other.sparse,
self.count + other.count,
self.modified.max(other.modified),
);
}
More examples
src/file_sum/sum_computation.rs (lines 286-291)
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
pub fn compute_file_sum(path: &Path) -> FileSum {
match fs::symlink_metadata(path) {
Ok(md) => {
let seconds = extract_seconds(&md);
#[cfg(unix)]
{
let nominal_size = md.size();
let block_size = md.blocks() * 512;
FileSum::new(
block_size.min(nominal_size),
block_size < nominal_size,
1,
seconds,
)
}
#[cfg(not(unix))]
FileSum::new(md.len(), false, 1, seconds)
}
Err(_) => FileSum::new(0, false, 1, 0),
}
}
#[cfg(unix)]
#[inline(always)]
fn extract_seconds(md: &fs::Metadata) -> u32 {
md.mtime().try_into().unwrap_or(0)
}
#[cfg(not(unix))]
#[inline(always)]
fn extract_seconds(md: &fs::Metadata) -> u32 {
if let Ok(st) = md.modified() {
if let Ok(d) = st.duration_since(std::time::UNIX_EPOCH) {
if let Ok(secs) = d.as_secs().try_into() {
return secs;
}
}
}
0
}
#[inline(always)]
fn md_sum(md: &fs::Metadata) -> FileSum {
#[cfg(unix)]
let size = md.blocks() * 512;
#[cfg(not(unix))]
let size = md.len();
let seconds = extract_seconds(md);
FileSum::new(size, false, 1, seconds)
}
sourcepub fn zero() -> Self
pub fn zero() -> Self
Examples found in repository?
src/stage/stage.rs (line 82)
81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96
pub fn compute_sum(&self, dam: &Dam, con: &AppContext) -> Option<FileSum> {
let mut sum = FileSum::zero();
for path in &self.paths {
if path.is_dir() {
let dir_sum = FileSum::from_dir(path, dam, con);
if let Some(dir_sum) = dir_sum {
sum += dir_sum;
} else {
return None; // computation was interrupted
}
} else {
sum += FileSum::from_file(path);
}
}
Some(sum)
}
More examples
src/tree/tree.rs (line 528)
521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538
pub fn total_sum(&self) -> FileSum {
if let Some(sum) = self.lines[0].sum {
// if the real total sum is computed, it's in the root line
sum
} else {
// if we don't have the sum in root, the nearest estimate is
// the sum of sums of lines at depth 1
let mut sum = FileSum::zero();
for i in 1..self.lines.len() {
if self.lines[i].depth == 1 {
if let Some(line_sum) = self.lines[i].sum {
sum += line_sum;
}
}
}
sum
}
}
src/file_sum/sum_computation.rs (line 79)
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
pub fn compute_dir_sum(
&mut self,
path: &Path,
cache: &mut AHashMap<PathBuf, FileSum>,
dam: &Dam,
con: &AppContext,
) -> Option<FileSum> {
let threads_count = self.thread_count;
if is_ignored(path, &con.special_paths) {
return Some(FileSum::zero());
}
// there are problems in /proc - See issue #637
if path.starts_with("/proc") {
debug!("not summing in /proc");
return Some(FileSum::zero());
}
if path.starts_with("/run") {
debug!("not summing in /run");
return Some(FileSum::zero());
}
// to avoid counting twice a node, we store their id in a set
#[cfg(unix)]
let nodes = Arc::new(Mutex::new(FnvHashSet::<NodeId>::default()));
// busy is the number of directories which are either being processed or queued
// We use this count to determine when threads can stop waiting for tasks
let mut busy = 0;
let mut sum = compute_file_sum(path);
// this MPMC channel contains the directory paths which must be handled.
// A None means there's nothing left and the thread may send its result and stop
let (dirs_sender, dirs_receiver) = channel::unbounded();
let special_paths: Vec<SpecialPath> = con.special_paths.iter()
.filter(|sp| sp.can_have_matches_in(path))
.cloned()
.collect();
// the first level is managed a little differently: we look at the cache
// before adding. This enables faster computations in two cases:
// - for the root line (assuming it's computed after the content)
// - when we navigate up the tree
if let Ok(entries) = fs::read_dir(path) {
for e in entries.flatten() {
if let Ok(md) = e.metadata() {
if md.is_dir() {
let entry_path = e.path();
if is_ignored(&entry_path, &special_paths) {
debug!("not summing special path {:?}", entry_path);
continue;
}
// we check the cache
if let Some(entry_sum) = cache.get(&entry_path) {
sum += *entry_sum;
continue;
}
// we add the directory to the channel of dirs needing
// processing
busy += 1;
dirs_sender.send(Some(entry_path)).unwrap();
} else {
#[cfg(unix)]
if md.nlink() > 1 {
let mut nodes = nodes.lock().unwrap();
let node_id = NodeId {
inode: md.ino(),
dev: md.dev(),
};
if !nodes.insert(node_id) {
// it was already in the set
continue;
}
}
}
sum += md_sum(&md);
}
}
}
if busy == 0 {
return Some(sum);
}
let busy = Arc::new(AtomicIsize::new(busy));
// this MPMC channel is here for the threads to send their results
// at end of computation
let (thread_sum_sender, thread_sum_receiver) = channel::bounded(threads_count);
// Each thread does a summation without merge and the data are merged
// at the end (this avoids waiting for a mutex during computation)
for _ in 0..threads_count {
let busy = Arc::clone(&busy);
let (dirs_sender, dirs_receiver) = (dirs_sender.clone(), dirs_receiver.clone());
#[cfg(unix)]
let nodes = nodes.clone();
let special_paths = special_paths.clone();
let observer = dam.observer();
let thread_sum_sender = thread_sum_sender.clone();
self.thread_pool.spawn(move || {
let mut thread_sum = FileSum::zero();
loop {
let o = dirs_receiver.recv();
if let Ok(Some(open_dir)) = o {
if let Ok(entries) = fs::read_dir(&open_dir) {
for e in entries.flatten() {
if let Ok(md) = e.metadata() {
if md.is_dir() {
let path = e.path();
if is_ignored(&path, &special_paths) {
debug!("not summing (deep) special path {:?}", path);
continue;
}
// we add the directory to the channel of dirs needing
// processing
busy.fetch_add(1, Ordering::Relaxed);
dirs_sender.send(Some(path)).unwrap();
} else {
#[cfg(unix)]
if md.nlink() > 1 {
let mut nodes = nodes.lock().unwrap();
let node_id = NodeId {
inode: md.ino(),
dev: md.dev(),
};
if !nodes.insert(node_id) {
// it was already in the set
continue;
}
}
}
thread_sum += md_sum(&md);
} else {
// we can't measure much but we can count the file
thread_sum.incr();
}
}
}
busy.fetch_sub(1, Ordering::Relaxed);
}
if observer.has_event() {
dirs_sender.send(None).unwrap(); // to unlock the next waiting thread
break;
}
if busy.load(Ordering::Relaxed) < 1 {
dirs_sender.send(None).unwrap(); // to unlock the next waiting thread
break;
}
}
thread_sum_sender.send(thread_sum).unwrap();
});
}
// Wait for the threads to finish and consolidate their results
for _ in 0..threads_count {
match thread_sum_receiver.recv() {
Ok(thread_sum) => {
sum += thread_sum;
}
Err(e) => {
warn!("Error while recv summing thread result : {:?}", e);
}
}
}
if dam.has_event() {
return None;
}
Some(sum)
}
sourcepub fn incr(&mut self)
pub fn incr(&mut self)
Examples found in repository?
src/file_sum/sum_computation.rs (line 219)
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
pub fn compute_dir_sum(
&mut self,
path: &Path,
cache: &mut AHashMap<PathBuf, FileSum>,
dam: &Dam,
con: &AppContext,
) -> Option<FileSum> {
let threads_count = self.thread_count;
if is_ignored(path, &con.special_paths) {
return Some(FileSum::zero());
}
// there are problems in /proc - See issue #637
if path.starts_with("/proc") {
debug!("not summing in /proc");
return Some(FileSum::zero());
}
if path.starts_with("/run") {
debug!("not summing in /run");
return Some(FileSum::zero());
}
// to avoid counting twice a node, we store their id in a set
#[cfg(unix)]
let nodes = Arc::new(Mutex::new(FnvHashSet::<NodeId>::default()));
// busy is the number of directories which are either being processed or queued
// We use this count to determine when threads can stop waiting for tasks
let mut busy = 0;
let mut sum = compute_file_sum(path);
// this MPMC channel contains the directory paths which must be handled.
// A None means there's nothing left and the thread may send its result and stop
let (dirs_sender, dirs_receiver) = channel::unbounded();
let special_paths: Vec<SpecialPath> = con.special_paths.iter()
.filter(|sp| sp.can_have_matches_in(path))
.cloned()
.collect();
// the first level is managed a little differently: we look at the cache
// before adding. This enables faster computations in two cases:
// - for the root line (assuming it's computed after the content)
// - when we navigate up the tree
if let Ok(entries) = fs::read_dir(path) {
for e in entries.flatten() {
if let Ok(md) = e.metadata() {
if md.is_dir() {
let entry_path = e.path();
if is_ignored(&entry_path, &special_paths) {
debug!("not summing special path {:?}", entry_path);
continue;
}
// we check the cache
if let Some(entry_sum) = cache.get(&entry_path) {
sum += *entry_sum;
continue;
}
// we add the directory to the channel of dirs needing
// processing
busy += 1;
dirs_sender.send(Some(entry_path)).unwrap();
} else {
#[cfg(unix)]
if md.nlink() > 1 {
let mut nodes = nodes.lock().unwrap();
let node_id = NodeId {
inode: md.ino(),
dev: md.dev(),
};
if !nodes.insert(node_id) {
// it was already in the set
continue;
}
}
}
sum += md_sum(&md);
}
}
}
if busy == 0 {
return Some(sum);
}
let busy = Arc::new(AtomicIsize::new(busy));
// this MPMC channel is here for the threads to send their results
// at end of computation
let (thread_sum_sender, thread_sum_receiver) = channel::bounded(threads_count);
// Each thread does a summation without merge and the data are merged
// at the end (this avoids waiting for a mutex during computation)
for _ in 0..threads_count {
let busy = Arc::clone(&busy);
let (dirs_sender, dirs_receiver) = (dirs_sender.clone(), dirs_receiver.clone());
#[cfg(unix)]
let nodes = nodes.clone();
let special_paths = special_paths.clone();
let observer = dam.observer();
let thread_sum_sender = thread_sum_sender.clone();
self.thread_pool.spawn(move || {
let mut thread_sum = FileSum::zero();
loop {
let o = dirs_receiver.recv();
if let Ok(Some(open_dir)) = o {
if let Ok(entries) = fs::read_dir(&open_dir) {
for e in entries.flatten() {
if let Ok(md) = e.metadata() {
if md.is_dir() {
let path = e.path();
if is_ignored(&path, &special_paths) {
debug!("not summing (deep) special path {:?}", path);
continue;
}
// we add the directory to the channel of dirs needing
// processing
busy.fetch_add(1, Ordering::Relaxed);
dirs_sender.send(Some(path)).unwrap();
} else {
#[cfg(unix)]
if md.nlink() > 1 {
let mut nodes = nodes.lock().unwrap();
let node_id = NodeId {
inode: md.ino(),
dev: md.dev(),
};
if !nodes.insert(node_id) {
// it was already in the set
continue;
}
}
}
thread_sum += md_sum(&md);
} else {
// we can't measure much but we can count the file
thread_sum.incr();
}
}
}
busy.fetch_sub(1, Ordering::Relaxed);
}
if observer.has_event() {
dirs_sender.send(None).unwrap(); // to unlock the next waiting thread
break;
}
if busy.load(Ordering::Relaxed) < 1 {
dirs_sender.send(None).unwrap(); // to unlock the next waiting thread
break;
}
}
thread_sum_sender.send(thread_sum).unwrap();
});
}
// Wait for the threads to finish and consolidate their results
for _ in 0..threads_count {
match thread_sum_receiver.recv() {
Ok(thread_sum) => {
sum += thread_sum;
}
Err(e) => {
warn!("Error while recv summing thread result : {:?}", e);
}
}
}
if dam.has_event() {
return None;
}
Some(sum)
}
sourcepub fn from_file(path: &Path) -> Self
pub fn from_file(path: &Path) -> Self
return the sum of the given file, which is assumed to be a normal file (ie not a directory)
Examples found in repository?
More examples
src/stage/stage.rs (line 92)
81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96
pub fn compute_sum(&self, dam: &Dam, con: &AppContext) -> Option<FileSum> {
let mut sum = FileSum::zero();
for path in &self.paths {
if path.is_dir() {
let dir_sum = FileSum::from_dir(path, dam, con);
if let Some(dir_sum) = dir_sum {
sum += dir_sum;
} else {
return None; // computation was interrupted
}
} else {
sum += FileSum::from_file(path);
}
}
Some(sum)
}
sourcepub fn from_dir(path: &Path, dam: &Dam, con: &AppContext) -> Option<Self>
pub fn from_dir(path: &Path, dam: &Dam, con: &AppContext) -> Option<Self>
Return the sum of the directory, either by computing it of by fetching it from cache. If the lifetime expires before complete computation, None is returned.
Examples found in repository?
More examples
src/stage/stage.rs (line 85)
81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96
pub fn compute_sum(&self, dam: &Dam, con: &AppContext) -> Option<FileSum> {
let mut sum = FileSum::zero();
for path in &self.paths {
if path.is_dir() {
let dir_sum = FileSum::from_dir(path, dam, con);
if let Some(dir_sum) = dir_sum {
sum += dir_sum;
} else {
return None; // computation was interrupted
}
} else {
sum += FileSum::from_file(path);
}
}
Some(sum)
}
sourcepub fn part_of_size(self, total: Self) -> f32
pub fn part_of_size(self, total: Self) -> f32
Examples found in repository?
src/display/displayable_tree.rs (line 178)
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
fn write_line_size_with_bar<'w, W: Write>(
&self,
cw: &mut CropWriter<'w, W>,
line: &TreeLine,
label_style: &CompoundStyle,
total_size: FileSum,
selected: bool,
) -> Result<usize, termimad::Error> {
Ok(if let Some(s) = line.sum {
let pb = ProgressBar::new(s.part_of_size(total_size), 10);
cond_bg!(sparse_style, self, selected, self.skin.sparse);
cw.queue_g_string(
label_style,
format!("{:>4}", file_size::fit_4(s.to_size())),
)?;
cw.queue_char(
sparse_style,
if s.is_sparse() && line.is_file() { 's' } else { ' ' },
)?;
cw.queue_g_string(label_style, format!("{:<10}", pb))?;
1
} else {
16
})
}
sourcepub fn to_count(self) -> usize
pub fn to_count(self) -> usize
return the number of files (normally at least 1)
Examples found in repository?
src/display/displayable_tree.rs (line 110)
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 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633
fn write_line_count<'w, W: Write>(
&self,
cw: &mut CropWriter<'w, W>,
line: &TreeLine,
count_len: usize,
selected: bool,
) -> Result<usize, termimad::Error> {
Ok(if let Some(s) = line.sum {
cond_bg!(count_style, self, selected, self.skin.count);
let s = format_count(s.to_count());
cw.queue_g_string(count_style, format!("{s:>count_len$}"))?;
1
} else {
count_len + 1
})
}
#[cfg(unix)]
fn write_line_device_id<'w, W: Write>(
&self,
cw: &mut CropWriter<'w, W>,
line: &TreeLine,
selected: bool,
) -> Result<usize, termimad::Error> {
let device_id = line.device_id();
cond_bg!(style, self, selected, self.skin.device_id_major);
cw.queue_g_string(style, format!("{:>3}", device_id.major))?;
cond_bg!(style, self, selected, self.skin.device_id_sep);
cw.queue_char(style, ':')?;
cond_bg!(style, self, selected, self.skin.device_id_minor);
cw.queue_g_string(style, format!("{:<3}", device_id.minor))?;
Ok(0)
}
fn write_line_selection_mark<'w, W: Write>(
&self,
cw: &mut CropWriter<'w, W>,
style: &CompoundStyle,
selected: bool,
) -> Result<usize, termimad::Error> {
Ok(if selected {
cw.queue_char(style, '▶')?;
0
} else {
1
})
}
fn write_line_size<'w, W: Write>(
&self,
cw: &mut CropWriter<'w, W>,
line: &TreeLine,
style: &CompoundStyle,
_selected: bool,
) -> Result<usize, termimad::Error> {
Ok(if let Some(s) = line.sum {
cw.queue_g_string(
style,
format!("{:>4}", file_size::fit_4(s.to_size())),
)?;
1
} else {
5
})
}
/// only makes sense when there's only one level
/// (so in sort mode)
fn write_line_size_with_bar<'w, W: Write>(
&self,
cw: &mut CropWriter<'w, W>,
line: &TreeLine,
label_style: &CompoundStyle,
total_size: FileSum,
selected: bool,
) -> Result<usize, termimad::Error> {
Ok(if let Some(s) = line.sum {
let pb = ProgressBar::new(s.part_of_size(total_size), 10);
cond_bg!(sparse_style, self, selected, self.skin.sparse);
cw.queue_g_string(
label_style,
format!("{:>4}", file_size::fit_4(s.to_size())),
)?;
cw.queue_char(
sparse_style,
if s.is_sparse() && line.is_file() { 's' } else { ' ' },
)?;
cw.queue_g_string(label_style, format!("{:<10}", pb))?;
1
} else {
16
})
}
fn write_line_git_status<'w, W: Write>(
&self,
cw: &mut CropWriter<'w, W>,
line: &TreeLine,
selected: bool,
) -> Result<usize, termimad::Error> {
let (style, char) = if !line.is_selectable() {
(&self.skin.tree, ' ')
} else {
match line.git_status.map(|s| s.status) {
Some(Status::CURRENT) => (&self.skin.git_status_current, ' '),
Some(Status::WT_NEW) => (&self.skin.git_status_new, 'N'),
Some(Status::CONFLICTED) => (&self.skin.git_status_conflicted, 'C'),
Some(Status::WT_MODIFIED) => (&self.skin.git_status_modified, 'M'),
Some(Status::IGNORED) => (&self.skin.git_status_ignored, 'I'),
None => (&self.skin.tree, ' '),
_ => (&self.skin.git_status_other, '?'),
}
};
cond_bg!(git_style, self, selected, style);
cw.queue_char(git_style, char)?;
Ok(0)
}
fn write_date<'w, W: Write>(
&self,
cw: &mut CropWriter<'w, W>,
seconds: i64,
selected: bool,
) -> Result<usize, termimad::Error> {
if let LocalResult::Single(date_time) = Local.timestamp_opt(seconds, 0) {
cond_bg!(date_style, self, selected, self.skin.dates);
cw.queue_g_string(
date_style,
date_time
.format(self.tree.options.date_time_format)
.to_string(),
)?;
}
Ok(1)
}
fn write_branch<'w, W: Write>(
&self,
cw: &mut CropWriter<'w, W>,
line_index: usize,
line: &TreeLine,
selected: bool,
staged: bool,
) -> Result<usize, ProgramError> {
cond_bg!(branch_style, self, selected, self.skin.tree);
let mut branch = String::new();
for depth in 0..line.depth {
branch.push_str(
if line.left_branchs[depth as usize] {
if self.tree.has_branch(line_index + 1, depth as usize) {
// TODO: If a theme is on, remove the horizontal lines
if depth == line.depth - 1 {
if staged {
"├◍─"
} else {
"├──"
}
} else {
"│ "
}
} else {
if staged {
"└◍─"
} else {
"└──"
}
}
} else {
" "
},
);
}
if !branch.is_empty() {
cw.queue_g_string(branch_style, branch)?;
}
Ok(0)
}
/// write the symbol showing whether the path is staged
fn write_line_stage_mark<'w, W: Write>(
&self,
cw: &mut CropWriter<'w, W>,
style: &CompoundStyle,
staged: bool,
) -> Result<usize, termimad::Error> {
Ok(if staged {
cw.queue_char(style, '◍')?; // ▣
0
} else {
1
})
}
/// write the name or subpath, depending on the pattern_object
fn write_line_label<'w, W: Write>(
&self,
cw: &mut CropWriter<'w, W>,
line: &TreeLine,
style: &CompoundStyle,
pattern_object: PatternObject,
selected: bool,
) -> Result<usize, ProgramError> {
cond_bg!(char_match_style, self, selected, self.skin.char_match);
if let Some(icon) = line.icon {
cw.queue_char(style, icon)?;
cw.queue_char(style, ' ')?;
cw.queue_char(style, ' ')?;
}
if pattern_object.subpath {
if self.tree.options.show_matching_characters_on_path_searches && line.unlisted == 0 {
let name_match = self.tree.options.pattern.pattern
.search_string(&line.subpath);
let mut path_ms = MatchedString::new(
name_match,
&line.subpath,
style,
char_match_style,
);
let name_ms = path_ms.split_on_last('/');
cond_bg!(parent_style, self, selected, self.skin.parent);
if name_ms.is_some() {
path_ms.base_style = parent_style;
}
path_ms.queue_on(cw)?;
if let Some(name_ms) = name_ms {
name_ms.queue_on(cw)?;
}
} else {
cw.queue_str(style, &line.name)?;
}
} else {
let name_match = self.tree.options.pattern.pattern
.search_string(&line.name);
let matched_string = MatchedString::new(
name_match,
&line.name,
style,
char_match_style,
);
matched_string.queue_on(cw)?;
}
match &line.line_type {
TreeLineType::Dir => {
if line.unlisted > 0 {
cw.queue_str(style, " …")?;
}
}
TreeLineType::BrokenSymLink(direct_path) => {
cw.queue_str(style, " -> ")?;
cond_bg!(error_style, self, selected, self.skin.file_error);
cw.queue_str(error_style, direct_path)?;
}
TreeLineType::SymLink {
final_is_dir,
direct_target,
..
} => {
cw.queue_str(style, " -> ")?;
let target_style = if *final_is_dir {
&self.skin.directory
} else {
&self.skin.file
};
cond_bg!(target_style, self, selected, target_style);
cw.queue_str(target_style, direct_target)?;
}
_ => {}
}
Ok(1)
}
fn write_content_extract<'w, W: Write>(
&self,
cw: &mut CropWriter<'w, W>,
extract: ContentMatch,
selected: bool,
) -> Result<(), ProgramError> {
cond_bg!(extract_style, self, selected, self.skin.content_extract);
cond_bg!(match_style, self, selected, self.skin.content_match);
cw.queue_str(extract_style, " ")?;
if extract.needle_start > 0 {
cw.queue_str(extract_style, &extract.extract[0..extract.needle_start])?;
}
cw.queue_str(
match_style,
&extract.extract[extract.needle_start..extract.needle_end],
)?;
if extract.needle_end < extract.extract.len() {
cw.queue_str(extract_style, &extract.extract[extract.needle_end..])?;
}
Ok(())
}
pub fn write_root_line<'w, W: Write>(
&self,
cw: &mut CropWriter<'w, W>,
selected: bool,
) -> Result<(), ProgramError> {
cond_bg!(style, self, selected, self.skin.directory);
let line = &self.tree.lines[0];
if self.tree.options.show_sizes {
if let Some(s) = line.sum {
cw.queue_g_string(
style,
format!("{:>4} ", file_size::fit_4(s.to_size())),
)?;
}
}
let title = line.path.to_string_lossy();
cw.queue_str(style, &title)?;
if self.in_app && !cw.is_full() {
if let ComputationResult::Done(git_status) = &self.tree.git_status {
let git_status_display = GitStatusDisplay::from(
git_status,
self.skin,
cw.allowed,
);
git_status_display.write(cw, selected)?;
}
#[cfg(unix)]
if self.tree.options.show_root_fs {
if let Some(mount) = line.mount() {
let fs_space_display = crate::filesystems::MountSpaceDisplay::from(
&mount,
self.skin,
cw.allowed,
);
fs_space_display.write(cw, selected)?;
}
}
self.extend_line_bg(cw, selected)?;
}
Ok(())
}
/// if in app, extend the background till the end of screen row
pub fn extend_line_bg<'w, W: Write>(
&self,
cw: &mut CropWriter<'w, W>,
selected: bool,
) -> Result<(), ProgramError> {
if self.in_app && !cw.is_full() {
let style = if selected {
&self.skin.selected_line
} else {
&self.skin.default
};
cw.fill(style, &SPACE_FILLING)?;
}
Ok(())
}
/// write the whole tree on the given `W`
pub fn write_on<W: Write>(&self, f: &mut W) -> Result<(), ProgramError> {
#[cfg(not(any(target_family = "windows", target_os = "android")))]
let perm_writer = super::PermWriter::for_tree(self.skin, self.tree);
let tree = self.tree;
let total_size = tree.total_sum();
let scrollbar = if self.in_app {
termimad::compute_scrollbar(
tree.scroll,
tree.lines.len() - 1, // the root line isn't scrolled
self.area.height - 1, // the scrollbar doesn't cover the first line
self.area.top + 1,
)
} else {
None
};
if self.in_app {
f.queue(cursor::MoveTo(self.area.left, self.area.top))?;
}
let mut cw = CropWriter::new(f, self.area.width as usize);
let pattern_object = tree.options.pattern.pattern.object();
self.write_root_line(&mut cw, self.in_app && tree.selection == 0)?;
self.skin.queue_reset(f)?;
let visible_cols: Vec<Col> = tree
.options
.cols_order
.iter()
.filter(|col| col.is_visible(tree, self.app_state))
.cloned()
.collect();
// if necessary we compute the width of the count column
let count_len = if tree.options.show_counts {
tree.lines.iter()
.skip(1) // we don't show the counts of the root
.map(|l| l.sum.map_or(0, |s| s.to_count()))
.max()
.map(|c| format_count(c).len())
.unwrap_or(0)
} else {
0
};
// we compute the length of the dates, depending on the format
let date_len = if tree.options.show_dates {
let date_time: DateTime<Local> = Local::now();
date_time.format(tree.options.date_time_format).to_string().len()
} else {
0 // we don't care
};
for y in 1..self.area.height {
if self.in_app {
f.queue(cursor::MoveTo(self.area.left, y + self.area.top))?;
} else {
write!(f, "\r\n")?;
}
let mut line_index = y as usize;
if line_index > 0 {
line_index += tree.scroll as usize;
}
let mut selected = false;
let mut cw = CropWriter::new(f, self.area.width as usize);
let cw = &mut cw;
if line_index < tree.lines.len() {
let line = &tree.lines[line_index];
selected = self.in_app && line_index == tree.selection;
let label_style = self.label_style(line, selected);
let mut in_branch = false;
let space_style = if selected {
&self.skin.selected_line
} else {
&self.skin.default
};
if visible_cols[0].needs_left_margin() {
cw.queue_char(space_style, ' ')?;
}
let staged = self.app_state
.map_or(false, |a| a.stage.contains(&line.path));
for col in &visible_cols {
let void_len = match col {
Col::Mark => {
self.write_line_selection_mark(cw, &label_style, selected)?
}
Col::Git => {
self.write_line_git_status(cw, line, selected)?
}
Col::Branch => {
in_branch = true;
self.write_branch(cw, line_index, line, selected, staged)?
}
Col::DeviceId => {
#[cfg(not(unix))]
{ 0 }
#[cfg(unix)]
self.write_line_device_id(cw, line, selected)?
}
Col::Permission => {
#[cfg(any(target_family = "windows", target_os = "android"))]
{ 0 }
#[cfg(not(any(target_family = "windows", target_os = "android")))]
perm_writer.write_permissions(cw, line, selected)?
}
Col::Date => {
if let Some(seconds) = line.sum.and_then(|sum| sum.to_valid_seconds()) {
self.write_date(cw, seconds, selected)?
} else {
date_len + 1
}
}
Col::Size => {
if tree.options.sort.prevent_deep_display() {
// as soon as there's only one level displayed we can show the size bars
self.write_line_size_with_bar(cw, line, &label_style, total_size, selected)?
} else {
self.write_line_size(cw, line, &label_style, selected)?
}
}
Col::Count => {
self.write_line_count(cw, line, count_len, selected)?
}
Col::Staged => {
self.write_line_stage_mark(cw, &label_style, staged)?
}
Col::Name => {
in_branch = false;
self.write_line_label(cw, line, &label_style, pattern_object, selected)?
}
};
// void: intercol & replacing missing cells
if in_branch && void_len > 2 {
cond_bg!(void_style, self, selected, self.skin.tree);
cw.repeat(void_style, &BRANCH_FILLING, void_len)?;
} else {
cond_bg!(void_style, self, selected, self.skin.default);
cw.repeat(void_style, &SPACE_FILLING, void_len)?;
}
}
if cw.allowed > 8 && pattern_object.content {
let extract = tree.options.pattern.pattern
.search_content(&line.path, cw.allowed - 2);
if let Some(extract) = extract {
self.write_content_extract(cw, extract, selected)?;
}
}
}
self.extend_line_bg(cw, selected)?;
self.skin.queue_reset(f)?;
if self.in_app {
if let Some((sctop, scbottom)) = scrollbar {
f.queue(cursor::MoveTo(self.area.left + self.area.width - 1, y))?;
let style = if sctop <= y && y <= scbottom {
&self.skin.scrollbar_thumb
} else {
&self.skin.scrollbar_track
};
style.queue_str(f, "▐")?;
}
}
}
if !self.in_app {
write!(f, "\r\n")?;
}
Ok(())
}
More examples
src/tree/tree.rs (line 492)
486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518
fn sort_siblings(&mut self) {
match self.options.sort {
Sort::Count => {
// we'll try to keep the same path selected
let selected_path = self.selected_line().path.to_path_buf();
self.lines[1..].sort_by(|a, b| {
let acount = a.sum.map_or(0, |s| s.to_count());
let bcount = b.sum.map_or(0, |s| s.to_count());
bcount.cmp(&acount)
});
self.try_select_path(&selected_path);
}
Sort::Date => {
let selected_path = self.selected_line().path.to_path_buf();
self.lines[1..].sort_by(|a, b| {
let adate = a.sum.map_or(0, |s| s.to_seconds());
let bdate = b.sum.map_or(0, |s| s.to_seconds());
bdate.cmp(&adate)
});
self.try_select_path(&selected_path);
}
Sort::Size => {
let selected_path = self.selected_line().path.to_path_buf();
self.lines[1..].sort_by(|a, b| {
let asize = a.sum.map_or(0, |s| s.to_size());
let bsize = b.sum.map_or(0, |s| s.to_size());
bsize.cmp(&asize)
});
self.try_select_path(&selected_path);
}
_ => {}
}
}
sourcepub fn to_seconds(self) -> u32
pub fn to_seconds(self) -> u32
return the number of seconds from Epoch to last modification, or 0 if the computation failed
Examples found in repository?
src/tree/tree.rs (line 501)
486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518
fn sort_siblings(&mut self) {
match self.options.sort {
Sort::Count => {
// we'll try to keep the same path selected
let selected_path = self.selected_line().path.to_path_buf();
self.lines[1..].sort_by(|a, b| {
let acount = a.sum.map_or(0, |s| s.to_count());
let bcount = b.sum.map_or(0, |s| s.to_count());
bcount.cmp(&acount)
});
self.try_select_path(&selected_path);
}
Sort::Date => {
let selected_path = self.selected_line().path.to_path_buf();
self.lines[1..].sort_by(|a, b| {
let adate = a.sum.map_or(0, |s| s.to_seconds());
let bdate = b.sum.map_or(0, |s| s.to_seconds());
bdate.cmp(&adate)
});
self.try_select_path(&selected_path);
}
Sort::Size => {
let selected_path = self.selected_line().path.to_path_buf();
self.lines[1..].sort_by(|a, b| {
let asize = a.sum.map_or(0, |s| s.to_size());
let bsize = b.sum.map_or(0, |s| s.to_size());
bsize.cmp(&asize)
});
self.try_select_path(&selected_path);
}
_ => {}
}
}
sourcepub fn to_size(self) -> u64
pub fn to_size(self) -> u64
return the size in bytes
Examples found in repository?
src/display/displayable_tree.rs (line 159)
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
fn write_line_size<'w, W: Write>(
&self,
cw: &mut CropWriter<'w, W>,
line: &TreeLine,
style: &CompoundStyle,
_selected: bool,
) -> Result<usize, termimad::Error> {
Ok(if let Some(s) = line.sum {
cw.queue_g_string(
style,
format!("{:>4}", file_size::fit_4(s.to_size())),
)?;
1
} else {
5
})
}
/// only makes sense when there's only one level
/// (so in sort mode)
fn write_line_size_with_bar<'w, W: Write>(
&self,
cw: &mut CropWriter<'w, W>,
line: &TreeLine,
label_style: &CompoundStyle,
total_size: FileSum,
selected: bool,
) -> Result<usize, termimad::Error> {
Ok(if let Some(s) = line.sum {
let pb = ProgressBar::new(s.part_of_size(total_size), 10);
cond_bg!(sparse_style, self, selected, self.skin.sparse);
cw.queue_g_string(
label_style,
format!("{:>4}", file_size::fit_4(s.to_size())),
)?;
cw.queue_char(
sparse_style,
if s.is_sparse() && line.is_file() { 's' } else { ' ' },
)?;
cw.queue_g_string(label_style, format!("{:<10}", pb))?;
1
} else {
16
})
}
fn write_line_git_status<'w, W: Write>(
&self,
cw: &mut CropWriter<'w, W>,
line: &TreeLine,
selected: bool,
) -> Result<usize, termimad::Error> {
let (style, char) = if !line.is_selectable() {
(&self.skin.tree, ' ')
} else {
match line.git_status.map(|s| s.status) {
Some(Status::CURRENT) => (&self.skin.git_status_current, ' '),
Some(Status::WT_NEW) => (&self.skin.git_status_new, 'N'),
Some(Status::CONFLICTED) => (&self.skin.git_status_conflicted, 'C'),
Some(Status::WT_MODIFIED) => (&self.skin.git_status_modified, 'M'),
Some(Status::IGNORED) => (&self.skin.git_status_ignored, 'I'),
None => (&self.skin.tree, ' '),
_ => (&self.skin.git_status_other, '?'),
}
};
cond_bg!(git_style, self, selected, style);
cw.queue_char(git_style, char)?;
Ok(0)
}
fn write_date<'w, W: Write>(
&self,
cw: &mut CropWriter<'w, W>,
seconds: i64,
selected: bool,
) -> Result<usize, termimad::Error> {
if let LocalResult::Single(date_time) = Local.timestamp_opt(seconds, 0) {
cond_bg!(date_style, self, selected, self.skin.dates);
cw.queue_g_string(
date_style,
date_time
.format(self.tree.options.date_time_format)
.to_string(),
)?;
}
Ok(1)
}
fn write_branch<'w, W: Write>(
&self,
cw: &mut CropWriter<'w, W>,
line_index: usize,
line: &TreeLine,
selected: bool,
staged: bool,
) -> Result<usize, ProgramError> {
cond_bg!(branch_style, self, selected, self.skin.tree);
let mut branch = String::new();
for depth in 0..line.depth {
branch.push_str(
if line.left_branchs[depth as usize] {
if self.tree.has_branch(line_index + 1, depth as usize) {
// TODO: If a theme is on, remove the horizontal lines
if depth == line.depth - 1 {
if staged {
"├◍─"
} else {
"├──"
}
} else {
"│ "
}
} else {
if staged {
"└◍─"
} else {
"└──"
}
}
} else {
" "
},
);
}
if !branch.is_empty() {
cw.queue_g_string(branch_style, branch)?;
}
Ok(0)
}
/// write the symbol showing whether the path is staged
fn write_line_stage_mark<'w, W: Write>(
&self,
cw: &mut CropWriter<'w, W>,
style: &CompoundStyle,
staged: bool,
) -> Result<usize, termimad::Error> {
Ok(if staged {
cw.queue_char(style, '◍')?; // ▣
0
} else {
1
})
}
/// write the name or subpath, depending on the pattern_object
fn write_line_label<'w, W: Write>(
&self,
cw: &mut CropWriter<'w, W>,
line: &TreeLine,
style: &CompoundStyle,
pattern_object: PatternObject,
selected: bool,
) -> Result<usize, ProgramError> {
cond_bg!(char_match_style, self, selected, self.skin.char_match);
if let Some(icon) = line.icon {
cw.queue_char(style, icon)?;
cw.queue_char(style, ' ')?;
cw.queue_char(style, ' ')?;
}
if pattern_object.subpath {
if self.tree.options.show_matching_characters_on_path_searches && line.unlisted == 0 {
let name_match = self.tree.options.pattern.pattern
.search_string(&line.subpath);
let mut path_ms = MatchedString::new(
name_match,
&line.subpath,
style,
char_match_style,
);
let name_ms = path_ms.split_on_last('/');
cond_bg!(parent_style, self, selected, self.skin.parent);
if name_ms.is_some() {
path_ms.base_style = parent_style;
}
path_ms.queue_on(cw)?;
if let Some(name_ms) = name_ms {
name_ms.queue_on(cw)?;
}
} else {
cw.queue_str(style, &line.name)?;
}
} else {
let name_match = self.tree.options.pattern.pattern
.search_string(&line.name);
let matched_string = MatchedString::new(
name_match,
&line.name,
style,
char_match_style,
);
matched_string.queue_on(cw)?;
}
match &line.line_type {
TreeLineType::Dir => {
if line.unlisted > 0 {
cw.queue_str(style, " …")?;
}
}
TreeLineType::BrokenSymLink(direct_path) => {
cw.queue_str(style, " -> ")?;
cond_bg!(error_style, self, selected, self.skin.file_error);
cw.queue_str(error_style, direct_path)?;
}
TreeLineType::SymLink {
final_is_dir,
direct_target,
..
} => {
cw.queue_str(style, " -> ")?;
let target_style = if *final_is_dir {
&self.skin.directory
} else {
&self.skin.file
};
cond_bg!(target_style, self, selected, target_style);
cw.queue_str(target_style, direct_target)?;
}
_ => {}
}
Ok(1)
}
fn write_content_extract<'w, W: Write>(
&self,
cw: &mut CropWriter<'w, W>,
extract: ContentMatch,
selected: bool,
) -> Result<(), ProgramError> {
cond_bg!(extract_style, self, selected, self.skin.content_extract);
cond_bg!(match_style, self, selected, self.skin.content_match);
cw.queue_str(extract_style, " ")?;
if extract.needle_start > 0 {
cw.queue_str(extract_style, &extract.extract[0..extract.needle_start])?;
}
cw.queue_str(
match_style,
&extract.extract[extract.needle_start..extract.needle_end],
)?;
if extract.needle_end < extract.extract.len() {
cw.queue_str(extract_style, &extract.extract[extract.needle_end..])?;
}
Ok(())
}
pub fn write_root_line<'w, W: Write>(
&self,
cw: &mut CropWriter<'w, W>,
selected: bool,
) -> Result<(), ProgramError> {
cond_bg!(style, self, selected, self.skin.directory);
let line = &self.tree.lines[0];
if self.tree.options.show_sizes {
if let Some(s) = line.sum {
cw.queue_g_string(
style,
format!("{:>4} ", file_size::fit_4(s.to_size())),
)?;
}
}
let title = line.path.to_string_lossy();
cw.queue_str(style, &title)?;
if self.in_app && !cw.is_full() {
if let ComputationResult::Done(git_status) = &self.tree.git_status {
let git_status_display = GitStatusDisplay::from(
git_status,
self.skin,
cw.allowed,
);
git_status_display.write(cw, selected)?;
}
#[cfg(unix)]
if self.tree.options.show_root_fs {
if let Some(mount) = line.mount() {
let fs_space_display = crate::filesystems::MountSpaceDisplay::from(
&mount,
self.skin,
cw.allowed,
);
fs_space_display.write(cw, selected)?;
}
}
self.extend_line_bg(cw, selected)?;
}
Ok(())
}
More examples
src/tree/tree.rs (line 510)
486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518
fn sort_siblings(&mut self) {
match self.options.sort {
Sort::Count => {
// we'll try to keep the same path selected
let selected_path = self.selected_line().path.to_path_buf();
self.lines[1..].sort_by(|a, b| {
let acount = a.sum.map_or(0, |s| s.to_count());
let bcount = b.sum.map_or(0, |s| s.to_count());
bcount.cmp(&acount)
});
self.try_select_path(&selected_path);
}
Sort::Date => {
let selected_path = self.selected_line().path.to_path_buf();
self.lines[1..].sort_by(|a, b| {
let adate = a.sum.map_or(0, |s| s.to_seconds());
let bdate = b.sum.map_or(0, |s| s.to_seconds());
bdate.cmp(&adate)
});
self.try_select_path(&selected_path);
}
Sort::Size => {
let selected_path = self.selected_line().path.to_path_buf();
self.lines[1..].sort_by(|a, b| {
let asize = a.sum.map_or(0, |s| s.to_size());
let bsize = b.sum.map_or(0, |s| s.to_size());
bsize.cmp(&asize)
});
self.try_select_path(&selected_path);
}
_ => {}
}
}
src/stage/stage_state.rs (line 118)
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
fn write_title_line(
&self,
stage: &Stage,
cw: &mut CropWriter<'_, W>,
styles: &StyleMap,
) -> Result<(), ProgramError> {
let total_count = format!("{}", stage.len());
let mut count_len = total_count.len();
if self.filtered_stage.pattern().is_some() {
count_len += total_count.len() + 1; // 1 for '/'
}
if cw.allowed < count_len {
return Ok(());
}
if TITLE.len() + 1 + count_len <= cw.allowed {
cw.queue_str(
&styles.staging_area_title,
TITLE,
)?;
}
let mut show_count_label = false;
let mut rem = cw.allowed - count_len;
if COUNT_LABEL.len() < rem {
rem -= COUNT_LABEL.len();
show_count_label = true;
if self.tree_options.show_sizes {
if let Some(sum) = self.stage_sum.computed() {
let size = file_size::fit_4(sum.to_size());
let size_len = SIZE_LABEL.len() + size.len();
if size_len < rem {
rem -= size_len;
// we display the size in the middle, so we cut rem in two
let left_rem = rem / 2;
rem -= left_rem;
cw.repeat(&styles.staging_area_title, &SPACE_FILLING, left_rem)?;
cw.queue_g_string(
&styles.staging_area_title,
SIZE_LABEL.to_string(),
)?;
cw.queue_g_string(
&styles.staging_area_title,
size,
)?;
}
}
}
}
cw.repeat(&styles.staging_area_title, &SPACE_FILLING, rem)?;
if show_count_label {
cw.queue_g_string(
&styles.staging_area_title,
COUNT_LABEL.to_string(),
)?;
}
if self.filtered_stage.pattern().is_some() {
cw.queue_g_string(
&styles.char_match,
format!("{}", self.filtered_stage.len()),
)?;
cw.queue_char(
&styles.staging_area_title,
'/',
)?;
}
cw.queue_g_string(
&styles.staging_area_title,
total_count,
)?;
cw.fill(&styles.staging_area_title, &SPACE_FILLING)?;
Ok(())
}
sourcepub fn to_valid_seconds(self) -> Option<i64>
pub fn to_valid_seconds(self) -> Option<i64>
Examples found in repository?
src/display/displayable_tree.rs (line 567)
454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633
pub fn write_on<W: Write>(&self, f: &mut W) -> Result<(), ProgramError> {
#[cfg(not(any(target_family = "windows", target_os = "android")))]
let perm_writer = super::PermWriter::for_tree(self.skin, self.tree);
let tree = self.tree;
let total_size = tree.total_sum();
let scrollbar = if self.in_app {
termimad::compute_scrollbar(
tree.scroll,
tree.lines.len() - 1, // the root line isn't scrolled
self.area.height - 1, // the scrollbar doesn't cover the first line
self.area.top + 1,
)
} else {
None
};
if self.in_app {
f.queue(cursor::MoveTo(self.area.left, self.area.top))?;
}
let mut cw = CropWriter::new(f, self.area.width as usize);
let pattern_object = tree.options.pattern.pattern.object();
self.write_root_line(&mut cw, self.in_app && tree.selection == 0)?;
self.skin.queue_reset(f)?;
let visible_cols: Vec<Col> = tree
.options
.cols_order
.iter()
.filter(|col| col.is_visible(tree, self.app_state))
.cloned()
.collect();
// if necessary we compute the width of the count column
let count_len = if tree.options.show_counts {
tree.lines.iter()
.skip(1) // we don't show the counts of the root
.map(|l| l.sum.map_or(0, |s| s.to_count()))
.max()
.map(|c| format_count(c).len())
.unwrap_or(0)
} else {
0
};
// we compute the length of the dates, depending on the format
let date_len = if tree.options.show_dates {
let date_time: DateTime<Local> = Local::now();
date_time.format(tree.options.date_time_format).to_string().len()
} else {
0 // we don't care
};
for y in 1..self.area.height {
if self.in_app {
f.queue(cursor::MoveTo(self.area.left, y + self.area.top))?;
} else {
write!(f, "\r\n")?;
}
let mut line_index = y as usize;
if line_index > 0 {
line_index += tree.scroll as usize;
}
let mut selected = false;
let mut cw = CropWriter::new(f, self.area.width as usize);
let cw = &mut cw;
if line_index < tree.lines.len() {
let line = &tree.lines[line_index];
selected = self.in_app && line_index == tree.selection;
let label_style = self.label_style(line, selected);
let mut in_branch = false;
let space_style = if selected {
&self.skin.selected_line
} else {
&self.skin.default
};
if visible_cols[0].needs_left_margin() {
cw.queue_char(space_style, ' ')?;
}
let staged = self.app_state
.map_or(false, |a| a.stage.contains(&line.path));
for col in &visible_cols {
let void_len = match col {
Col::Mark => {
self.write_line_selection_mark(cw, &label_style, selected)?
}
Col::Git => {
self.write_line_git_status(cw, line, selected)?
}
Col::Branch => {
in_branch = true;
self.write_branch(cw, line_index, line, selected, staged)?
}
Col::DeviceId => {
#[cfg(not(unix))]
{ 0 }
#[cfg(unix)]
self.write_line_device_id(cw, line, selected)?
}
Col::Permission => {
#[cfg(any(target_family = "windows", target_os = "android"))]
{ 0 }
#[cfg(not(any(target_family = "windows", target_os = "android")))]
perm_writer.write_permissions(cw, line, selected)?
}
Col::Date => {
if let Some(seconds) = line.sum.and_then(|sum| sum.to_valid_seconds()) {
self.write_date(cw, seconds, selected)?
} else {
date_len + 1
}
}
Col::Size => {
if tree.options.sort.prevent_deep_display() {
// as soon as there's only one level displayed we can show the size bars
self.write_line_size_with_bar(cw, line, &label_style, total_size, selected)?
} else {
self.write_line_size(cw, line, &label_style, selected)?
}
}
Col::Count => {
self.write_line_count(cw, line, count_len, selected)?
}
Col::Staged => {
self.write_line_stage_mark(cw, &label_style, staged)?
}
Col::Name => {
in_branch = false;
self.write_line_label(cw, line, &label_style, pattern_object, selected)?
}
};
// void: intercol & replacing missing cells
if in_branch && void_len > 2 {
cond_bg!(void_style, self, selected, self.skin.tree);
cw.repeat(void_style, &BRANCH_FILLING, void_len)?;
} else {
cond_bg!(void_style, self, selected, self.skin.default);
cw.repeat(void_style, &SPACE_FILLING, void_len)?;
}
}
if cw.allowed > 8 && pattern_object.content {
let extract = tree.options.pattern.pattern
.search_content(&line.path, cw.allowed - 2);
if let Some(extract) = extract {
self.write_content_extract(cw, extract, selected)?;
}
}
}
self.extend_line_bg(cw, selected)?;
self.skin.queue_reset(f)?;
if self.in_app {
if let Some((sctop, scbottom)) = scrollbar {
f.queue(cursor::MoveTo(self.area.left + self.area.width - 1, y))?;
let style = if sctop <= y && y <= scbottom {
&self.skin.scrollbar_thumb
} else {
&self.skin.scrollbar_track
};
style.queue_str(f, "▐")?;
}
}
}
if !self.in_app {
write!(f, "\r\n")?;
}
Ok(())
}
sourcepub fn is_sparse(self) -> bool
pub fn is_sparse(self) -> bool
tell whether the file has holes (in which case the size displayed by other tools may be greater than the “real” one returned by broot). Not computed (return false) on windows or for directories.
Examples found in repository?
src/display/displayable_tree.rs (line 186)
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
fn write_line_size_with_bar<'w, W: Write>(
&self,
cw: &mut CropWriter<'w, W>,
line: &TreeLine,
label_style: &CompoundStyle,
total_size: FileSum,
selected: bool,
) -> Result<usize, termimad::Error> {
Ok(if let Some(s) = line.sum {
let pb = ProgressBar::new(s.part_of_size(total_size), 10);
cond_bg!(sparse_style, self, selected, self.skin.sparse);
cw.queue_g_string(
label_style,
format!("{:>4}", file_size::fit_4(s.to_size())),
)?;
cw.queue_char(
sparse_style,
if s.is_sparse() && line.is_file() { 's' } else { ' ' },
)?;
cw.queue_g_string(label_style, format!("{:<10}", pb))?;
1
} else {
16
})
}
Trait Implementations§
source§impl AddAssign<FileSum> for FileSum
impl AddAssign<FileSum> for FileSum
source§fn add_assign(&mut self, other: Self)
fn add_assign(&mut self, other: Self)
Performs the
+=
operation. Read more