Skip to content

Commit

Permalink
feat: add ReadConf
Browse files Browse the repository at this point in the history
  • Loading branch information
nonzzz committed Jun 19, 2023
1 parent 519bd9d commit 4bbe3b0
Show file tree
Hide file tree
Showing 2 changed files with 105 additions and 87 deletions.
134 changes: 70 additions & 64 deletions internal/action/action.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import (
"fmt"
"net/url"
"os"
"path"
"path/filepath"

"github.com/modern-magic/grm/internal/fs"
"github.com/modern-magic/grm/internal/logger"
Expand All @@ -18,20 +18,20 @@ func printAlias(s string) source.S {
return source.EnsureDefaultKey(s)
}

func isDefaultAlias(s string) (bool, string) {
func isDefaultAlias(s string) (bool, source.S) {
alias := printAlias(s)
return alias != source.System, alias.String()
return alias != source.System, alias
}

func isDefaultPath(s string) (bool, string) {
func isDefaultPath(s string) (bool, source.S) {
alias, ok := source.DefaultSource[s]
if ok {
return true, alias.String()
return true, alias
}
return false, source.System.String()
return false, source.System
}

func isDefault(i string, isPath bool) (s bool, alias, source string) {
func isDefault(i string, isPath bool) (s bool, alias source.S, source string) {
if isPath {
s, alias = isDefaultPath(i)
return s, alias, i
Expand Down Expand Up @@ -71,23 +71,26 @@ func (action *actionImpl) currentPath() string {

func (action *actionImpl) View(option ViewOptions) int {
cp := action.currentPath()
ok, alias, source := isDefault(cp, true)
var c string
ok, alias, argvPath := isDefault(cp, true)
if !ok {
sources, _ := action.conf.ScannerUserConf()
if s, ok := sources[source]; ok {
alias = s
if s, ok := sources[argvPath]; ok {
c = s
}
} else {
c = alias.String()
}

if !option.All {
logger.PrintTextWithColor(os.Stdout, func(c logger.Colors) string {
return fmt.Sprintf("%s%s%s\n", c.Dim, alias, c.Reset)
return fmt.Sprintf("%s%s%s\n", c.Dim, c, c.Reset)
})
return 0
}

for _, s := range action.conf.Paths {
if s == alias {
if s == c {
logger.PrintTextWithColor(os.Stdout, func(c logger.Colors) string {
return fmt.Sprintf("* %s%s%s%s\n", c.Cyan, s, fmt.Sprintf(" %s%s%s", c.DimCyan, "default", c.Reset), c.Reset)
})
Expand All @@ -109,7 +112,7 @@ func (action *actionImpl) Drop() int {
return 1
}
name := action.args[0]
ok, _, alias := isDefault(name, false)
ok, alias, argvName := isDefault(name, false)
if ok {
logger.PrintTextWithColor(os.Stderr, func(c logger.Colors) string {
return fmt.Sprintf("%s%s%s%s\n", c.Red, "error: can't remove default source", alias, c.Reset)
Expand All @@ -118,8 +121,8 @@ func (action *actionImpl) Drop() int {
}

// user conf
_, keys := action.conf.ScannerUserConf()
if _, ok := keys[alias]; !ok {
files := action.conf.Files()
if _, ok = files[argvName]; !ok {
logger.PrintTextWithColor(os.Stderr, func(c logger.Colors) string {
return fmt.Sprintf("%s%s%s\n", c.Red, "error: can't found alias", c.Reset)
})
Expand All @@ -132,14 +135,14 @@ func (action *actionImpl) Drop() int {
})
return 0
}
err := action.fs.Rm(path.Join(action.conf.BaseDir, alias))
err := action.fs.Rm(filepath.Join(action.conf.BaseDir, argvName))
if err != nil {
logger.PrintTextWithColor(os.Stderr, func(c logger.Colors) string {
return fmt.Sprintf("%s%s%s\n", c.Red, err, c.Reset)
})
return 1
}
// // Set npm as default choose
// Set npm as default choose
ok = action.conf.SetCurrentPath(source.DefaultKey[source.Npm])
if ok {
err := action.fs.OuputFile(action.conf.ConfPath, []byte(action.conf.GetCurrentConf()))
Expand All @@ -165,45 +168,42 @@ func (action *actionImpl) Join() int {
}
name := action.args[0]
path := action.args[1]
ok, alias, _ := isDefault(name, false)
ok, _, argvName := isDefault(name, false)
if ok {
logger.PrintTextWithColor(os.Stderr, func(c logger.Colors) string {
return fmt.Sprintf("%s%s%s\n", c.Red, "error: can't be named the same as default", c.Reset)
})
return 1
}
// if
// _, key := action.conf.ScannerUserConf()
files := action.conf.Files()
if _, ok := files[argvName]; ok {
if !shell.MakeConfirm("The alias already exists. Do you want to modify it?") {
logger.PrintTextWithColor(os.Stdout, func(c logger.Colors) string {
return fmt.Sprintf("%s%s%s\n", c.Dim, "process exit", c.Reset)
})
return 0
}
}

// _, userKey := action.conf.ScannerUserConf()
// if _, ok := userKey[alias]; ok {
// if !shell.MakeConfirm("The alias already exists. Do you want to modify it?") {
// logger.PrintTextWithColor(os.Stdout, func(c logger.Colors) string {
// return fmt.Sprintf("%s%s%s\n", c.Dim, "process exit", c.Reset)
// })
// return 0
// }
// }
// // verify path is a right url.
// if !verifyURL(action.args[1]) {
// logger.PrintTextWithColor(os.Stdout, func(c logger.Colors) string {
// return fmt.Sprintf("%s%s%s\n", c.Red, "invalid url", c.Reset)
// })
// return 1
// }
if !isURL(path) {
logger.PrintTextWithColor(os.Stdout, func(c logger.Colors) string {
return fmt.Sprintf("%s%s%s\n", c.Red, "invalid url", c.Reset)
})
return 1
}

// file := path.Join(action.conf.BaseDir, alias)
// err := action.fs.OuputFile(file, []byte(action.args[1]))
// if err != nil {
// logger.PrintTextWithColor(os.Stderr, func(c logger.Colors) string {
// return fmt.Sprintf("%s%s%s\n", c.Red, err, c.Reset)
// })
// return 1
// }
// logger.PrintTextWithColor(os.Stdout, func(c logger.Colors) string {
// return fmt.Sprintf("%s%s%s\n", c.Green, "update new conf success", c.Reset)
// })
// return 0
fp := filepath.Join(action.conf.BaseDir, argvName)
err := action.fs.OuputFile(fp, []byte(path))
if err != nil {
logger.PrintTextWithColor(os.Stderr, func(c logger.Colors) string {
return fmt.Sprintf("%s%s%s\n", c.Red, err, c.Reset)
})
return 1
}
logger.PrintTextWithColor(os.Stdout, func(c logger.Colors) string {
return fmt.Sprintf("%s%s%s\n", c.Green, "update new conf success", c.Reset)
})
return 0
}

// Pick up should test path
Expand Down Expand Up @@ -246,25 +246,33 @@ func (action *actionImpl) Test() int {
}

func (action *actionImpl) Use() int {
alias := action.args[0]
s := source.EnsureDefaultKey(alias)
url := ""
if !action.isDefaultAlias(s) {
_, userKey := action.conf.ScannerUserConf()
if v, ok := userKey[alias]; ok {
url = v
name := action.args[0]
var url string
ok, alias, argvName := isDefault(name, false)
if ok {
url = source.DefaultKey[alias]
} else {
files := action.conf.Files()
fp, ok := files[argvName]
if ok {
_url, err := source.ReadConf(fp)
if err != nil {
fmt.Fprintf(os.Stderr, "failed to update config file: %v\n", err)
return 1
}
url = _url
} else {
if !shell.MakeConfirm("This registry can't find. Do you want to add a new one?") {
logger.PrintTextWithColor(os.Stdout, func(c logger.Colors) string {
return fmt.Sprintf("%s%s%s\n", c.Dim, "process exit", c.Reset)
})
return 0
}
url, err := shell.MakePrompt(fmt.Sprintf("Enter registry address for %s: ", alias), func(input string) error {
_url, err := shell.MakePrompt(fmt.Sprintf("Enter registry address for %s: ", argvName), func(input string) error {
if len(input) == 0 {
return errors.New("can't be empty")
}
if !verifyURL(input) {
if !isURL(input) {
return errors.New("invalid url")
}
return nil
Expand All @@ -273,20 +281,19 @@ func (action *actionImpl) Use() int {
fmt.Fprintf(os.Stderr, "failed to update config file: %v\n", err)
return 1
}
file := path.Join(action.conf.BaseDir, alias)
err = action.fs.OuputFile(file, []byte(url))
url := _url
fp := filepath.Join(action.conf.BaseDir, argvName)
err = action.fs.OuputFile(fp, []byte(url))
if err != nil {
fmt.Fprintf(os.Stderr, "failed to update config file: %v\n", err)
return 1
}
}
} else {
url = source.DefaultKey[s]
}
logger.PrintTextWithColor(os.Stdout, func(c logger.Colors) string {
return fmt.Sprintf("%s%s%s%s\n", c.Dim, "using registry", fmt.Sprintf(" %s%s%s", c.Green, alias, c.Reset), c.Reset)
return fmt.Sprintf("%s%s%s%s\n", c.Dim, "using registry", fmt.Sprintf(" %s%s%s", c.Green, argvName, c.Reset), c.Reset)
})
ok := action.conf.SetCurrentPath(url)
ok = action.conf.SetCurrentPath(url)
if ok {
err := action.fs.OuputFile(action.conf.ConfPath, []byte(action.conf.GetCurrentConf()))
if err == nil {
Expand All @@ -297,5 +304,4 @@ func (action *actionImpl) Use() int {
return fmt.Sprintf("%s%s%s\n", c.Red, "invalid error", c.Reset)
})
return 1

}
58 changes: 35 additions & 23 deletions internal/source/conf.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,10 @@ package source

import (
"bufio"
"errors"
"os"
"path"
"path/filepath"
"strings"
"sync"

Expand Down Expand Up @@ -79,12 +81,22 @@ func readConf(path, alias string, c chan string) {
}
}

func ReadConf(path string) (url string, err error) {
ch := make(chan string)
go readConf(path, "*", ch)
line := <-ch
expr := strings.Split(line, "->")
if len(expr) == 0 {
return url, errors.New("Internal Error")
}
return expr[1], nil
}

type GrmConfig struct {
BaseDir string
ConfPath string
Paths []string
files []string // user conf
aliases []string // user alias
files map[string]string // user conf
parse *GrmIni
}

Expand All @@ -99,16 +111,17 @@ func NewGrmConf() *GrmConfig {
}

func (g *GrmConfig) ListAllPath() {
aliases, files := g.scanner()
list := make([]string, 0, len(aliases)+len(SourceToString))
files := g.scanner()
list := make([]string, 0, len(g.files)+len(SourceToString))
for _, s := range SourceToString {
if s != System.String() {
list = append(list, s)
}
}
list = append(list, aliases...)
for k := range files {
list = append(list, k)
}
g.files = files
g.aliases = aliases
g.Paths = list
}

Expand All @@ -125,28 +138,23 @@ func (g *GrmConfig) GetCurrentConf() string {
return g.parse.ToString()
}

func (g *GrmConfig) scanner() (aliases []string, files []string) {
func (g *GrmConfig) scanner() (files map[string]string) {
if _, err := os.Stat(g.BaseDir); os.IsNotExist(err) {
return nil, nil
return files
}
fd, err := os.ReadDir(g.BaseDir)
if err != nil {
return nil, nil
return files
}
var b strings.Builder
aliases = make([]string, 0, len(fd))
files = make([]string, 0, len(fd))
files = make(map[string]string, len(fd))
for _, file := range fd {
if !file.IsDir() {
aliases = append(aliases, file.Name())
b.Reset()
b.WriteString(g.BaseDir)
b.WriteByte('/')
b.WriteString(file.Name())
files = append(files, b.String())
n := file.Name()
p := filepath.Join(g.BaseDir, n)
files[n] = p
}
}
return aliases, files
return files
}

func (g *GrmConfig) ScannerUserConf() (source, key map[string]string) {
Expand All @@ -157,12 +165,12 @@ func (g *GrmConfig) ScannerUserConf() (source, key map[string]string) {
key = make(map[string]string)
var wg sync.WaitGroup
c := make(chan string)
for pos, file := range g.files {
for name, file := range g.files {
wg.Add(1)
go func(path string, pos int) {
readConf(path, g.aliases[pos], c)
go func(path string, name string) {
readConf(path, name, c)
wg.Done()
}(file, pos)
}(file, name)
}
go func() {
wg.Wait()
Expand Down Expand Up @@ -193,3 +201,7 @@ func (g *GrmConfig) MergePaths(userConf map[string]string) map[string]string {
}
return merged
}

func (g *GrmConfig) Files() map[string]string {
return g.files
}

0 comments on commit 4bbe3b0

Please sign in to comment.