Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

added config #539

Draft
wants to merge 1 commit into
base: master
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 32 additions & 0 deletions command.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import (
"os"
"strings"

"github.com/rsteube/carapace/internal/config"
"github.com/rsteube/carapace/internal/uid"
"github.com/rsteube/carapace/pkg/style"
"github.com/spf13/cobra"
Expand Down Expand Up @@ -104,4 +105,35 @@ func addCompletionCommand(cmd *cobra.Command) {
Carapace{styleSetCmd}.PositionalAnyCompletion(
ActionStyleConfig(),
)

addConfigCommand(carapaceCmd)
}

func addConfigCommand(cmd *cobra.Command) {
configCmd := &cobra.Command{
Use: "config",
Args: cobra.ExactArgs(1),
Run: func(cmd *cobra.Command, args []string) {},
}
cmd.AddCommand(configCmd)

configSetCmd := &cobra.Command{
Use: "set",
Args: cobra.MinimumNArgs(1),
Run: func(cmd *cobra.Command, args []string) {
for _, arg := range args {
if splitted := strings.SplitN(arg, "=", 2); len(splitted) == 2 {
if err := config.SetConfig(splitted[0], splitted[1]); err != nil {
fmt.Fprint(cmd.ErrOrStderr(), err.Error())
}
} else {
fmt.Fprintf(cmd.ErrOrStderr(), "invalid format: '%v'", arg)
}
}
},
}
configCmd.AddCommand(configSetCmd)
Carapace{configSetCmd}.PositionalAnyCompletion(
ActionConfigs(),
)
}
66 changes: 66 additions & 0 deletions config.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
package carapace

import (
"strings"

"github.com/rsteube/carapace/internal/config"
)

type carapaceConfig struct {
DescriptionLength int
}

func (c *carapaceConfig) Completion() ActionMap {
return ActionMap{
"DescriptionLength": ActionValues("40", "30"),
}
}

var conf = carapaceConfig{
DescriptionLength: 40,
}

func init() {
config.RegisterConfig("carapace", &conf)
}

type configI interface {
Completion() ActionMap
}

func ActionConfigs() Action {
return ActionMultiParts("=", func(c Context) Action {
switch len(c.Parts) {
case 0:
return ActionMultiParts(".", func(c Context) Action {
switch len(c.Parts) {
case 0:
return ActionValues(config.GetConfigs()...).Invoke(c).Suffix(".").ToA()
case 1:
fields, err := config.GetConfigFields(c.Parts[0])
if err != nil {
return ActionMessage(err.Error())
}

vals := make([]string, 0)
for _, field := range fields {
vals = append(vals, field.Name, field.Description, field.Style)
}
return ActionStyledValuesDescribed(vals...).Invoke(c).Suffix("=").ToA()
default:
return ActionValues()
}
})
case 1:
if m := config.GetConfigMap(strings.Split(c.Parts[0], ".")[0]); m != nil {
if i, ok := m.(configI); ok {
// TODO check splitted length
return i.Completion()[strings.Split(c.Parts[0], ".")[1]]
}
}
return ActionValues()
default:
return ActionValues()
}
})
}
93 changes: 74 additions & 19 deletions internal/config/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import (
"os"
"path/filepath"
"reflect"
"strconv"
"strings"

"github.com/rsteube/carapace/pkg/xdg"
Expand All @@ -22,34 +23,60 @@ func (c configMap) Keys() []string {
return keys
}

type Field struct {
Name string
Description string
Style string
Tag string
}

func (c configMap) Fields(name string) ([]Field, error) {
// func (c configMap) Fields(name string, styled bool) ([]string, error) {
// if i, ok := c[name]; ok {
// fields := make([]string, 0)
// t := reflect.TypeOf(i).Elem()
// for index := 0; index < t.NumField(); index++ {
// field := t.Field(index)
// style := ""
// if styled {
// if field.Type.Name() != "string" {
// return nil, fmt.Errorf("invalid field type [name: '%v', type: '%v']", field.Name, field.Type.Name())
// }
// v := reflect.ValueOf(i).Elem()
// style = v.FieldByName(field.Name).String()
// }
// fields = append(fields, field.Name, field.Tag.Get("desc"), style)
// }
// return fields, nil
// }
// return nil, fmt.Errorf("unknown config: '%v'", name)
// }

func (c configMap) Fields(name string, styled bool) ([]Field, error) {
if i, ok := c[name]; ok {
fields := make([]Field, 0)
t := reflect.TypeOf(i).Elem()
v := reflect.ValueOf(i).Elem()
for index := 0; index < t.NumField(); index++ {
field := t.Field(index)
if field.Type.Name() != "string" {
if styled && field.Type.Name() != "string" {
return nil, fmt.Errorf("invalid field type [name: '%v', type: '%v']", field.Name, field.Type.Name())
}
fields = append(fields, Field{field.Name, field.Tag.Get("desc"), v.FieldByName(field.Name).String(), field.Tag.Get("tag")})
fields = append(fields, Field{
Name: field.Name,
Description: field.Tag.Get("desc"),
Style: v.FieldByName(field.Name).String(), // TODO only if styled
Tag: field.Tag.Get("tag"),
Type: field.Type,
})
}
return fields, nil
}
return nil, fmt.Errorf("unknown config: '%v'", name)
}

var config = struct {
Styles configMap
Configs configMap
Styles configMap
}{
Styles: make(configMap),
Configs: make(configMap),
Styles: make(configMap),
}

func RegisterConfig(name string, i interface{}) {
config.Configs[name] = i
}

func RegisterStyle(name string, i interface{}) {
Expand All @@ -60,6 +87,11 @@ func Load() error {
if err := load("styles", config.Styles); err != nil {
return err
}

// TODO duplicated, ok or improve?
if err := load("configs", config.Configs); err != nil {
return err
}
return nil
}

Expand All @@ -73,7 +105,7 @@ func load(name string, c configMap) error {
return err
}

var unmarshalled map[string]map[string]string
var unmarshalled map[string]map[string]interface{}
if err := json.Unmarshal(content, &unmarshalled); err != nil {
return err
}
Expand All @@ -83,7 +115,7 @@ func load(name string, c configMap) error {
elem := reflect.ValueOf(s).Elem()
for k, v := range value {
if field := elem.FieldByName(k); field != (reflect.Value{}) {
field.SetString(v)
field.Set(reflect.ValueOf(v).Convert(field.Type()))
}
}
}
Expand All @@ -92,8 +124,16 @@ func load(name string, c configMap) error {
return nil
}

func SetConfig(key, value string) error {
return set("configs", key, strings.Replace(value, ",", " ", -1))
}

func GetConfigs() []string { return config.Configs.Keys() }
func GetConfigFields(name string) ([]Field, error) { return config.Configs.Fields(name, false) }
func GetConfigMap(name string) interface{} { return config.Configs[name] }

func GetStyleConfigs() []string { return config.Styles.Keys() }
func GetStyleFields(name string) ([]Field, error) { return config.Styles.Fields(name) }
func GetStyleFields(name string) ([]Field, error) { return config.Styles.Fields(name, true) }
func SetStyle(key, value string) error {
return set("styles", key, strings.Replace(value, ",", " ", -1))
}
Expand All @@ -116,7 +156,7 @@ func set(name, key, value string) error {
content = []byte("{}")
}

var config map[string]map[string]string
var config map[string]map[string]interface{}
if err := json.Unmarshal(content, &config); err != nil {
return err
}
Expand All @@ -125,18 +165,33 @@ func set(name, key, value string) error {
return errors.New("invalid key")
} else {
if _, ok := config[splitted[0]]; !ok {
config[splitted[0]] = make(map[string]string, 0)
config[splitted[0]] = make(map[string]interface{}, 0)
}
if strings.TrimSpace(value) == "" {
delete(config[splitted[0]], splitted[1])
} else {
config[splitted[0]][splitted[1]] = value
switch reflect.TypeOf(config[splitted[0]][splitted[1]]).Kind() {
case reflect.Int:
intValue, err := strconv.Atoi(value)
if err != nil {
return err
}
config[splitted[0]][splitted[1]] = intValue

case reflect.String:
config[splitted[0]][splitted[1]] = value

case reflect.Slice:
// TODO
}
}
}

marshalled, err := json.MarshalIndent(config, "", " ")
if err != nil {
return err
}
return os.WriteFile(file, marshalled, os.ModePerm)
os.WriteFile(file, marshalled, os.ModePerm)

return nil
}
11 changes: 11 additions & 0 deletions internal/config/field.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
package config

import "reflect"

type Field struct {
Name string
Description string
Style string
Tag string
Type reflect.Type
}
6 changes: 6 additions & 0 deletions pkg/config/config.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
package config

import "github.com/rsteube/carapace/internal/config"


func Register(name string, i interface{}) { config.RegisterConfig(name, i) }