Created
June 5, 2017 03:22
-
-
Save TheLinuxGuy/2dd8ed958d14c491bf86e2f5f3d4688d to your computer and use it in GitHub Desktop.
golang total folder size, backup design question
This file contains 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 ( | |
"fmt" | |
"io/ioutil" | |
"math" | |
"strconv" | |
) | |
// decimal places rounding | |
func round(input float64, places int) (float64) { | |
pow := math.Pow(10, float64(places)) | |
digit := pow * input | |
round := math.Ceil(digit) | |
rounded := round / pow | |
return rounded | |
} | |
// Since we want human readable numbers not bytes (Kilobyte, MB, GB...) | |
func readableByte(input float64, shift int) string { | |
var ( | |
classification string | |
size float64 | |
) | |
// Not going to care for anything bigger than TB | |
if input >= 1000000000000 { | |
size = round((input / (1024 * 1024 * 1024 * 1024)), shift) | |
classification = " TB" | |
} else if input >= 1000000000 { | |
size = round((input / (1024 * 1024 * 1024)), shift) | |
classification = " GB" | |
} else if input >= 1000000 { | |
size = round((input / (1024 * 1024)), shift) | |
classification = " MB" | |
} else if input >= 1000 { | |
size = round((input / 1024), shift) | |
classification = " KB" | |
} else { | |
size = input | |
classification = " bytes" | |
} | |
return strconv.FormatFloat(size, 'f', shift, 64) + classification | |
} | |
// Let's define a backup and go from there | |
type Backup struct { | |
Files | |
Directories | |
byteSize int64 | |
humanSize string | |
} | |
type Directories struct { | |
name string | |
containsBytes float64 | |
constainsFiles int64 | |
} | |
type Files struct { | |
parent Directories | |
name string | |
byteSize int64 | |
humanSize string | |
} | |
func main() { | |
readerDir, _ := ioutil.ReadDir(`C:\Users\Giovanni\Downloads\cPanel`) | |
totalDir := 0 | |
totalFiles := 0 | |
var totalbytes float64 | |
for _, fileInfo := range readerDir { | |
if fileInfo.IsDir() { | |
totalDir++ | |
} else { | |
totalFiles++ | |
totalbytes += float64(fileInfo.Size()) | |
} | |
fmt.Printf("File Name: %s \n", fileInfo.Name()) | |
fmt.Printf("is it a directory? %v \n", fileInfo.IsDir()) | |
fmt.Printf("File Size: %d bytes \n", fileInfo.Size()) | |
//bytesize := fileInfo.Size() | |
fmt.Println("Human readable size: ", (readableByte(float64(fileInfo.Size()), 2))) | |
} | |
fmt.Println("===== FIRST LEVEL ONLY =====") | |
fmt.Printf("Total directories: %d\n", totalDir) | |
fmt.Printf("Total files: %d\n", totalFiles) | |
fmt.Printf("Total Size: %s\n", readableByte(float64(totalbytes), 2)) | |
// The problem here is that we are not being recursive (this is only top level) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment