Skip to content

Instantly share code, notes, and snippets.

@zeroidentidad
Created September 26, 2023 04:14
Show Gist options
  • Save zeroidentidad/ae69a1bfe801f3296b7571374c06ef69 to your computer and use it in GitHub Desktop.
Save zeroidentidad/ae69a1bfe801f3296b7571374c06ef69 to your computer and use it in GitHub Desktop.
get the disk usage of a directory.
package main
import (
"fmt"
"os"
"path/filepath"
)
func main() {
path, _ := os.Getwd()
if len(os.Args) == 2 {
path = os.Args[1]
}
fmt.Println("Scanning", path)
reportUsage(path)
}
func reportUsage(path string) {
f, _ := os.Open(path)
files, _ := f.Readdir(-1)
f.Close()
result := make(chan sizeInfo)
for _, file := range files {
go dirSize(filepath.Join(path, file.Name()), result)
}
var total int64
results := 0
for info := range result {
total += info.size
fmt.Printf("%s:\t%d\n", info.name, info.size)
results++
if results == len(files) {
break
}
}
fmt.Printf("\nTotal:\t\t%d\n", total)
}
type sizeInfo struct {
name string
size int64
}
func dirSize(path string, result chan sizeInfo) {
var size int64
filepath.Walk(path, func(_ string, file os.FileInfo, err error) error {
if err == nil {
size += file.Size()
}
return nil
})
result <- sizeInfo{filepath.Base(path), size}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment