Skip to content

Instantly share code, notes, and snippets.

@bradfitz
Created November 22, 2011 18:55
Show Gist options
  • Save bradfitz/1386532 to your computer and use it in GitHub Desktop.
Save bradfitz/1386532 to your computer and use it in GitHub Desktop.
for ojan
package main
import (
"json"
"os"
"fmt"
"log"
"strings"
)
var data = `{
"ChromiumWin": {
"dir": { "bar.html": 5, "baz.html": 4, "foobar.html": 7},
"file.html": 5
},
"version": 4
}
`
type File interface {
IsDirectory() bool
Name() string
Children() []File
Count() int64
}
type file struct {
name string
val interface{}
}
func (f file) Name() string {
return f.name
}
func (f file) IsDirectory() bool {
_, isDir := f.val.(map[string]interface{})
return isDir
}
func (f file) Count() int64 {
n, _ := f.val.(float64)
return int64(n)
}
func (f file) Children() []File {
var fs []File
m, _ := f.val.(map[string]interface{})
for name, v := range m {
fs = append(fs, file{name: name, val: v})
}
return fs
}
type BuildResult map[string]interface{}
func (m BuildResult) Name() string {
for k := range m {
if k != "version" {
return k
}
}
return ""
}
func (m BuildResult) Version() int {
for k, v := range m {
if k == "version" {
return int(v.(float64))
}
}
return 0
}
func (m BuildResult) Root() File {
return file{name: m.Name(), val: m[m.Name()]}
}
func main() {
var jm map[string]interface{}
check(json.Unmarshal([]byte(data), &jm))
res := BuildResult(jm)
fmt.Printf("Builder name: %q, version %d\n", res.Name(), res.Version())
Dump(res.Root(), 0)
}
func Dump(f File, depth int) {
indent := strings.Repeat(" ", depth)
if f.IsDirectory() {
fmt.Printf("%s[ %s ]\n", indent, f.Name())
for _, c := range f.Children() {
Dump(c, depth+1)
}
} else {
fmt.Printf("%s- %s (%d)\n", indent, f.Name(), f.Count())
}
}
func check(err os.Error) {
if err != nil {
log.Panic(err.String())
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment