Created
April 29, 2012 02:17
-
-
Save jasonmc/2523587 to your computer and use it in GitHub Desktop.
Go directory tree builder
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 ( | |
"os" | |
"log" | |
"fmt" | |
"path/filepath" | |
"strconv" | |
"strings" | |
) | |
type record struct { | |
name string | |
subs []*record | |
size int64 | |
} | |
func (r *record) String() string { | |
var parts []string | |
parts = append(parts, "(\"", r.name, "\" [" ) | |
for _, v := range r.subs { | |
parts = append(parts, v.String()) | |
} | |
parts = append(parts, strconv.FormatInt(r.size,10), ")\n") | |
return strings.Join(parts,"") | |
} | |
func main() { | |
fmt.Println(buildTree("/Users/jason/Code/","/Users/jason/")) | |
} | |
func buildTree(directory string, root string) ([]*record, int64) { | |
path, err := os.Open(directory) | |
if err != nil { | |
log.Fatal(err) | |
} | |
items, err := path.Readdir(0) | |
var total int64 = 0 | |
var allParts[] *record | |
if err == nil && len(items) > 0 { | |
for _, item := range items { | |
var thisSize int64 = 0 | |
thisPart := new(record) | |
name := item.Name() | |
thisPart.name = name | |
if item.Mode()&os.ModeSymlink != 1 { | |
if !item.IsDir() { | |
thisSize = item.Size() | |
} else { | |
key := fmt.Sprintf("%s/%s", root, name) | |
subs,t := buildTree(filepath.Join(directory, name), key) | |
thisPart.subs = subs | |
thisSize = item.Size() + t | |
} | |
thisPart.size = thisSize | |
allParts = append(allParts, thisPart) | |
} | |
total = total + thisSize | |
} | |
} | |
path.Close() | |
return allParts,total | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment