fork/gdu
git clone https://git.julia.blue/fork/gdu
4d478cf
subvolume
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 .ShouldIgnore ,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 242switch { 243case ui .top > 0 : 244ui .printTopFiles (dir ) 245case ui .depth > 0 : 246ui .printDirWithDepth (dir ,0 ) 247case ui .summarize : 248ui .printTotalItem (dir ) 249default : 250ui .showDir (dir ) 251 } 252 253return nil 254} 255 256// ReadFromStorage reads analysis data from persistent key-value storage 257func (ui * UI )ReadFromStorage (storagePath ,path string )error { 258storage := analyze .NewStorage (storagePath ,path ) 259closeFn := storage .Open () 260defer closeFn () 261 262dir ,err := storage .GetDirForPath (path ) 263if err != nil { 264return err 265 } 266 267switch { 268case ui .top > 0 : 269ui .printTopFiles (dir ) 270case ui .summarize : 271ui .printTotalItem (dir ) 272default : 273ui .showDir (dir ) 274 } 275return nil 276} 277 278func (ui * UI )showDir (dir fs.Item ) { 279sortOrder := fs .SortDesc 280if ui .reverseSort { 281sortOrder = fs .SortAsc 282 } 283 284sort := fs .SortBySize 285if ui .ShowApparentSize { 286sort = fs .SortByApparentSize 287 } 288 289for file := range dir .GetFiles (sort ,sortOrder ) { 290ui .printItem (file ) 291 } 292} 293 294func (ui * UI )printTopFiles (file fs.Item ) { 295collected := analyze .CollectTopFiles (file ,ui .top ) 296for _ ,file := range collected { 297ui .printItemPath (file ) 298 } 299} 300 301func (ui * UI )printTotalItem (file fs.Item ) { 302var lineFormat string 303if ui .UseColors { 304lineFormat = "%20s %s\n" 305 }else { 306lineFormat = "%9s %s\n" 307 } 308 309var size int64 310if ui .ShowApparentSize { 311size = file .GetSize () 312 }else { 313size = file .GetUsage () 314 } 315 316fmt .Fprintf ( 317ui .output , 318lineFormat , 319ui .formatSize (size ), 320file .GetName (), 321 ) 322} 323 324func (ui * UI )printItem (file fs.Item ) { 325var lineFormat string 326if ui .showItemCnt { 327if ui .UseColors { 328lineFormat = "%s %23s %25s %s\n" 329 }else { 330lineFormat = "%s %9s %11s %s\n" 331 } 332 }else { 333if ui .UseColors { 334lineFormat = "%s %23s %s\n" 335 }else { 336lineFormat = "%s %9s %s\n" 337 } 338 } 339 340var size int64 341if ui .ShowApparentSize { 342size = file .GetSize () 343 }else { 344size = file .GetUsage () 345 } 346 347name := file .GetName () 348if file .IsDir () { 349name = ui .blue .Sprint ("/" + file .GetName ()) 350 } 351 352// Append symlink target with cyan name (like ls --color) 353if ui .showSymlinkTarget { 354if si ,ok := file .(fs.SymlinkItem );ok { 355if target := si .GetSymlinkTarget ();target != "" { 356name = ui .cyan .Sprint (file .GetName ())+ " -> " + target 357 } 358 } 359 } 360 361if ui .showItemCnt { 362fmt .Fprintf ( 363ui .output , 364lineFormat , 365string (file .GetFlag ()), 366ui .formatSize (size ), 367ui .formatCount (file .GetItemCount ()), 368name , 369 ) 370return 371 } 372 373fmt .Fprintf ( 374ui .output , 375lineFormat , 376string (file .GetFlag ()), 377ui .formatSize (size ), 378name , 379 ) 380} 381 382func (ui * UI )printItemPath (file fs.Item ) { 383var lineFormat string 384if ui .UseColors { 385lineFormat = "%20s %s\n" 386 }else { 387lineFormat = "%9s %s\n" 388 } 389 390var size int64 391if ui .ShowApparentSize { 392size = file .GetSize () 393 }else { 394size = file .GetUsage () 395 } 396 397if file .IsDir () { 398fmt .Fprintf (ui .output , 399lineFormat , 400ui .formatSize (size ), 401ui .blue .Sprint (file .GetPath ())) 402 }else { 403fmt .Fprintf (ui .output , 404lineFormat , 405ui .formatSize (size ), 406file .GetPath ()) 407 } 408} 409 410func (ui * UI )printDirWithDepth (dir fs.Item ,currentDepth int ) { 411// Print current directory 412ui .printItemPath (dir ) 413 414// If we haven't reached the max depth, print contents 415if currentDepth < ui .depth && dir .IsDir () { 416sortOrder := fs .SortDesc 417if ui .reverseSort { 418sortOrder = fs .SortAsc 419 } 420 421files := dir .GetFiles (fs .SortBySize ,sortOrder ) 422 423// Print all files at this depth level 424for file := range files { 425if file .IsDir () { 426// Recurse into subdirectories 427ui .printDirWithDepth (file ,currentDepth + 1 ) 428 }else { 429// Print regular files 430ui .printItemPath (file ) 431 } 432 } 433 } 434} 435 436// ReadAnalysis reads analysis report from JSON file 437func (ui * UI )ReadAnalysis (input io.Reader )error { 438var ( 439dir fs.Item 440wait sync.WaitGroup 441err error 442doneChan chan struct {} 443 ) 444 445if ui .ShowProgress { 446wait .Add (1 ) 447doneChan = make (chan struct {}) 448go func () { 449defer wait .Done () 450ui .showReadingProgress (doneChan ) 451 }() 452 } 453 454wait .Add (1 ) 455go func () { 456defer wait .Done () 457dir ,err = report .ReadAnalysis (input ) 458if err != nil { 459if ui .ShowProgress { 460doneChan <- struct {}{} 461 } 462return 463 } 464runtime .GC () 465 466if ui .IsFilteringFiles () { 467dir .UpdateStatsWithFileFiltering (make (fs.HardLinkedItems ,10 )) 468 }else { 469dir .UpdateStats (make (fs.HardLinkedItems ,10 )) 470 } 471 472if ui .ShowProgress { 473doneChan <- struct {}{} 474 } 475 }() 476 477wait .Wait () 478 479if err != nil { 480return err 481 } 482 483if ui .summarize { 484ui .printTotalItem (dir ) 485 }else { 486ui .showDir (dir ) 487 } 488 489return nil 490} 491 492func (ui * UI )showReadingProgress (doneChan chan struct {}) { 493emptyRow := "\r" 494for j := 0 ;j < 40 ;j ++ { 495emptyRow += " " 496 } 497 498i := 0 499for { 500fmt .Fprint (ui .output ,emptyRow ) 501 502select { 503case <- doneChan : 504fmt .Fprint (ui .output ,"\r" ) 505return 506default : 507 } 508 509fmt .Fprintf (ui .output ,"\r %s " ,string (progressRunes [i ])) 510fmt .Fprint (ui .output ,"Reading analysis from file..." ) 511 512time .Sleep (100 * time .Millisecond ) 513i ++ 514i %= progressRunesCount 515 } 516} 517 518func (ui * UI )updateProgress (updateStatsDone <- chan struct {}) { 519emptyRow := "\r" 520for j := 0 ;j < 100 ;j ++ { 521emptyRow += " " 522 } 523 524analysisDoneChan := ui .Analyzer .GetDone () 525ticker := time .NewTicker (100 * time .Millisecond ) 526defer ticker .Stop () 527 528i := 0 529for { 530select { 531case <- ticker .C : 532progress := ui .Analyzer .GetProgress () 533fmt .Fprint (ui .output ,emptyRow ) 534fmt .Fprintf (ui .output ,"\r %s " ,string (progressRunes [i ])) 535fmt .Fprint (ui .output ,"Scanning... Total items: " + 536ui .red .Sprint (common .FormatNumber (int64 (progress .ItemCount )))+ 537" size: " + 538ui .formatSize (progress .TotalUsage )) 539i ++ 540i %= progressRunesCount 541case <- analysisDoneChan : 542ticker .Stop () 543fmt .Fprint (ui .output ,emptyRow ) 544for { 545fmt .Fprint (ui .output ,emptyRow ) 546fmt .Fprintf (ui .output ,"\r %s " ,string (progressRunes [i ])) 547fmt .Fprint (ui .output ,"Calculating disk usage..." ) 548time .Sleep (100 * time .Millisecond ) 549i ++ 550i %= progressRunesCount 551 552select { 553case <- updateStatsDone : 554fmt .Fprint (ui .output ,emptyRow ) 555fmt .Fprint (ui .output ,"\r" ) 556return 557default : 558 } 559 } 560 } 561 } 562} 563 564func (ui * UI )formatCount (count int64 )string { 565count64 := float64 (count ) 566 567switch { 568case count64 >= common .G : 569return ui .red .Sprintf ("%.1f" ,float64 (count )/ float64 (common .G ))+ "G" 570case count64 >= common .M : 571return ui .red .Sprintf ("%.1f" ,float64 (count )/ float64 (common .M ))+ "M" 572case count64 >= common .K : 573return ui .red .Sprintf ("%.1f" ,float64 (count )/ float64 (common .K ))+ "k" 574default : 575return ui .red .Sprintf ("%d" ,count ) 576 } 577} 578 579func (ui * UI )formatSize (size int64 )string { 580if ui .noPrefix { 581return ui .orange .Sprintf ("%d" ,size ) 582 } 583if formatted ,ok := ui .FormatBlockSize (size );ok { 584return ui .orange .Sprint (formatted ) 585 } 586if ui .fixedBase > 0 { 587val := float64 (size )/ ui .fixedBase 588return ui .orange .Sprintf ("%.1f" ,val )+ ui .fixedSuffix 589 } 590if ui .UseSIPrefix { 591return ui .formatWithDecPrefix (size ) 592 } 593return ui .formatWithBinPrefix (size ) 594} 595 596func (ui * UI )formatWithBinPrefix (size int64 )string { 597fsize := float64 (size ) 598asize := math .Abs (fsize ) 599 600switch { 601case asize >= common .Ei : 602return ui .orange .Sprintf ("%.1f" ,fsize / common .Ei )+ " EiB" 603case asize >= common .Pi : 604return ui .orange .Sprintf ("%.1f" ,fsize / common .Pi )+ " PiB" 605case asize >= common .Ti : 606return ui .orange .Sprintf ("%.1f" ,fsize / common .Ti )+ " TiB" 607case asize >= common .Gi : 608return ui .orange .Sprintf ("%.1f" ,fsize / common .Gi )+ " GiB" 609case asize >= common .Mi : 610return ui .orange .Sprintf ("%.1f" ,fsize / common .Mi )+ " MiB" 611case asize >= common .Ki : 612return ui .orange .Sprintf ("%.1f" ,fsize / common .Ki )+ " KiB" 613default : 614return ui .orange .Sprintf ("%d" ,size )+ " B" 615 } 616} 617 618func (ui * UI )formatWithDecPrefix (size int64 )string { 619fsize := float64 (size ) 620asize := math .Abs (fsize ) 621 622switch { 623case asize >= common .E : 624return ui .orange .Sprintf ("%.1f" ,fsize / common .E )+ " EB" 625case asize >= common .P : 626return ui .orange .Sprintf ("%.1f" ,fsize / common .P )+ " PB" 627case asize >= common .T : 628return ui .orange .Sprintf ("%.1f" ,fsize / common .T )+ " TB" 629case asize >= common .G : 630return ui .orange .Sprintf ("%.1f" ,fsize / common .G )+ " GB" 631case asize >= common .M : 632return ui .orange .Sprintf ("%.1f" ,fsize / common .M )+ " MB" 633case asize >= common .K : 634return ui .orange .Sprintf ("%.1f" ,fsize / common .K )+ " kB" 635default : 636return ui .orange .Sprintf ("%d" ,size )+ " B" 637 } 638} 639 640func maxLength (list []* device.Device ,keyGetter func (* device.Device )string )int { 641maxLen := 0 642var s string 643for _ ,item := range list { 644s = keyGetter (item ) 645if len (s )> maxLen { 646maxLen = len (s ) 647 } 648 } 649return maxLen 650} 651 652func maxInt (x ,y int )int { 653if x > y { 654return x 655 } 656return y 657}