Go R1 Day 10
tech development 100DaysOfCode microblog golang
Day 10 of 100
progress
- Experimented with CLI tool using go-prompt
- Customized initial options
- OS independent call to get user home directory.
- Iterated through a directory listing
- Used path join to initialize path for directory search.
- One challenge in working with structs being returned was figuring out how to print the values of the struct. Initially, I only had pointers to the values coming back. This made sense, though, as I watched a tutorial this weekend on slices, and better understand that a slice is actually a small data structure being described by: pointer to the location in memory, length, and the capacity of the slice. Without this tutorial, I think seeing the pointer addresses coming through would have been pretty confusing.
- In reading StackOverflow, I realized it’s a “slice of interfaces”.
- Worked with apex logger and moved some of the log output to debug level logging.
- Final result
links
source
Code
package main
import (
// "fmt"
"github.com/c-bata/go-prompt"
// pretty "github.com/inancgumus/prettyslice"
"io/ioutil"
"github.com/common-nighthawk/go-figure"
"github.com/mitchellh/go-homedir"
"github.com/olekukonko/tablewriter"
// "log"
"os"
"path"
"github.com/apex/log"
"github.com/apex/log/handlers/text"
)
func ListDirectories(dir string) ([]os.FileInfo, error) {
dirList, err := ioutil.ReadDir(dir)
if err != nil {
log.Fatalf("Failed to ReadDir: %s", err)
return nil, err
}
return dirList, nil
}
func completer(d prompt.Document) []prompt.Suggest {
s := []prompt.Suggest{
{Text: "sheldonhull", Description: "my personal github repos"},
{Text: "github", Description: "General cloned repos from github"},
}
return prompt.FilterHasPrefix(s, d.GetWordBeforeCursor(), true)
}
func RenderDirectoryTable(f []os.FileInfo) {
table := tablewriter.NewWriter(os.Stdout)
table.SetHeader([]string{"Name"})
for _, file := range f {
table.Append([]string{file.Name()})
}
// table.AppendBulk(f)
table.Render() // Send output
}
func Title() {
myFigure := figure.NewColorFigure("FooBar", "", "green", true)
myFigure.Print()
}
func main() {
log.SetHandler(text.New(os.Stderr))
Title()
log.Infof("Please select table.")
t := prompt.Input("> ", completer, prompt.OptionShowCompletionAtStart())
log.Infof("You selected " + t)
d, err := homedir.Dir()
if err != nil {
log.Fatalf("Failed to parse user home directory: %s", err)
}
log.Infof("User Directory: %s", d)
dirPath := path.Join(d, "git", t)
log.Infof("The path join value is: %s", dirPath)
dl, err := ListDirectories(dirPath)
if err != nil {
log.Fatalf("Error in ListDirectories: %s", err)
}
// pretty.Show("The resulting directories", dl)
// fmt.Infof("The resulting directories: %+v\n", dl)
// fmt.Infof("The resulting directories: %s\n", dl.Name()) // doesn't work as slice of interfaces
// This works as it uses the function to get name
for _, i := range dl {
log.Debugf("%s\n", i.Name())
}
RenderDirectoryTable(dl)
// ListDirectories(t)
}