Skip to content

Commit

Permalink
Update version to v1.4.122 and commit
Browse files Browse the repository at this point in the history
  • Loading branch information
github-actions[bot] committed Dec 14, 2024
1 parent f180e8f commit 12284ad
Show file tree
Hide file tree
Showing 5 changed files with 127 additions and 134 deletions.
163 changes: 78 additions & 85 deletions cli/flags.go
Original file line number Diff line number Diff line change
Expand Up @@ -68,12 +68,11 @@ type Flags struct {
var debug = false

func Debugf(format string, a ...interface{}) {
if debug {
fmt.Printf("DEBUG: "+format, a...)
}
if debug {
fmt.Printf("DEBUG: "+format, a...)
}
}


// Init Initialize flags. returns a Flags struct and an error
func Init() (ret *Flags, err error) {
// Track which yaml-configured flags were set on CLI
Expand All @@ -84,152 +83,146 @@ func Init() (ret *Flags, err error) {
yamlFields := make(map[string]bool)
t := reflect.TypeOf(Flags{})
for i := 0; i < t.NumField(); i++ {
if yamlTag := t.Field(i).Tag.Get("yaml"); yamlTag != "" {
yamlFields[yamlTag] = true
//Debugf("Found yaml-configured field: %s\n", yamlTag)
}
if yamlTag := t.Field(i).Tag.Get("yaml"); yamlTag != "" {
yamlFields[yamlTag] = true
//Debugf("Found yaml-configured field: %s\n", yamlTag)
}
}

// Scan args for that are provided by cli and might be in yaml
for _, arg := range args {
if strings.HasPrefix(arg, "--") {
flag := strings.TrimPrefix(arg, "--")
if i := strings.Index(flag, "="); i > 0 {
flag = flag[:i]
}
if yamlFields[flag] {
usedFlags[flag] = true
Debugf("CLI flag used: %s\n", flag)
}
if strings.HasPrefix(arg, "--") {
flag := strings.TrimPrefix(arg, "--")
if i := strings.Index(flag, "="); i > 0 {
flag = flag[:i]
}
if yamlFields[flag] {
usedFlags[flag] = true
Debugf("CLI flag used: %s\n", flag)
}
}
}

// Parse CLI flags first
ret = &Flags{}
parser := flags.NewParser(ret, flags.Default)
if _, err = parser.Parse(); err != nil {
return nil, err
return nil, err
}

// If config specified, load and apply YAML for unused flags
if ret.Config != "" {
yamlFlags, err := loadYAMLConfig(ret.Config)
if err != nil {
return nil, err
}
yamlFlags, err := loadYAMLConfig(ret.Config)
if err != nil {
return nil, err
}

// Apply YAML values where CLI flags weren't used
flagsVal := reflect.ValueOf(ret).Elem()
yamlVal := reflect.ValueOf(yamlFlags).Elem()
flagsType := flagsVal.Type()

for i := 0; i < flagsType.NumField(); i++ {
field := flagsType.Field(i)
if yamlTag := field.Tag.Get("yaml"); yamlTag != "" {
if !usedFlags[yamlTag] {
flagField := flagsVal.Field(i)
yamlField := yamlVal.Field(i)
if flagField.CanSet() {
if yamlField.Type() != flagField.Type() {
if err := assignWithConversion(flagField, yamlField); err != nil {
Debugf("Type conversion failed for %s: %v\n", yamlTag, err)
continue
}
} else {
flagField.Set(yamlField)
}
Debugf("Applied YAML value for %s: %v\n", yamlTag, yamlField.Interface())
}
// Apply YAML values where CLI flags weren't used
flagsVal := reflect.ValueOf(ret).Elem()
yamlVal := reflect.ValueOf(yamlFlags).Elem()
flagsType := flagsVal.Type()

for i := 0; i < flagsType.NumField(); i++ {
field := flagsType.Field(i)
if yamlTag := field.Tag.Get("yaml"); yamlTag != "" {
if !usedFlags[yamlTag] {
flagField := flagsVal.Field(i)
yamlField := yamlVal.Field(i)
if flagField.CanSet() {
if yamlField.Type() != flagField.Type() {
if err := assignWithConversion(flagField, yamlField); err != nil {
Debugf("Type conversion failed for %s: %v\n", yamlTag, err)
continue
}
} else {
flagField.Set(yamlField)
}
Debugf("Applied YAML value for %s: %v\n", yamlTag, yamlField.Interface())
}
}
}
}
}

// Handle stdin and messages
info, _ := os.Stdin.Stat()
pipedToStdin := (info.Mode() & os.ModeCharDevice) == 0

if len(args) > 0 {
ret.Message = AppendMessage(ret.Message, args[len(args)-1])
ret.Message = AppendMessage(ret.Message, args[len(args)-1])
}

if pipedToStdin {
var pipedMessage string
if pipedMessage, err = readStdin(); err != nil {
return
}
ret.Message = AppendMessage(ret.Message, pipedMessage)
var pipedMessage string
if pipedMessage, err = readStdin(); err != nil {
return
}
ret.Message = AppendMessage(ret.Message, pipedMessage)
}

return ret, nil
}



func assignWithConversion(targetField, sourceField reflect.Value) error {
switch targetField.Kind() {
case reflect.Float64:
if sourceField.Kind() == reflect.Int || sourceField.Kind() == reflect.Float32 {
targetField.SetFloat(float64(sourceField.Convert(reflect.TypeOf(float64(0))).Float()))
Debugf("Converted field %s : %v\n", targetField.Type(), targetField.Interface())
return nil
}
if sourceField.Kind() == reflect.Int || sourceField.Kind() == reflect.Float32 {
targetField.SetFloat(float64(sourceField.Convert(reflect.TypeOf(float64(0))).Float()))
Debugf("Converted field %s : %v\n", targetField.Type(), targetField.Interface())
return nil
}
case reflect.Int:
if sourceField.Kind() == reflect.Float64 || sourceField.Kind() == reflect.Float32 {
targetField.SetInt(int64(sourceField.Convert(reflect.TypeOf(int64(0))).Int()))
Debugf("Converted field %s : %v\n", targetField.Type(), targetField.Interface())
return nil
}
if sourceField.Kind() == reflect.Float64 || sourceField.Kind() == reflect.Float32 {
targetField.SetInt(int64(sourceField.Convert(reflect.TypeOf(int64(0))).Int()))
Debugf("Converted field %s : %v\n", targetField.Type(), targetField.Interface())
return nil
}
case reflect.String:
if sourceField.Kind() == reflect.Interface {
if str, ok := sourceField.Interface().(string); ok {
targetField.SetString(str)
Debugf("Converted field %s : %v\n", targetField.Type(), targetField.Interface())
return nil
}
if sourceField.Kind() == reflect.Interface {
if str, ok := sourceField.Interface().(string); ok {
targetField.SetString(str)
Debugf("Converted field %s : %v\n", targetField.Type(), targetField.Interface())
return nil
}
}
case reflect.Bool:
if sourceField.Kind() == reflect.Interface {
if b, ok := sourceField.Interface().(bool); ok {
targetField.SetBool(b)
Debugf("Converted field %s : %v\n", targetField.Type(), targetField.Interface())
return nil
}
if sourceField.Kind() == reflect.Interface {
if b, ok := sourceField.Interface().(bool); ok {
targetField.SetBool(b)
Debugf("Converted field %s : %v\n", targetField.Type(), targetField.Interface())
return nil
}
}
}

return fmt.Errorf("unsupported conversion: %s to %s", sourceField.Type(), targetField.Type())
}




func loadYAMLConfig(configPath string) (*Flags, error) {
absPath, err := common.GetAbsolutePath(configPath)
if err != nil {
return nil, fmt.Errorf("invalid config path: %w", err)
return nil, fmt.Errorf("invalid config path: %w", err)
}

data, err := os.ReadFile(absPath)
if err != nil {
if os.IsNotExist(err) {
return nil, fmt.Errorf("config file not found: %s", absPath)
}
return nil, fmt.Errorf("error reading config file: %w", err)
if os.IsNotExist(err) {
return nil, fmt.Errorf("config file not found: %s", absPath)
}
return nil, fmt.Errorf("error reading config file: %w", err)
}

// Use the existing Flags struct for YAML unmarshal
config := &Flags{}
if err := yaml.Unmarshal(data, config); err != nil {
return nil, fmt.Errorf("error parsing config file: %w", err)
return nil, fmt.Errorf("error parsing config file: %w", err)
}

Debugf("Config: %v\n", config)

return config, nil
}


// readStdin reads from stdin and returns the input as a string or an error
func readStdin() (ret string, err error) {
reader := bufio.NewReader(os.Stdin)
Expand Down
88 changes: 44 additions & 44 deletions cli/flags_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -98,69 +98,69 @@ stream: true
`
tmpfile, err := os.CreateTemp("", "config.*.yaml")
if err != nil {
t.Fatal(err)
t.Fatal(err)
}
defer os.Remove(tmpfile.Name())

if _, err := tmpfile.Write([]byte(configContent)); err != nil {
t.Fatal(err)
t.Fatal(err)
}
if err := tmpfile.Close(); err != nil {
t.Fatal(err)
t.Fatal(err)
}

// Test 1: Basic YAML loading
t.Run("Load YAML config", func(t *testing.T) {
oldArgs := os.Args
defer func() { os.Args = oldArgs }()
os.Args = []string{"cmd", "--config", tmpfile.Name()}

flags, err := Init()
assert.NoError(t, err)
assert.Equal(t, 0.9, flags.Temperature)
assert.Equal(t, "gpt-4", flags.Model)
assert.Equal(t, "analyze", flags.Pattern)
assert.True(t, flags.Stream)
oldArgs := os.Args
defer func() { os.Args = oldArgs }()
os.Args = []string{"cmd", "--config", tmpfile.Name()}

flags, err := Init()
assert.NoError(t, err)
assert.Equal(t, 0.9, flags.Temperature)
assert.Equal(t, "gpt-4", flags.Model)
assert.Equal(t, "analyze", flags.Pattern)
assert.True(t, flags.Stream)
})

// Test 2: CLI overrides YAML
t.Run("CLI overrides YAML", func(t *testing.T) {
oldArgs := os.Args
defer func() { os.Args = oldArgs }()
os.Args = []string{"cmd", "--config", tmpfile.Name(), "--temperature", "0.7", "--model", "gpt-3.5-turbo"}

flags, err := Init()
assert.NoError(t, err)
assert.Equal(t, 0.7, flags.Temperature)
assert.Equal(t, "gpt-3.5-turbo", flags.Model)
assert.Equal(t, "analyze", flags.Pattern) // unchanged from YAML
assert.True(t, flags.Stream) // unchanged from YAML
oldArgs := os.Args
defer func() { os.Args = oldArgs }()
os.Args = []string{"cmd", "--config", tmpfile.Name(), "--temperature", "0.7", "--model", "gpt-3.5-turbo"}

flags, err := Init()
assert.NoError(t, err)
assert.Equal(t, 0.7, flags.Temperature)
assert.Equal(t, "gpt-3.5-turbo", flags.Model)
assert.Equal(t, "analyze", flags.Pattern) // unchanged from YAML
assert.True(t, flags.Stream) // unchanged from YAML
})

// Test 3: Invalid YAML config
t.Run("Invalid YAML config", func(t *testing.T) {
badConfig := `
badConfig := `
temperature: "not a float"
model: 123 # should be string
`
badfile, err := os.CreateTemp("", "bad-config.*.yaml")
if err != nil {
t.Fatal(err)
}
defer os.Remove(badfile.Name())

if _, err := badfile.Write([]byte(badConfig)); err != nil {
t.Fatal(err)
}
if err := badfile.Close(); err != nil {
t.Fatal(err)
}

oldArgs := os.Args
defer func() { os.Args = oldArgs }()
os.Args = []string{"cmd", "--config", badfile.Name()}

_, err = Init()
assert.Error(t, err)
badfile, err := os.CreateTemp("", "bad-config.*.yaml")
if err != nil {
t.Fatal(err)
}
defer os.Remove(badfile.Name())

if _, err := badfile.Write([]byte(badConfig)); err != nil {
t.Fatal(err)
}
if err := badfile.Close(); err != nil {
t.Fatal(err)
}

oldArgs := os.Args
defer func() { os.Args = oldArgs }()
os.Args = []string{"cmd", "--config", badfile.Name()}

_, err = Init()
assert.Error(t, err)
})
}
}
6 changes: 3 additions & 3 deletions gomod2nix.toml
Original file line number Diff line number Diff line change
Expand Up @@ -154,9 +154,6 @@ schema = 3
[mod."github.com/leodido/go-urn"]
version = "v1.4.0"
hash = "sha256-Q6kplWkY37Tzy6GOme3Wut40jFK4Izun+ij/BJvcEu0="
[mod."github.com/liushuangls/go-anthropic/v2"]
version = "v2.11.0"
hash = "sha256-VvQ6RT8qcP19mRzBtFKh19czlRk5obHzh1NVs3z/Gkc="
[mod."github.com/mattn/go-isatty"]
version = "v0.0.20"
hash = "sha256-qhw9hWtU5wnyFyuMbKx+7RB8ckQaFQ8D+8GKPkN3HHQ="
Expand Down Expand Up @@ -280,6 +277,9 @@ schema = 3
[mod."gopkg.in/warnings.v0"]
version = "v0.1.2"
hash = "sha256-ATVL9yEmgYbkJ1DkltDGRn/auGAjqGOfjQyBYyUo8s8="
[mod."gopkg.in/yaml.v2"]
version = "v2.4.0"
hash = "sha256-uVEGglIedjOIGZzHW4YwN1VoRSTK8o0eGZqzd+TNdd0="
[mod."gopkg.in/yaml.v3"]
version = "v3.0.1"
hash = "sha256-FqL9TKYJ0XkNwJFnq9j0VvJ5ZUU1RvH/52h/f5bkYAU="
2 changes: 1 addition & 1 deletion pkgs/fabric/version.nix
Original file line number Diff line number Diff line change
@@ -1 +1 @@
"1.4.121"
"1.4.122"
2 changes: 1 addition & 1 deletion version.go
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
package main

var version = "v1.4.121"
var version = "v1.4.122"

0 comments on commit 12284ad

Please sign in to comment.