Skip to content

Instantly share code, notes, and snippets.

@kjk kjk/build_files.go
Created Jul 19, 2019

Embed
What would you like to do?
build list of files as compact json from directory
package main
import (
"encoding/json"
"fmt"
"io/ioutil"
"os"
"path/filepath"
)
type DirInfo struct {
Path string
Dirs []string
Files []os.FileInfo
}
func buildDirInfoRecur(startDir string) ([]*DirInfo, error) {
toVisit := []string{startDir}
var res []*DirInfo
for len(toVisit) > 0 {
dir := toVisit[0]
toVisit = toVisit[1:]
files, err := ioutil.ReadDir(dir)
if err != nil {
return nil, err
}
// convert to unix form
path := filepath.ToSlash(dir)
di := &DirInfo{
Path: path,
}
res = append(res, di)
for _, fi := range files {
name := fi.Name()
if fi.IsDir() {
di.Dirs = append(di.Dirs, name)
newDir := filepath.Join(dir, name)
toVisit = append(toVisit, newDir)
continue
}
if !fi.Mode().IsRegular() {
// skip non-files
continue
}
di.Files = append(di.Files, fi)
}
}
return res, nil
}
func must(err error) {
if err != nil {
panic(err.Error())
}
}
/* compact JSON trepresentations is:
[$path1,
[
[$dir1],
[$dir2],
...
],
[
[$file1, $file1Size],
[$file2, $file2Size],
...
]
],
[$path2, ...],
*/
func dirInfosToCompact(infos []*DirInfo) []interface{} {
var res []interface{}
for _, di := range infos {
// ensure it's always [] and not nil
dirs := di.Dirs
if dirs == nil {
dirs = []string{}
}
files := []interface{}{}
for _, fi := range di.Files {
fii := []interface{}{fi.Name(), fi.Size()}
files = append(files, fii)
}
dii := []interface{}{di.Path, dirs, files}
res = append(res, dii)
}
return res
}
func main() {
dirInfos, err := buildDirInfoRecur(".")
must(err)
dirInfosCompact := dirInfosToCompact(dirInfos)
d, err := json.MarshalIndent(dirInfosCompact, "", " ")
must(err)
fmt.Printf("export let files = %s\n", string(d))
//fmt.Printf("Finished! Got info about %d dirs\n", len(dirInfos))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.