Last active
March 26, 2020 21:09
-
-
Save selahattinunlu/e832d84dfdcad4523bbf3421a05eb845 to your computer and use it in GitHub Desktop.
jr-du using go :))
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"errors" | |
"fmt" | |
"io/ioutil" | |
"os" | |
"path" | |
) | |
/* | |
jr-du :) | |
*/ | |
type Path struct { | |
Name string | |
Size int64 | |
IsDir bool | |
} | |
func PrintDefaultMessage() { | |
fmt.Println("Give a valid path to calculation") | |
} | |
func checks(err error) { | |
if err != nil { | |
panic(err) | |
} | |
} | |
func isDir(path string) bool { | |
stat, err := os.Stat(path) | |
checks(err) | |
return stat.IsDir() | |
} | |
func calculateDirectorySize(directoryPath string) (int64, error) { | |
if !isDir(directoryPath) { | |
return 0, errors.New("Please enter a valid directory path") | |
} | |
var size int64 = 0 | |
entries, _ := ioutil.ReadDir(directoryPath) | |
for _, entry := range entries { | |
if entry.IsDir() { | |
directorySize, _ := calculateDirectorySize(path.Join(directoryPath, entry.Name())) | |
size += directorySize | |
} else { | |
size += entry.Size() | |
} | |
} | |
return size, nil | |
} | |
func main() { | |
if len(os.Args) == 1 { | |
PrintDefaultMessage() | |
os.Exit(2) | |
} | |
pathArg := os.Args[1] | |
if !isDir(pathArg) { | |
panic("Please enter a valid directory path... Not a file...") | |
} | |
entries, err := ioutil.ReadDir(pathArg) | |
checks(err) | |
paths := make([]Path, 0) | |
for _, v := range entries { | |
pathInst := Path{Name: v.Name(), IsDir: v.IsDir()} | |
if pathInst.IsDir { | |
pathInst.Size, _ = calculateDirectorySize(path.Join(pathArg, pathInst.Name)) | |
} else { | |
pathInst.Size = v.Size() | |
} | |
paths = append(paths, pathInst) | |
} | |
for _, v := range paths { | |
fmt.Printf("Name: %s - Size: %d\n", v.Name, v.Size) | |
} | |
os.Exit(0) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment