Skip to content

Commit

Permalink
fix(chaincmd): skip non json in JSONEnsuredBytes (#4540)
Browse files Browse the repository at this point in the history
  • Loading branch information
julienrbrt authored Feb 26, 2025
1 parent a126f68 commit ec7fd51
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 1 deletion.
1 change: 1 addition & 0 deletions changelog.md
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,7 @@
- [#4091](https://github.com/ignite/cli/pull/4091) Fix race conditions in the plugin logic
- [#4128](https://github.com/ignite/cli/pull/4128) Check for duplicate proto fields in config
- [#4402](https://github.com/ignite/cli/pull/4402) Fix gentx parser into the cosmosutil package
- [#4540](https://github.com/ignite/cli/pull/4540) Skip logs / gibberish when parsing commands outputs

## [`v28.8.0`](https://github.com/ignite/cli/releases/tag/v28.8.0)

Expand Down
35 changes: 34 additions & 1 deletion ignite/pkg/chaincmd/runner/runner.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import (
"context"
"encoding/json"
"io"
"strings"

"sigs.k8s.io/yaml"

Expand Down Expand Up @@ -145,12 +146,44 @@ type buffer struct {
func (b *buffer) JSONEnsuredBytes() ([]byte, error) {
bz := b.Bytes()

var out interface{}
// check for valid json
startIndex := strings.IndexAny(string(bz), "{[")
if startIndex >= 0 {
// check if we need to find the matching closing bracket
opening := bz[startIndex]
var closing byte
if opening == '{' {
closing = '}'
} else {
closing = ']'
}

// look for the last matching closing bracket
endIndex := bytes.LastIndexByte(bz, closing)
if endIndex > startIndex {
// extract what appears to be valid JSON
bz = bz[startIndex : endIndex+1]

// verify it's actually valid JSON
var jsonTest any
if err := json.Unmarshal(bz, &jsonTest); err == nil {
return bz, nil
}
}
}

// fallback to yaml parsing
var out any
if err := yaml.Unmarshal(bz, &out); err == nil {
return yaml.YAMLToJSON(bz)
}

// if neither JSON nor YAML parsing succeeded, return the original bytes
// starting from the first opening brace if found, or the entire buffer
if startIndex >= 0 {
return bz[startIndex:], nil
}

return bz, nil
}

Expand Down

0 comments on commit ec7fd51

Please sign in to comment.