fork/gdu
git clone https://git.julia.blue/fork/gdu
34f3996
master
1package stdout 2 3import ( 4"fmt" 5"io" 6"math" 7"os" 8"path/filepath" 9"runtime" 10"sync" 11"time" 12 13"github.com/dundee/gdu/v5/internal/common" 14"github.com/dundee/gdu/v5/pkg/analyze" 15"github.com/dundee/gdu/v5/pkg/device" 16"github.com/dundee/gdu/v5/pkg/fs" 17"github.com/dundee/gdu/v5/report" 18"github.com/fatih/color" 19) 20 21// UI struct 22type UI struct { 23output io.Writer 24* common.UI 25red * color.Color 26orange * color.Color 27blue * color.Color 28cyan * color.Color 29showItemCnt bool 30showSymlinkTarget bool 31top int 32depth int 33summarize bool 34noPrefix bool 35fixedBase float64 36fixedSuffix string 37reverseSort bool 38} 39 40var ( 41progressRunes = []rune (`⠇⠏⠋⠙⠹⠸⠼⠴⠦⠧` ) 42progressRunesOld = []rune (`-\\|/` ) 43progressRunesCount = len (progressRunes ) 44) 45 46// CreateStdoutUI creates UI for stdout 47func CreateStdoutUI ( 48output io.Writer , 49useColors bool , 50showProgress bool , 51showApparentSize bool , 52showRelativeSize bool , 53summarize bool , 54useSIPrefix bool , 55noPrefix bool , 56fixedUnit string , 57top int , 58reverseSort bool , 59depth int , 60)* UI { 61ui := & UI { 62UI :& common.UI { 63UseColors :useColors , 64ShowProgress :showProgress , 65ShowApparentSize :showApparentSize , 66ShowRelativeSize :showRelativeSize , 67Analyzer :analyze .CreateTopDirAnalyzer (), 68UseSIPrefix :useSIPrefix , 69 }, 70output :output , 71summarize :summarize , 72noPrefix :noPrefix , 73top :top , 74reverseSort :reverseSort , 75depth :depth , 76 } 77if fixedUnit != "" { 78ui .SetFixedUnit (fixedUnit ) 79 }else if ! noPrefix && ! useSIPrefix { 80ui .SetBlockSizeFromEnvironment () 81 } 82ui .red = color .New (color .FgRed ).Add (color .Bold ) 83ui .orange = color .New (color .FgYellow ).Add (color .Bold ) 84ui .blue = color .New (color .FgBlue ).Add (color .Bold ) 85ui .cyan = color .New (color .FgCyan ).Add (color .Bold ) 86 87if ui .top > 0 || ui .depth > 0 { 88ui .Analyzer = analyze .CreateAnalyzer () 89 } 90 91if ! useColors { 92color .NoColor = true 93 } 94 95return ui 96} 97func (ui * UI )SetFixedUnit (unitChar string ) { 98k ,m ,g := common .Ki ,common .Mi ,common .Gi 99suffixMap := map [string ]string {"k" :" KiB" ,"m" :" MiB" ,"g" :" GiB" } 100 101if ui .UseSIPrefix { 102k ,m ,g = common .K ,common .M ,common .G 103suffixMap = map [string ]string {"k" :" kB" ,"m" :" MB" ,"g" :" GB" } 104 } 105 106switch unitChar { 107case "k" : 108ui .fixedBase = k 109ui .fixedSuffix = suffixMap ["k" ] 110case "m" : 111ui .fixedBase = m 112ui .fixedSuffix = suffixMap ["m" ] 113case "g" : 114ui .fixedBase = g 115ui .fixedSuffix = suffixMap ["g" ] 116 } 117} 118 119func (ui * UI )SetShowItemCount () { 120ui .showItemCnt = true 121} 122 123// SetShowSymlinkTarget enables displaying the symlink target (name -> target). 124func (ui * UI )SetShowSymlinkTarget (value bool ) { 125ui .showSymlinkTarget = value 126} 127 128func (ui * UI )UseOldProgressRunes () { 129progressRunes = progressRunesOld 130progressRunesCount = len (progressRunes ) 131} 132 133// StartUILoop stub 134func (ui * UI )StartUILoop ()error { 135return nil 136} 137 138// SetCollapsePath sets the flag to collapse paths 139func (ui * UI )SetCollapsePath (value bool ) { 140} 141 142// ListDevices lists mounted devices and shows their disk usage 143func (ui * UI )ListDevices (getter device.DevicesInfoGetter )error { 144devices ,err := getter .GetDevicesInfo () 145if err != nil { 146return err 147 } 148 149maxDeviceNameLength := maxInt (maxLength ( 150devices , 151func (device * device.Device )string {return device .Name }, 152 ),len ("Devices" )) 153 154var sizeLength ,percentLength int 155if ui .UseColors { 156sizeLength = 20 157percentLength = 16 158 }else { 159sizeLength = 9 160percentLength = 5 161 } 162 163lineFormat := fmt .Sprintf ( 164"%%%ds %%%ds %%%ds %%%ds %%%ds %%s\n" , 165maxDeviceNameLength , 166sizeLength , 167sizeLength , 168sizeLength , 169percentLength , 170 ) 171 172fmt .Fprintf ( 173ui .output , 174fmt .Sprintf ("%%%ds %%9s %%9s %%9s %%5s %%s\n" ,maxDeviceNameLength ), 175"Device" , 176"Size" , 177"Used" , 178"Free" , 179"Used%" , 180"Mount point" , 181 ) 182 183for _ ,device := range devices { 184usedPercent := math .Round (float64 (device .Size - device .Free )/ float64 (device .Size )* 100 ) 185 186fmt .Fprintf ( 187ui .output , 188lineFormat , 189device .Name , 190ui .formatSize (device .Size ), 191ui .formatSize (device .Size - device .Free ), 192ui .formatSize (device .Free ), 193ui .red .Sprintf ("%.f%%" ,usedPercent ), 194device .MountPoint ) 195 } 196 197return nil 198} 199 200// AnalyzePath analyzes recursively disk usage in given path 201func (ui * UI )AnalyzePath (path string ,_ fs.Item )error { 202// When path is a regular file, create a File item directly so that 203// apparent-size (GetSize) and disk-usage (GetUsage) are both correct. 204// Running a file through AnalyzeDir + UpdateStats would report the 205// default 4096-byte directory overhead instead of the real values. 206info ,err := os .Stat (path ) 207if err == nil && info .Mode ().IsRegular () { 208file := analyze .CreateFileItem (filepath .Base (path ),info ) 209ui .printTotalItem (file ) 210return nil 211 } 212 213var ( 214dir fs.Item 215wait sync.WaitGroup 216updateStatsDone chan struct {} 217 ) 218updateStatsDone = make (chan struct {},1 ) 219 220if ui .ShowProgress { 221wait .Add (1 ) 222go func () { 223defer wait .Done () 224ui .updateProgress (updateStatsDone ) 225 }() 226 } 227 228wait .Add (1 ) 229go func () { 230defer wait .Done () 231dir = ui .Analyzer .AnalyzeDir (path ,ui .CreateIgnoreFunc (),ui .CreateFileTypeFilter ()) 232if ui .IsFilteringFiles () { 233dir .UpdateStatsWithFileFiltering (make (fs.HardLinkedItems ,10 )) 234 }else { 235dir .UpdateStats (make (fs.HardLinkedItems ,10 )) 236 } 237updateStatsDone <- struct {}{} 238 }() 239 240wait .Wait () 241 242ui .printAnalyzedDir (dir ) 243 244return nil 245} 246 247// AnalyzePaths analyzes several paths and reports them together, grouped under 248// a virtual top level directory. 249func (ui * UI )AnalyzePaths (paths []string )error { 250if len (paths )== 1 { 251return ui .AnalyzePath (paths [0 ],nil ) 252 } 253 254// The top dir analyzer returns SimpleDir, a reduced item that cannot be 255// re-parented, so it cannot live under a virtual root. Trade its lower 256// memory use for the full tree, as --top and --depth already do. 257if _ ,ok := ui .Analyzer .(* analyze.TopDirAnalyzer );ok { 258ui .Analyzer = analyze .CreateAnalyzer () 259 } 260 261roots := make ([]fs.Item ,0 ,len (paths )) 262for _ ,path := range paths { 263// the analyzer owns one set of progress channels per scan, so it has to 264// be reset before each root - and before updateProgress reads its done 265// channel 266ui .Analyzer .ResetProgress () 267 268var wait sync.WaitGroup 269updateStatsDone := make (chan struct {},1 ) 270 271if ui .ShowProgress { 272wait .Add (1 ) 273go func () { 274defer wait .Done () 275ui .updateProgress (updateStatsDone ) 276 }() 277 } 278 279root := ui .Analyzer .AnalyzeDir (path ,ui .CreateIgnoreFunc (),ui .CreateFileTypeFilter ()) 280updateStatsDone <- struct {}{} 281wait .Wait () 282 283roots = append (roots ,root ) 284 } 285 286dir := analyze .CreateVirtualRootDir (roots ... ) 287if ui .IsFilteringFiles () { 288dir .UpdateStatsWithFileFiltering (make (fs.HardLinkedItems ,10 )) 289 }else { 290dir .UpdateStats (make (fs.HardLinkedItems ,10 )) 291 } 292 293ui .printAnalyzedDir (dir ) 294 295return nil 296} 297 298func (ui * UI )printAnalyzedDir (dir fs.Item ) { 299switch { 300case ui .top > 0 : 301ui .printTopFiles (dir ) 302case ui .depth > 0 : 303ui .printDirWithDepth (dir ,0 ) 304case ui .summarize : 305ui .printTotalItem (dir ) 306default : 307ui .showDir (dir ) 308 } 309} 310 311// ReadFromStorage reads analysis data from persistent key-value storage 312func (ui * UI )ReadFromStorage (storagePath ,path string )error { 313storage := analyze .NewStorage (storagePath ,path ) 314closeFn := storage .Open () 315defer closeFn () 316 317dir ,err := storage .GetDirForPath (path ) 318if err != nil { 319return err 320 } 321 322switch { 323case ui .top > 0 : 324ui .printTopFiles (dir ) 325case ui .summarize : 326ui .printTotalItem (dir ) 327default : 328ui .showDir (dir ) 329 } 330return nil 331} 332 333func (ui * UI )showDir (dir fs.Item ) { 334sortOrder := fs .SortDesc 335if ui .reverseSort { 336sortOrder = fs .SortAsc 337 } 338 339sort := fs .SortBySize 340if ui .ShowApparentSize { 341sort = fs .SortByApparentSize 342 } 343 344for file := range dir .GetFiles (sort ,sortOrder ) { 345ui .printItem (dir ,file ) 346 } 347} 348 349func (ui * UI )printTopFiles (file fs.Item ) { 350collected := analyze .CollectTopFiles (file ,ui .top ) 351for _ ,file := range collected { 352ui .printItemPath (file ) 353 } 354} 355 356func (ui * UI )printTotalItem (file fs.Item ) { 357var lineFormat string 358if ui .UseColors { 359lineFormat = "%20s %s\n" 360 }else { 361lineFormat = "%9s %s\n" 362 } 363 364var size int64 365if ui .ShowApparentSize { 366size = file .GetSize () 367 }else { 368size = file .GetUsage () 369 } 370 371fmt .Fprintf ( 372ui .output , 373lineFormat , 374ui .formatSize (size ), 375file .GetName (), 376 ) 377} 378 379// printItem prints one row of a directory listing. parent is the directory 380// being listed, which decides how the item is labelled; it may be nil. 381func (ui * UI )printItem (parent ,file fs.Item ) { 382var lineFormat string 383if ui .showItemCnt { 384if ui .UseColors { 385lineFormat = "%s %23s %25s %s\n" 386 }else { 387lineFormat = "%s %9s %11s %s\n" 388 } 389 }else { 390if ui .UseColors { 391lineFormat = "%s %23s %s\n" 392 }else { 393lineFormat = "%s %9s %s\n" 394 } 395 } 396 397var size int64 398if ui .ShowApparentSize { 399size = file .GetSize () 400 }else { 401size = file .GetUsage () 402 } 403 404name := analyze .ItemDisplayName (parent ,file ) 405if file .IsDir () { 406// a scanned root is labelled with its absolute path, which already 407// reads as a path and must not gain another leading separator 408if ! analyze .IsVirtualRootDir (parent ) { 409name = "/" + name 410 } 411name = ui .blue .Sprint (name ) 412 } 413 414// Append symlink target with cyan name (like ls --color) 415if ui .showSymlinkTarget { 416if si ,ok := file .(fs.SymlinkItem );ok { 417if target := si .GetSymlinkTarget ();target != "" { 418name = ui .cyan .Sprint (file .GetName ())+ " -> " + target 419 } 420 } 421 } 422 423if ui .showItemCnt { 424fmt .Fprintf ( 425ui .output , 426lineFormat , 427string (file .GetFlag ()), 428ui .formatSize (size ), 429ui .formatCount (file .GetItemCount ()), 430name , 431 ) 432return 433 } 434 435fmt .Fprintf ( 436ui .output , 437lineFormat , 438string (file .GetFlag ()), 439ui .formatSize (size ), 440name , 441 ) 442} 443 444func (ui * UI )printItemPath (file fs.Item ) { 445var lineFormat string 446if ui .UseColors { 447lineFormat = "%20s %s\n" 448 }else { 449lineFormat = "%9s %s\n" 450 } 451 452var size int64 453if ui .ShowApparentSize { 454size = file .GetSize () 455 }else { 456size = file .GetUsage () 457 } 458 459if file .IsDir () { 460fmt .Fprintf (ui .output , 461lineFormat , 462ui .formatSize (size ), 463ui .blue .Sprint (file .GetPath ())) 464 }else { 465fmt .Fprintf (ui .output , 466lineFormat , 467ui .formatSize (size ), 468file .GetPath ()) 469 } 470} 471 472func (ui * UI )printDirWithDepth (dir fs.Item ,currentDepth int ) { 473// Print current directory 474ui .printItemPath (dir ) 475 476// If we haven't reached the max depth, print contents 477if currentDepth < ui .depth && dir .IsDir () { 478sortOrder := fs .SortDesc 479if ui .reverseSort { 480sortOrder = fs .SortAsc 481 } 482 483files := dir .GetFiles (fs .SortBySize ,sortOrder ) 484 485// Print all files at this depth level 486for file := range files { 487if file .IsDir () { 488// Recurse into subdirectories 489ui .printDirWithDepth (file ,currentDepth + 1 ) 490 }else { 491// Print regular files 492ui .printItemPath (file ) 493 } 494 } 495 } 496} 497 498// ReadAnalysis reads analysis report from JSON file 499func (ui * UI )ReadAnalysis (input io.Reader )error { 500var ( 501dir fs.Item 502wait sync.WaitGroup 503err error 504doneChan chan struct {} 505 ) 506 507if ui .ShowProgress { 508wait .Add (1 ) 509doneChan = make (chan struct {}) 510go func () { 511defer wait .Done () 512ui .showReadingProgress (doneChan ) 513 }() 514 } 515 516wait .Add (1 ) 517go func () { 518defer wait .Done () 519dir ,err = report .ReadAnalysis (input ) 520if err != nil { 521if ui .ShowProgress { 522doneChan <- struct {}{} 523 } 524return 525 } 526runtime .GC () 527 528if ui .IsFilteringFiles () { 529dir .UpdateStatsWithFileFiltering (make (fs.HardLinkedItems ,10 )) 530 }else { 531dir .UpdateStats (make (fs.HardLinkedItems ,10 )) 532 } 533 534if ui .ShowProgress { 535doneChan <- struct {}{} 536 } 537 }() 538 539wait .Wait () 540 541if err != nil { 542return err 543 } 544 545if ui .summarize { 546ui .printTotalItem (dir ) 547 }else { 548ui .showDir (dir ) 549 } 550 551return nil 552} 553 554func (ui * UI )showReadingProgress (doneChan chan struct {}) { 555emptyRow := "\r" 556for j := 0 ;j < 40 ;j ++ { 557emptyRow += " " 558 } 559 560i := 0 561for { 562fmt .Fprint (ui .output ,emptyRow ) 563 564select { 565case <- doneChan : 566fmt .Fprint (ui .output ,"\r" ) 567return 568default : 569 } 570 571fmt .Fprintf (ui .output ,"\r %s " ,string (progressRunes [i ])) 572fmt .Fprint (ui .output ,"Reading analysis from file..." ) 573 574time .Sleep (100 * time .Millisecond ) 575i ++ 576i %= progressRunesCount 577 } 578} 579 580func (ui * UI )updateProgress (updateStatsDone <- chan struct {}) { 581emptyRow := "\r" 582for j := 0 ;j < 100 ;j ++ { 583emptyRow += " " 584 } 585 586analysisDoneChan := ui .Analyzer .GetDone () 587ticker := time .NewTicker (100 * time .Millisecond ) 588defer ticker .Stop () 589 590i := 0 591for { 592select { 593case <- ticker .C : 594progress := ui .Analyzer .GetProgress () 595fmt .Fprint (ui .output ,emptyRow ) 596fmt .Fprintf (ui .output ,"\r %s " ,string (progressRunes [i ])) 597fmt .Fprint (ui .output ,"Scanning... Total items: " + 598ui .red .Sprint (common .FormatNumber (int64 (progress .ItemCount )))+ 599" size: " + 600ui .formatSize (progress .TotalUsage )) 601i ++ 602i %= progressRunesCount 603case <- analysisDoneChan : 604ticker .Stop () 605fmt .Fprint (ui .output ,emptyRow ) 606for { 607fmt .Fprint (ui .output ,emptyRow ) 608fmt .Fprintf (ui .output ,"\r %s " ,string (progressRunes [i ])) 609fmt .Fprint (ui .output ,"Calculating disk usage..." ) 610time .Sleep (100 * time .Millisecond ) 611i ++ 612i %= progressRunesCount 613 614select { 615case <- updateStatsDone : 616fmt .Fprint (ui .output ,emptyRow ) 617fmt .Fprint (ui .output ,"\r" ) 618return 619default : 620 } 621 } 622 } 623 } 624} 625 626func (ui * UI )formatCount (count int64 )string { 627count64 := float64 (count ) 628 629switch { 630case count64 >= common .G : 631return ui .red .Sprintf ("%.1f" ,float64 (count )/ float64 (common .G ))+ "G" 632case count64 >= common .M : 633return ui .red .Sprintf ("%.1f" ,float64 (count )/ float64 (common .M ))+ "M" 634case count64 >= common .K : 635return ui .red .Sprintf ("%.1f" ,float64 (count )/ float64 (common .K ))+ "k" 636default : 637return ui .red .Sprintf ("%d" ,count ) 638 } 639} 640 641func (ui * UI )formatSize (size int64 )string { 642if ui .noPrefix { 643return ui .orange .Sprintf ("%d" ,size ) 644 } 645if formatted ,ok := ui .FormatBlockSize (size );ok { 646return ui .orange .Sprint (formatted ) 647 } 648if ui .fixedBase > 0 { 649val := float64 (size )/ ui .fixedBase 650return ui .orange .Sprintf ("%.1f" ,val )+ ui .fixedSuffix 651 } 652if ui .UseSIPrefix { 653return ui .formatWithDecPrefix (size ) 654 } 655return ui .formatWithBinPrefix (size ) 656} 657 658func (ui * UI )formatWithBinPrefix (size int64 )string { 659fsize := float64 (size ) 660asize := math .Abs (fsize ) 661 662switch { 663case asize >= common .Ei : 664return ui .orange .Sprintf ("%.1f" ,fsize / common .Ei )+ " EiB" 665case asize >= common .Pi : 666return ui .orange .Sprintf ("%.1f" ,fsize / common .Pi )+ " PiB" 667case asize >= common .Ti : 668return ui .orange .Sprintf ("%.1f" ,fsize / common .Ti )+ " TiB" 669case asize >= common .Gi : 670return ui .orange .Sprintf ("%.1f" ,fsize / common .Gi )+ " GiB" 671case asize >= common .Mi : 672return ui .orange .Sprintf ("%.1f" ,fsize / common .Mi )+ " MiB" 673case asize >= common .Ki : 674return ui .orange .Sprintf ("%.1f" ,fsize / common .Ki )+ " KiB" 675default : 676return ui .orange .Sprintf ("%d" ,size )+ " B" 677 } 678} 679 680func (ui * UI )formatWithDecPrefix (size int64 )string { 681fsize := float64 (size ) 682asize := math .Abs (fsize ) 683 684switch { 685case asize >= common .E : 686return ui .orange .Sprintf ("%.1f" ,fsize / common .E )+ " EB" 687case asize >= common .P : 688return ui .orange .Sprintf ("%.1f" ,fsize / common .P )+ " PB" 689case asize >= common .T : 690return ui .orange .Sprintf ("%.1f" ,fsize / common .T )+ " TB" 691case asize >= common .G : 692return ui .orange .Sprintf ("%.1f" ,fsize / common .G )+ " GB" 693case asize >= common .M : 694return ui .orange .Sprintf ("%.1f" ,fsize / common .M )+ " MB" 695case asize >= common .K : 696return ui .orange .Sprintf ("%.1f" ,fsize / common .K )+ " kB" 697default : 698return ui .orange .Sprintf ("%d" ,size )+ " B" 699 } 700} 701 702func maxLength (list []* device.Device ,keyGetter func (* device.Device )string )int { 703maxLen := 0 704var s string 705for _ ,item := range list { 706s = keyGetter (item ) 707if len (s )> maxLen { 708maxLen = len (s ) 709 } 710 } 711return maxLen 712} 713 714func maxInt (x ,y int )int { 715if x > y { 716return x 717 } 718return y 719}