diff --git a/README.md b/README.md index 46b43c4e..011899a9 100644 --- a/README.md +++ b/README.md @@ -98,24 +98,19 @@ In order to re/build the binaries from scratch, along with all the cowfile conve Makefile tasks ```shell -cd build && make build/docker build/release +cd build && make build/docker build/assets build/release ``` -This will produce 4 executable bin files inside the build/ directory +This will produce 4 executable bin files inside the `build/bin` directory, and a heap of binary asset files in `build/assets`. ### On your host OS You'll have to install a golang version that matches the go.mod, and ensure that other package dependencies are installed (see the dockerfile for the dependencies) -``` -# Build the pokedex build tool -go build src/pokedex.go -# Extract the cowfiles into a directory -tar xzf build/cows.tar.gz -C build/ - -# Generate a encoding/gob data file from the cowfiles -./pokedex -from build/cows -to build/pokedex.gob +```shell +# Generate binary asset files from the cowfiles +./build/build_assets.sh # Finally, build the pokesay tool (this builds and uses the build/pokedex.gob file automatically) go build pokesay.go diff --git a/build/Dockerfile b/build/Dockerfile index b63714ab..a1ba3310 100644 --- a/build/Dockerfile +++ b/build/Dockerfile @@ -9,10 +9,6 @@ RUN apt-get update \ RUN git clone --depth 1 https://github.com/denilsonsa/img2xterm \ && (cd img2xterm && make && make install) -ENV DOCKER_BUILD_DIR /tmp/original -ENV DOCKER_OUTPUT_DIR /tmp/cows - -RUN mkdir -p /tmp/original /tmp/cows WORKDIR /tmp/original RUN git clone --depth 1 https://github.com/msikma/pokesprite @@ -23,13 +19,11 @@ ADD go.* /usr/local/src/ RUN go mod tidy \ && go get -v github.com/mitchellh/go-wordwrap -ADD . . # Convert all of the pokesprite .pngs -> cowfiles for the terminal -# build up a map of category -> pokemon, and write it as a "encoding/gob" file -RUN go run /usr/local/src/src/pokedex.go \ +RUN go run /usr/local/src/src/bin/convert/png_convert.go \ -from /tmp/original/pokesprite/ \ -to /tmp/cows/ \ - -skip '["resources/", "misc/", "icons/", "items/", "items-outline/"]' \ - -toCategoryFpath "build/pokedex.gob" + -padding 4 \ + -skip '["resources/", "misc/", "icons/", "items/", "items-outline/"]' -RUN build/build.sh +ADD . . \ No newline at end of file diff --git a/build/Makefile b/build/Makefile index e0831266..e75475d7 100644 --- a/build/Makefile +++ b/build/Makefile @@ -6,31 +6,30 @@ DOCKER_OUTPUT_DIR ?= /tmp/cows all: build/docker build/cows build/release build/docker: - docker build \ - -f Dockerfile \ - -t pokesay-go:latest .. + docker build -f Dockerfile -t pokesay-go:latest .. build/cows: @rm -rf cows.tar.gz cows/ - docker create \ - --name pokebuilder \ - pokesay-go:latest + docker rm -f pokebuilder + docker create --name pokebuilder pokesay-go:latest @docker cp pokebuilder:$(DOCKER_OUTPUT_DIR)/ cows/ @tar czf cows.tar.gz cows/ @rm -rf cows/ @docker rm -f pokebuilder @du -sh cows.tar.gz -install: build/bin - cp -v pokesay-$(TARGET_GOOS)-$(TARGET_GOARCH) $(HOME)/bin/pokesay +# generate embedded bin files for category/metadata/the actual pokemon +build/assets: + docker run \ + -v $(PWD)/assets:/usr/local/src/build/assets \ + --rm --name pokesay pokesay-go:latest \ + build/build_assets.sh build/release: - @docker create --name pokesay pokesay-go:latest - docker cp pokesay:/usr/local/src/pokesay-linux-amd64 . - docker cp pokesay:/usr/local/src/pokesay-darwin-amd64 . - docker cp pokesay:/usr/local/src/pokesay-darwin-arm64 . - docker cp pokesay:/usr/local/src/pokesay-windows-amd64.exe . - docker cp pokesay:/usr/local/src/pokesay-android-arm64 . - @docker rm -f pokesay + docker run \ + -v $(PWD)/bin:/usr/local/src/build/bin \ + -v $(PWD)/assets:/usr/local/src/build/assets \ + --rm --name pokesay pokesay-go:latest build/build.sh + tree bin/ .PHONY: all build/docker build/cows install build/release diff --git a/build/build.sh b/build/build.sh index 5fa5f632..a53deddd 100755 --- a/build/build.sh +++ b/build/build.sh @@ -1,17 +1,18 @@ #!/bin/bash -set -euo pipefail +set -euxo pipefail + +OUTPUT_DIR="build/bin" +mkdir -p "$OUTPUT_DIR" function build() { echo "building $1 / $2" - GOOS=$1 GOARCH=$2 go build -o bin/pokesay-${1}-${2}${3:-} pokesay.go + GOOS=$1 GOARCH=$2 go build -o "${OUTPUT_DIR}/pokesay-${1}-${2}${3:-}" pokesay.go } -mkdir bin/ - build darwin amd64 & build darwin arm64 & build linux amd64 & build windows amd64 .exe & build android arm64 & -wait \ No newline at end of file +wait diff --git a/build/build_assets.sh b/build/build_assets.sh new file mode 100755 index 00000000..0c175adb --- /dev/null +++ b/build/build_assets.sh @@ -0,0 +1,15 @@ +#!/bin/bash + +set -euo pipefail + +tar xzf build/cows.tar.gz +go run ./src/bin/pokedex/pokedex.go \ + -from ./cows/ \ + -to ./build/assets/ \ + -toCategoryFpath pokedex.gob \ + -toDataSubDir cows/ \ + -toMetadataSubDir metadata/ \ + -toTotalFname total.txt + +rm -rf cows +ls -alh build/assets diff --git a/go.mod b/go.mod index 830ca265..5aeb74b8 100644 --- a/go.mod +++ b/go.mod @@ -8,6 +8,9 @@ require ( ) require ( + github.com/fatih/color v1.13.0 // indirect + github.com/mattn/go-colorable v0.1.9 // indirect + github.com/mattn/go-isatty v0.0.14 // indirect github.com/mattn/go-runewidth v0.0.13 // indirect github.com/mitchellh/colorstring v0.0.0-20190213212951-d06e56a500db // indirect github.com/rivo/uniseg v0.2.0 // indirect diff --git a/go.sum b/go.sum index 11118be7..232d66fc 100644 --- a/go.sum +++ b/go.sum @@ -1,7 +1,13 @@ github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/fatih/color v1.13.0 h1:8LOYc1KYPPmyKMuN8QV2DNRWNbLo6LZ0iLs8+mlH53w= +github.com/fatih/color v1.13.0/go.mod h1:kLAiJbzzSOZDVNGyDpeOxJ47H46qBXwg5ILebYFFOfk= github.com/k0kubun/go-ansi v0.0.0-20180517002512-3bf9e2903213/go.mod h1:vNUNkEQ1e29fT/6vq2aBdFsgNPmy8qMdSay1npru+Sw= +github.com/mattn/go-colorable v0.1.9 h1:sqDoxXbdeALODt0DAeJCVp38ps9ZogZEAXjus69YV3U= +github.com/mattn/go-colorable v0.1.9/go.mod h1:u6P/XSegPjTcexA+o6vUJrdnUu04hMope9wVRipJSqc= +github.com/mattn/go-isatty v0.0.12/go.mod h1:cbi8OIDigv2wuxKPP5vlRcQ1OAZbq2CE4Kysco4FUpU= +github.com/mattn/go-isatty v0.0.14 h1:yVuAays6BHfxijgZPzw+3Zlu5yQgKGP2/hcQbHb7S9Y= github.com/mattn/go-isatty v0.0.14/go.mod h1:7GGIvUiUoEMVVmxf/4nioHXj79iQHKdU27kJ6hsGG94= github.com/mattn/go-runewidth v0.0.13 h1:lTGmDsbAYt5DmK6OnoV7EuIF1wEIFAcxld6ypU4OSgU= github.com/mattn/go-runewidth v0.0.13/go.mod h1:Jdepj2loyihRzMpdS35Xk/zdY8IAYHsh153qUoGf23w= @@ -21,6 +27,8 @@ github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UV golang.org/x/crypto v0.0.0-20210817164053-32db794688a5 h1:HWj/xjIHfjYU5nVXpTM0s39J9CbLn7Cc5a7IC5rwsMQ= golang.org/x/crypto v0.0.0-20210817164053-32db794688a5/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc= golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg= +golang.org/x/sys v0.0.0-20200116001909-b77594299b42/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200223170610-d5e6a3e2c0ae/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20210630005230-0f9fa26af87c/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= diff --git a/pokesay.go b/pokesay.go index e182b53a..85bc73bd 100644 --- a/pokesay.go +++ b/pokesay.go @@ -12,21 +12,26 @@ import ( "strings" "time" - "github.com/mitchellh/go-wordwrap" + "github.com/fatih/color" "github.com/tmck-code/pokesay-go/src/pokedex" + + "github.com/mitchellh/go-wordwrap" ) var ( - //go:embed build/pokedex.gob + //go:embed build/assets/pokedex.gob GOBCategory []byte - //go:embed build/total.txt + //go:embed build/assets/total.txt GOBTotal []byte - //go:embed build/*cow + //go:embed build/assets/cows/*cow GOBCowData embed.FS - //go:embed build/*metadata + //go:embed build/assets/metadata/*metadata GOBCowNames embed.FS Rand rand.Source = rand.NewSource(time.Now().UnixNano()) + + textStyleItalic *color.Color = color.New(color.Italic) + textStyleBold *color.Color = color.New(color.Bold) ) func check(e error) { @@ -76,8 +81,16 @@ func printSpeechBubble(scanner *bufio.Scanner, args Args) { } func printPokemon(index int, name string, categoryKeys []string) { - d, _ := GOBCowData.ReadFile(pokedex.EntryFpath(index)) - fmt.Printf("%schoice: %s / categories: %s\n", pokedex.Decompress(d), name, categoryKeys) + d, _ := GOBCowData.ReadFile(pokedex.EntryFpath("build/assets/cows", index)) + + fmt.Printf( + "%s%s: %s | %s: %s\n", + pokedex.Decompress(d), + "choice", + textStyleBold.Sprint(name), + "categories", + textStyleItalic.Sprint(strings.Join(categoryKeys, ", ")), + ) } func chooseRandomCategory(keys [][]string, categories pokedex.PokemonTrie) ([]string, []*pokedex.PokemonEntry) { @@ -169,7 +182,7 @@ func runPrintByCategory(args Args, categories pokedex.PokemonTrie) { func runPrintRandom(args Args) { total, _ := strconv.Atoi(string(GOBTotal)) choice := randomInt(total) - m, err := GOBCowNames.ReadFile(pokedex.MetadataFpath(choice)) + m, err := GOBCowNames.ReadFile(pokedex.MetadataFpath("build/assets/metadata", choice)) check(err) metadata := pokedex.ReadMetadataFromBytes(m) diff --git a/src/bin/convert/png_convert.go b/src/bin/convert/png_convert.go new file mode 100644 index 00000000..05c2287f --- /dev/null +++ b/src/bin/convert/png_convert.go @@ -0,0 +1,67 @@ +package main + +import ( + "encoding/json" + "flag" + "fmt" + "log" + "os" + + "github.com/tmck-code/pokesay-go/src/bin" + "github.com/tmck-code/pokesay-go/src/pokedex" +) + +func check(e error) { + if e != nil { + log.Fatal(e) + } +} + +var ( + DEBUG bool = false +) + +type CowBuildArgs struct { + FromDir string + ToDir string + SkipDirs []string + Padding int + Debug bool +} + +func parseArgs() CowBuildArgs { + fromDir := flag.String("from", ".", "from dir") + toDir := flag.String("to", ".", "to dir") + skipDirs := flag.String("skip", "'[\"resources\"]'", "JSON array of dir patterns to skip converting") + padding := flag.Int("padding", 2, "the number of spaces to pad from the left") + debug := flag.Bool("debug", DEBUG, "show debug logs") + + flag.Parse() + + DEBUG = *debug + + args := CowBuildArgs{FromDir: *fromDir, ToDir: *toDir, Padding: *padding} + json.Unmarshal([]byte(*skipDirs), &args.SkipDirs) + + if DEBUG { + fmt.Println("%+v", args) + } + return args +} + +func main() { + args := parseArgs() + + fpaths := pokedex.FindFiles(args.FromDir, ".png", args.SkipDirs) + + // Ensure that the destination dir exists + os.MkdirAll(args.ToDir, 0755) + + fmt.Println("Converting PNGs -> cowfiles") + pbar := bin.NewProgressBar(len(fpaths)) + for _, f := range fpaths { + pokedex.ConvertPngToCow(args.FromDir, f, args.ToDir, args.Padding) + pbar.Add(1) + } + fmt.Println("Finished converting", len(fpaths), "pokesprite PNGs", "-> cowfiles") +} diff --git a/src/bin/pokedex/pokedex.go b/src/bin/pokedex/pokedex.go new file mode 100644 index 00000000..ecacd042 --- /dev/null +++ b/src/bin/pokedex/pokedex.go @@ -0,0 +1,90 @@ +package main + +import ( + "flag" + "fmt" + "log" + "os" + "path" + "strconv" + + "github.com/tmck-code/pokesay-go/src/bin" + "github.com/tmck-code/pokesay-go/src/pokedex" +) + +func check(e error) { + if e != nil { + log.Fatal(e) + } +} + +type PokedexArgs struct { + FromDir string + ToDir string + Debug bool + ToCategoryFname string + ToDataSubDir string + ToMetadataSubDir string + ToTotalFname string +} + +func parseArgs() PokedexArgs { + fromDir := flag.String("from", "/tmp/cows", "from dir") + toDir := flag.String("to", "build/assets/", "to dir") + + toDataSubDir := flag.String("toDataSubDir", "cows/", "dir to write all binary (image) data to") + toMetadataSubDir := flag.String("toMetadataSubDir", "metadata/", "dir to write all binary (metadata) data to") + toCategoryFname := flag.String("toCategoryFpath", "pokedex.gob", "to fpath") + toTotalFname := flag.String("toTotalFname", "total.txt", "file to write the number of available entries to") + debug := flag.Bool("debug", false, "show debug logs") + + flag.Parse() + + args := PokedexArgs{ + FromDir: pokedex.NormaliseRelativeDir(*fromDir), + ToDir: pokedex.NormaliseRelativeDir(*toDir), + ToCategoryFname: *toCategoryFname, + ToDataSubDir: pokedex.NormaliseRelativeDir(*toDataSubDir), + ToMetadataSubDir: pokedex.NormaliseRelativeDir(*toMetadataSubDir), + ToTotalFname: *toTotalFname, + Debug: *debug, + } + if args.Debug { + fmt.Printf("%+v\n", args) + } + return args +} + +func main() { + args := parseArgs() + + totalFpath := path.Join(args.ToDir, args.ToTotalFname) + categoryFpath := path.Join(args.ToDir, args.ToCategoryFname) + + fpaths := pokedex.FindFiles(args.FromDir, ".cow", make([]string, 0)) + + err := os.MkdirAll(path.Join(args.ToDir, args.ToDataSubDir), 0755) + check(err) + err = os.MkdirAll(path.Join(args.ToDir, args.ToMetadataSubDir), 0755) + check(err) + + // categories is a PokemonTrie struct that will be written to a file using encoding/gob + // metadata is a list of pokemon data and an index to use when writing them to a file + // - this index matches a corresponding one in the categories struct + // - these files are embedded into the build binary using go:embed and then loaded at runtime + categories, metadata := pokedex.CreateMetadata(args.FromDir, fpaths, args.Debug) + + pokedex.WriteStructToFile(categories, categoryFpath) + + fmt.Println("\nConverting cowfiles -> category & metadata GOB") + pbar := bin.NewProgressBar(len(fpaths)) + for _, m := range metadata { + pokedex.WriteBytesToFile(m.Data, pokedex.EntryFpath(path.Join(args.ToDir, args.ToDataSubDir), m.Index), true) + pokedex.WriteStructToFile(m.Metadata, pokedex.MetadataFpath(path.Join(args.ToDir, args.ToMetadataSubDir), m.Index)) + pbar.Add(1) + } + pokedex.WriteBytesToFile([]byte(strconv.Itoa(len(metadata))), totalFpath, false) + + fmt.Println("Finished converting", len(fpaths), "pokesprite -> cowfiles") + fmt.Println("Wrote categories to", path.Join(args.ToDir, args.ToCategoryFname)) +} diff --git a/src/bin/utils.go b/src/bin/utils.go new file mode 100644 index 00000000..0db93a9f --- /dev/null +++ b/src/bin/utils.go @@ -0,0 +1,21 @@ +package bin + +import ( + "fmt" + "os" + "time" + "github.com/schollz/progressbar/v3" +) + +func NewProgressBar(max int) progressbar.ProgressBar { + return *progressbar.NewOptions( + max, + progressbar.OptionSetWriter(os.Stderr), + progressbar.OptionSetWidth(40), + progressbar.OptionThrottle(100*time.Millisecond), + progressbar.OptionShowCount(), + progressbar.OptionShowIts(), + progressbar.OptionOnCompletion(func() { fmt.Fprint(os.Stderr, "\n") }), + progressbar.OptionSetTheme(progressbar.Theme{Saucer: "█", SaucerPadding: "░", BarStart: "╢", BarEnd: "╟"}), + ) +} diff --git a/src/pokedex.go b/src/pokedex.go deleted file mode 100644 index 35f1d5eb..00000000 --- a/src/pokedex.go +++ /dev/null @@ -1,91 +0,0 @@ -package main - -import ( - "encoding/json" - "flag" - "fmt" - "log" - "os" - "time" - "strconv" - - "github.com/schollz/progressbar/v3" - "github.com/tmck-code/pokesay-go/src/pokedex" -) - -func check(e error) { - if e != nil { - log.Fatal(e) - } -} - -type CowBuildArgs struct { - FromDir string - ToDir string - SkipDirs []string - DebugTimer bool - ToCategoryFpath string -} - -func newProgressBar(max int) progressbar.ProgressBar { - return *progressbar.NewOptions( - max, - progressbar.OptionSetWriter(os.Stderr), - progressbar.OptionSetWidth(40), - progressbar.OptionThrottle(100*time.Millisecond), - progressbar.OptionShowCount(), - progressbar.OptionShowIts(), - progressbar.OptionOnCompletion(func() { fmt.Fprint(os.Stderr, "\n") }), - progressbar.OptionSetTheme(progressbar.Theme{Saucer: "█", SaucerPadding: "░", BarStart: "╢", BarEnd: "╟"}), - ) -} - -func parseArgs() CowBuildArgs { - fromDir := flag.String("from", ".", "from dir") - toDir := flag.String("to", ".", "to dir") - toCategoryFpath := flag.String("toCategoryFpath", "build/pokedex.gob", "to fpath") - skipDirs := flag.String("skip", "'[\"resources\"]'", "JSON array of dir patterns to skip converting") - debugTimer := flag.Bool("debugTimer", false, "show a debug timer") - - flag.Parse() - - args := CowBuildArgs{FromDir: *fromDir, ToDir: *toDir, ToCategoryFpath: *toCategoryFpath, DebugTimer: *debugTimer} - json.Unmarshal([]byte(*skipDirs), &args.SkipDirs) - - return args -} - -func main() { - args := parseArgs() - - fpaths := pokedex.FindFiles(args.FromDir, ".png", args.SkipDirs) - - fmt.Println("Converting PNGs -> cowfiles") - pbar := newProgressBar(len(fpaths)) - for _, f := range fpaths { - pokedex.ConvertPngToCow(args.FromDir, f, args.ToDir, 2) - pbar.Add(1) - } - - cowFpaths := pokedex.FindFiles(args.ToDir, ".cow", args.SkipDirs) - - // categories is a PokemonTrie struct that will be written to a file using encoding/gob - // metadata is a list of pokemon data and an index to use when writing them to a file - // - this index matches a corresponding one in the categories struct - // - these files are embedded into the build binary using go:embed and then loaded at runtime - categories, metadata := pokedex.CreateMetadata(cowFpaths) - - pokedex.WriteStructToFile(categories, args.ToCategoryFpath) - - fmt.Println("\nConverting cowfiles -> category & metadata GOB") - pbar = newProgressBar(len(cowFpaths)) - for _, m := range metadata { - pokedex.WriteBytesToFile(m.Data, pokedex.EntryFpath(m.Index), true) - pokedex.WriteStructToFile(m.Metadata, pokedex.MetadataFpath(m.Index)) - pbar.Add(1) - } - pokedex.WriteBytesToFile([]byte(strconv.Itoa(len(metadata))), "build/total.txt", false) - - fmt.Println("Finished converting", len(fpaths), "pokesprite", len(cowFpaths), "-> cowfiles") - fmt.Println("Wrote categories to", args.ToCategoryFpath) -} diff --git a/src/pokedex/convert.go b/src/pokedex/convert.go index fc83e630..ed4179fd 100644 --- a/src/pokedex/convert.go +++ b/src/pokedex/convert.go @@ -1,4 +1,5 @@ package pokedex + import ( "bufio" "fmt" @@ -6,7 +7,6 @@ import ( "os/exec" "path/filepath" "strings" - "time" ) var ( @@ -92,9 +92,6 @@ func ConvertPngToCow(sourceDirpath string, sourceFpath string, destDirpath strin ) // Ensure that the destination dir exists os.MkdirAll(destDir, 0755) - time.Sleep(0) - - destFpath := filepath.Join(destDir, strings.ReplaceAll(filepath.Base(sourceFpath), ".png", ".cow")) // Some conversions are failing with something about colour channels // Can't be bothered resolving atm, so just skip past any failed conversions @@ -105,6 +102,7 @@ func ConvertPngToCow(sourceDirpath string, sourceFpath string, destDirpath strin return } + destFpath := filepath.Join(destDir, strings.ReplaceAll(filepath.Base(sourceFpath), ".png", ".cow")) ostream, err := os.Create(destFpath) check(err) defer ostream.Close() @@ -120,26 +118,26 @@ func ConvertPngToCow(sourceDirpath string, sourceFpath string, destDirpath strin } type Metadata struct { - Data []byte - Index int + Data []byte + Index int Metadata PokemonMetadata } -func CreateMetadata(fpaths []string) (PokemonTrie, []Metadata) { +func CreateMetadata(rootDir string, fpaths []string, debug bool) (PokemonTrie, []Metadata) { categories := NewTrie() metadata := []Metadata{} for i, fpath := range fpaths { data, err := os.ReadFile(fpath) check(err) - cats := createCategories(fpath) + cats := createCategories(strings.TrimPrefix(fpath, rootDir)) name := createName(fpath) categories.Insert( cats, - NewPokemonEntry(i,name), + NewPokemonEntry(i, name), ) - metadata = append(metadata, Metadata{data, i, PokemonMetadata{Name: name, Categories: strings.Join(cats, "/")}}) + metadata = append(metadata, Metadata{data, i, PokemonMetadata{Name: name, Categories: strings.Join(cats, "/")}}) } return *categories, metadata } @@ -151,5 +149,10 @@ func createName(fpath string) string { func createCategories(fpath string) []string { parts := strings.Split(fpath, "/") - return append([]string{"pokemon"}, parts[3:len(parts)-1]...) + return parts[0 : len(parts)-1] +} + +// Strips the leading "./" from a path e.g. "./cows/ -> cows/" +func NormaliseRelativeDir(dirPath string) string { + return strings.TrimPrefix(dirPath, "./") } diff --git a/src/pokedex/entries.go b/src/pokedex/entries.go index 57289aaa..a13db44f 100644 --- a/src/pokedex/entries.go +++ b/src/pokedex/entries.go @@ -8,6 +8,7 @@ import ( "errors" "fmt" "log" + "path" "os" "strings" ) @@ -60,12 +61,12 @@ func NewTrie() *PokemonTrie { } } -func EntryFpath(idx int) string { - return fmt.Sprintf("build/%d.cow", idx) +func EntryFpath(subdir string, idx int) string { + return path.Join(subdir, fmt.Sprintf("%d.cow", idx)) } -func MetadataFpath(idx int) string { - return fmt.Sprintf("build/%d.metadata", idx) +func MetadataFpath(subdir string, idx int) string { + return path.Join(subdir, fmt.Sprintf("%d.metadata", idx)) } func Equal(a, b []string) bool {