feat(config): split files and folders

main
Tran Hau 2021-01-18 11:28:06 +07:00
parent ceda041891
commit e130245287
5 changed files with 86 additions and 7 deletions

4
.gitignore vendored
View File

@ -6,3 +6,7 @@
# VSCode
.vscode/
# Node
node_modules/
package-lock.json

View File

@ -10,36 +10,49 @@ import (
)
type Config struct {
// Read when run
Path string `json:"-"`
// Read from file
Apps map[string]App `json:"apps"`
}
type App struct {
ConfigPath string `json:"config_path"`
Files []FromToPath `json:"files"`
Folders []FromToPath `json:"folders"`
}
type FromToPath struct {
From string `json:"from"`
To string `json:"to"`
}
// Load config from file
func LoadConfig(path string) (Config, error) {
func LoadConfig(path string) (result Config, err error) {
configPath := getConfigPath(path)
f, err := os.Open(configPath)
if err != nil {
// https://github.com/golang/go/blob/3e1e13ce6d1271f49f3d8ee359689145a6995bad/src/os/error.go#L90-L91
if errors.Is(err, os.ErrNotExist) {
return Config{}, fmt.Errorf("file not exist %s: %w", configPath, err)
err = fmt.Errorf("file not exist %s: %w", configPath, err)
return
}
}
defer f.Close()
bytes, err := ioutil.ReadAll(f)
if err != nil {
return Config{}, fmt.Errorf("failed to read %s: %w", configPath, err)
err = fmt.Errorf("failed to read %s: %w", configPath, err)
return
}
var result Config
if err := json.Unmarshal(bytes, &result); err != nil {
return Config{}, fmt.Errorf("failed to unmarshal: %w,", err)
err = fmt.Errorf("failed to unmarshal: %w", err)
return
}
return result, nil
result.Path = configPath
return
}
func getConfigPath(path string) string {

20
configs/config.json Normal file
View File

@ -0,0 +1,20 @@
{
"apps": {
"tmux": {
"folders": [
{
"from": "configs/tmux",
"to": "~/.config/tmux"
}
]
},
"nvim": {
"folders": [
{
"from": "configs/nvim",
"to": "~/.config/nvim"
}
]
}
}
}

7
file.go Normal file
View File

@ -0,0 +1,7 @@
package main
import "os"
func Delete(path string) error {
return os.RemoveAll(path)
}

35
main.go
View File

@ -18,6 +18,8 @@ const (
)
func main() {
a := &action{}
app := &cli.App{
Name: appName,
Usage: "managing dotfiles",
@ -33,6 +35,13 @@ func main() {
Usage: "update dotfiles from configs",
},
},
Flags: []cli.Flag{
&cli.StringFlag{
Name: "pathFlag",
Usage: "path to `DOTFILES`",
},
},
Action: a.Run,
}
if err := app.Run(os.Args); err != nil {
@ -42,3 +51,29 @@ func main() {
fmt.Printf("%s\n", err.Error())
}
}
type action struct {
flags struct {
path string
}
}
// Show help by default
func (a *action) Run(c *cli.Context) error {
return cli.ShowAppHelp(c)
}
func (a *action) RunInstall(c *cli.Context) error {
a.getFlags(c)
cfg, err := LoadConfig(a.flags.path)
if err != nil {
return fmt.Errorf("failed to load config: %w", err)
}
return nil
}
func (a *action) getFlags(c *cli.Context) {
a.flags.path = c.String(pathFlag)
}