From 85b4f409a4c06e5482d557ca40f81406edce185c Mon Sep 17 00:00:00 2001 From: hamrezoffic-source <304277313+hamrezoffic-source@users.noreply.github.com> Date: Sun, 22 Nov 2026 10:36:49 +0000 Subject: [PATCH 1/5] Initial plan From 4b3b6e269a5e22b886ff8bb87d750fc4f750d656 Mon Sep 17 00:00:00 2001 From: hamrezoffic-source <304277313+hamrezoffic-source@users.noreply.github.com> Date: Sun, 22 Nov 2026 10:40:09 +0000 Subject: [PATCH 2/5] Add core CLI implementation Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com> --- go.mod | 5 + main.go | 376 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 381 insertions(+) create mode 100644 go.mod create mode 100644 main.go diff --git a/go.mod b/go.mod new file mode 100644 index 0000000..ac3d4eb --- /dev/null +++ b/go.mod @@ -0,0 +1,5 @@ +module github.com/hamrezoffic-source/devkit + +go 1.22 + +require gopkg.in/yaml.v3 v3.0.1 diff --git a/main.go b/main.go new file mode 100644 index 0000000..0c3bab3 --- /dev/null +++ b/main.go @@ -0,0 +1,376 @@ +package main + +import ( + "bytes" + "encoding/json" + "errors" + "flag" + "fmt" + "io" + "net" + "os" + "strconv" + "strings" + "time" + + "gopkg.in/yaml.v3" +) + +const usage = `devkit - a fast, portable developer toolkit + +Usage: + devkit json format [file|-] + devkit json to-yaml [file|-] + devkit yaml to-json [file|-] + devkit port check + +Aliases: + devkit format [file|-] + devkit json-to-yaml [file|-] + devkit yaml-to-json [file|-] + devkit check-port + +Use "-" or omit the file argument to read from standard input. +` + +func readInput(args []string) ([]byte, error) { + if len(args) == 0 || args[0] == "-" { + return io.ReadAll(os.Stdin) + } + if len(args) > 1 { + return nil, errors.New("too many arguments") + } + return os.ReadFile(args[0]) +} + +func jsonDecoder(data []byte) (*json.Decoder, error) { + decoder := json.NewDecoder(bytes.NewReader(data)) + decoder.UseNumber() + return decoder, nil +} + +func FormatJSON(data []byte) ([]byte, error) { + decoder, _ := jsonDecoder(data) + var value any + if err := decoder.Decode(&value); err != nil { + return nil, fmt.Errorf("invalid JSON: %w", err) + } + var trailing any + if err := decoder.Decode(&trailing); err != io.EOF { + if err == nil { + return nil, errors.New("invalid JSON: multiple JSON values") + } + return nil, fmt.Errorf("invalid JSON: %w", err) + } + output, err := json.MarshalIndent(value, "", " ") + if err != nil { + return nil, err + } + return append(output, '\n'), nil +} + +func JSONToYAML(data []byte) ([]byte, error) { + decoder, _ := jsonDecoder(data) + var value any + if err := decoder.Decode(&value); err != nil { + return nil, fmt.Errorf("invalid JSON: %w", err) + } + var trailing any + if err := decoder.Decode(&trailing); err != io.EOF { + if err == nil { + return nil, errors.New("invalid JSON: multiple JSON values") + } + return nil, fmt.Errorf("invalid JSON: %w", err) + } + output, err := yaml.Marshal(value) + if err != nil { + return nil, fmt.Errorf("convert JSON to YAML: %w", err) + } + return output, nil +} + +func yamlNodeToJSONCompatible(node *yaml.Node) (any, error) { + switch node.Kind { + case yaml.DocumentNode: + if len(node.Content) == 0 { + return nil, nil + } + return yamlNodeToJSONCompatible(node.Content[0]) + case yaml.AliasNode: + return yamlNodeToJSONCompatible(node.Alias) + case yaml.ScalarNode: + if node.Tag == "!!null" || node.Value == "" && node.Tag == "" { + return nil, nil + } + switch node.Tag { + case "!!bool": + var value bool + if err := node.Decode(&value); err != nil { + return nil, err + } + return value, nil + case "!!int": + text := strings.ReplaceAll(node.Value, "_", "") + if strings.HasPrefix(text, "0x") || strings.HasPrefix(text, "0X") { + value, err := strconv.ParseUint(text[2:], 16, 64) + if err == nil { + return json.Number(strconv.FormatUint(value, 10)), nil + } + } + if strings.HasPrefix(text, "0o") || strings.HasPrefix(text, "0O") { + value, err := strconv.ParseUint(text[2:], 8, 64) + if err == nil { + return json.Number(strconv.FormatUint(value, 10)), nil + } + } + if strings.HasPrefix(text, "0b") || strings.HasPrefix(text, "0B") { + value, err := strconv.ParseUint(text[2:], 2, 64) + if err == nil { + return json.Number(strconv.FormatUint(value, 10)), nil + } + } + if strings.HasPrefix(text, "-") { + value, err := strconv.ParseInt(text, 10, 64) + if err == nil { + return json.Number(strconv.FormatInt(value, 10)), nil + } + } + value, err := strconv.ParseUint(text, 10, 64) + if err == nil { + return json.Number(strconv.FormatUint(value, 10)), nil + } + return node.Value, nil + case "!!float": + text := strings.ReplaceAll(node.Value, "_", "") + if text == ".inf" || text == "+.inf" || text == "-.inf" || + text == ".nan" || text == "+.nan" || text == "-.nan" { + return nil, fmt.Errorf("YAML value %q is not representable in JSON", node.Value) + } + var value float64 + if err := node.Decode(&value); err != nil { + return nil, err + } + return value, nil + case "!!timestamp": + var value time.Time + if err := node.Decode(&value); err == nil { + return value.Format(time.RFC3339), nil + } + fallthrough + default: + return node.Value, nil + } + case yaml.SequenceNode: + value := make([]any, 0, len(node.Content)) + for _, child := range node.Content { + item, err := yamlNodeToJSONCompatible(child) + if err != nil { + return nil, err + } + value = append(value, item) + } + return value, nil + case yaml.MappingNode: + value := make(map[string]any, len(node.Content)/2) + for i := 0; i < len(node.Content); i += 2 { + keyNode, child := node.Content[i], node.Content[i+1] + key, err := yamlNodeToJSONCompatible(keyNode) + if err != nil { + return nil, err + } + text, ok := key.(string) + if !ok { + return nil, fmt.Errorf("YAML mapping key %q is not a string", keyNode.Value) + } + if _, exists := value[text]; exists { + return nil, fmt.Errorf("duplicate YAML mapping key %q", text) + } + item, err := yamlNodeToJSONCompatible(child) + if err != nil { + return nil, err + } + value[text] = item + } + return value, nil + default: + return nil, fmt.Errorf("unsupported YAML node kind") + } +} + +func YAMLToJSON(data []byte) ([]byte, error) { + decoder := yaml.NewDecoder(bytes.NewReader(data)) + var documents []any + for { + var node yaml.Node + err := decoder.Decode(&node) + if err == io.EOF { + break + } + if err != nil { + return nil, fmt.Errorf("invalid YAML: %w", err) + } + if len(node.Content) == 0 { + continue + } + value, err := yamlNodeToJSONCompatible(&node) + if err != nil { + return nil, err + } + documents = append(documents, value) + } + if len(documents) == 0 { + return []byte("null\n"), nil + } + var value any = documents[0] + if len(documents) > 1 { + value = documents + } + output, err := json.MarshalIndent(value, "", " ") + if err != nil { + return nil, fmt.Errorf("convert YAML to JSON: %w", err) + } + return append(output, '\n'), nil +} + +func CheckTCPPort(host string, port int, timeout time.Duration) error { + address := net.JoinHostPort(host, strconv.Itoa(port)) + conn, err := net.DialTimeout("tcp", address, timeout) + if err != nil { + return err + } + return conn.Close() +} + +func writeOutput(data []byte) error { + _, err := os.Stdout.Write(data) + return err +} + +func run(args []string) error { + if len(args) == 0 { + fmt.Print(usage) + return nil + } + + switch args[0] { + case "-h", "--help", "help": + fmt.Print(usage) + return nil + case "json": + if len(args) < 2 { + return errors.New("json command requires format, to-yaml, or tojson") + } + switch args[1] { + case "format": + data, err := readInput(args[2:]) + if err != nil { + return err + } + output, err := FormatJSON(data) + if err != nil { + return err + } + return writeOutput(output) + case "to-yaml", "toyaml", "2yaml": + data, err := readInput(args[2:]) + if err != nil { + return err + } + output, err := JSONToYAML(data) + if err != nil { + return err + } + return writeOutput(output) + default: + return fmt.Errorf("unknown json command %q", args[1]) + } + case "yaml": + if len(args) < 2 { + return errors.New("yaml command requires to-json or tojson") + } + switch args[1] { + case "to-json", "tojson", "2json": + data, err := readInput(args[2:]) + if err != nil { + return err + } + output, err := YAMLToJSON(data) + if err != nil { + return err + } + return writeOutput(output) + default: + return fmt.Errorf("unknown yaml command %q", args[1]) + } + case "port": + if len(args) < 2 || args[1] != "check" { + return errors.New("port command requires check") + } + return runPortCheck(args[2:]) + case "format": + data, err := readInput(args[1:]) + if err != nil { + return err + } + output, err := FormatJSON(data) + if err != nil { + return err + } + return writeOutput(output) + case "json-to-yaml", "jsontoyaml", "json2yaml": + data, err := readInput(args[1:]) + if err != nil { + return err + } + output, err := JSONToYAML(data) + if err != nil { + return err + } + return writeOutput(output) + case "yaml-to-json", "yamltojson", "yaml2json": + data, err := readInput(args[1:]) + if err != nil { + return err + } + output, err := YAMLToJSON(data) + if err != nil { + return err + } + return writeOutput(output) + case "check-port", "portcheck", "check": + return runPortCheck(args[1:]) + default: + return fmt.Errorf("unknown command %q\n\n%s", args[0], usage) + } +} + +func runPortCheck(args []string) error { + fs := flag.NewFlagSet("check", flag.ContinueOnError) + fs.SetOutput(io.Discard) + timeoutSeconds := fs.Float64("timeout", 3, "connection timeout in seconds") + if err := fs.Parse(args); err != nil { + return err + } + remaining := fs.Args() + if len(remaining) != 2 { + return errors.New("usage: devkit port check ") + } + port, err := strconv.Atoi(remaining[1]) + if err != nil || port < 1 || port > 65535 { + return errors.New("port must be an integer between 1 and 65535") + } + timeout := time.Duration(*timeoutSeconds * float64(time.Second)) + if err := CheckTCPPort(remaining[0], port, timeout); err != nil { + fmt.Fprintf(os.Stdout, "closed: %s\n", err) + return err + } + fmt.Fprintln(os.Stdout, "open") + return nil +} + +func main() { + if err := run(os.Args[1:]); err != nil { + fmt.Fprintf(os.Stderr, "error: %v\n", err) + os.Exit(1) + } +} From d86abce2b4c293757f36bbecb2a359f24baeb098 Mon Sep 17 00:00:00 2001 From: hamrezoffic-source <304277313+hamrezoffic-source@users.noreply.github.com> Date: Sun, 22 Nov 2026 10:41:43 +0000 Subject: [PATCH 3/5] Add tests and automation workflows Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com> --- .github/workflows/release.yml | 74 ++++++++++++++ .github/workflows/test.yml | 29 ++++++ README.md | 57 ++++++++++- go.sum | 4 + main.go | 40 +++++--- main_test.go | 179 ++++++++++++++++++++++++++++++++++ 6 files changed, 371 insertions(+), 12 deletions(-) create mode 100644 .github/workflows/release.yml create mode 100644 .github/workflows/test.yml create mode 100644 go.sum create mode 100644 main_test.go diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml new file mode 100644 index 0000000..932452e --- /dev/null +++ b/.github/workflows/release.yml @@ -0,0 +1,74 @@ +name: Release + +on: + push: + tags: + - "v*" + +permissions: + contents: write + +jobs: + build: + strategy: + fail-fast: false + matrix: + include: + - goos: linux + goarch: amd64 + runner: ubuntu-latest + - goos: linux + goarch: arm64 + runner: ubuntu-latest + - goos: windows + goarch: amd64 + runner: ubuntu-latest + - goos: windows + goarch: arm64 + runner: ubuntu-latest + - goos: darwin + goarch: amd64 + runner: ubuntu-latest + - goos: darwin + goarch: arm64 + runner: ubuntu-latest + runs-on: ${{ matrix.runner }} + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-go@v5 + with: + go-version: "1.22.x" + cache: true + - name: Build + shell: bash + env: + GOOS: ${{ matrix.goos }} + GOARCH: ${{ matrix.goarch }} + CGO_ENABLED: 0 + run: | + ext="" + if [ "${GOOS}" = "windows" ]; then ext=".exe"; fi + mkdir -p dist + go build -trimpath -ldflags="-s -w" -o "dist/devkit-${GOOS}-${GOARCH}${ext}" . + - uses: actions/upload-artifact@v4 + with: + name: devkit-${{ matrix.goos }}-${{ matrix.goarch }} + path: dist/* + + release: + needs: build + runs-on: ubuntu-latest + steps: + - uses: actions/download-artifact@v4 + with: + pattern: devkit-* + path: dist + merge-multiple: true + - name: Create GitHub release + env: + GH_TOKEN: ${{ github.token }} + run: | + gh release create "${GITHUB_REF_NAME}" dist/* \ + --repo "${GITHUB_REPOSITORY}" \ + --title "devkit ${GITHUB_REF_NAME}" \ + --generate-notes diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml new file mode 100644 index 0000000..b26b366 --- /dev/null +++ b/.github/workflows/test.yml @@ -0,0 +1,29 @@ +name: Test + +on: + push: + pull_request: + +permissions: + contents: read + +jobs: + test: + strategy: + fail-fast: false + matrix: + os: [ubuntu-latest, windows-latest, macos-latest] + runs-on: ${{ matrix.os }} + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-go@v5 + with: + go-version: "1.22.x" + cache: true + - name: Format check + run: test -z "$(gofmt -l .)" || (gofmt -l . && exit 1) + if: runner.os != 'Windows' + - name: Test + run: go test ./... + - name: Build + run: go build ./... diff --git a/README.md b/README.md index fed1e11..dd31a33 100644 --- a/README.md +++ b/README.md @@ -1,2 +1,57 @@ # devkit -A fast, portable developer toolkit for formatting JSON, converting between JSON and YAML, and checking TCP ports. + +`devkit` is a fast, portable developer toolkit for formatting JSON, converting +between JSON and YAML, and checking TCP ports. + +## Install + +Download a binary for Windows, Linux, or macOS from the GitHub Releases page, +or build it from source: + +```sh +go build -o devkit . +``` + +## JSON + +Format JSON from a file or standard input: + +```sh +devkit json format input.json +cat input.json | devkit json format - +devkit format input.json +``` + +Convert JSON to YAML: + +```sh +devkit json to-yaml input.json +cat input.json | devkit json-to-yaml - +``` + +Large JSON integers are preserved without floating-point rounding. + +## YAML + +Convert YAML to formatted JSON: + +```sh +devkit yaml to-json input.yaml +cat input.yaml | devkit yaml-to-json - +``` + +Empty input converts to `null`. Multiple YAML documents become a JSON array. +YAML mapping keys must be strings, duplicate keys are rejected, and non-finite +numbers cannot be represented by JSON. + +## TCP ports + +Check whether a TCP port accepts connections: + +```sh +devkit port check example.com 443 +devkit port check 127.0.0.1 8080 --timeout 5 +devkit check-port example.com 443 +``` + +The command prints `open` on success and exits with a non-zero status on failure. diff --git a/go.sum b/go.sum new file mode 100644 index 0000000..a62c313 --- /dev/null +++ b/go.sum @@ -0,0 +1,4 @@ +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= +gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= diff --git a/main.go b/main.go index 0c3bab3..7c3b7d8 100644 --- a/main.go +++ b/main.go @@ -4,7 +4,6 @@ import ( "bytes" "encoding/json" "errors" - "flag" "fmt" "io" "net" @@ -265,7 +264,7 @@ func run(args []string) error { data, err := readInput(args[2:]) if err != nil { return err - } + } output, err := FormatJSON(data) if err != nil { return err @@ -293,11 +292,11 @@ func run(args []string) error { data, err := readInput(args[2:]) if err != nil { return err - } + } output, err := YAMLToJSON(data) if err != nil { return err - } + } return writeOutput(output) default: return fmt.Errorf("unknown yaml command %q", args[1]) @@ -345,13 +344,32 @@ func run(args []string) error { } func runPortCheck(args []string) error { - fs := flag.NewFlagSet("check", flag.ContinueOnError) - fs.SetOutput(io.Discard) - timeoutSeconds := fs.Float64("timeout", 3, "connection timeout in seconds") - if err := fs.Parse(args); err != nil { - return err + timeoutSeconds := 3.0 + remaining := make([]string, 0, len(args)) + for i := 0; i < len(args); i++ { + arg := args[i] + switch { + case arg == "--timeout" || arg == "-timeout": + if i+1 >= len(args) { + return errors.New("timeout requires a value") + } + i++ + value, err := strconv.ParseFloat(args[i], 64) + if err != nil || value <= 0 { + return errors.New("timeout must be a positive number") + } + timeoutSeconds = value + case strings.HasPrefix(arg, "--timeout=") || strings.HasPrefix(arg, "-timeout="): + text := arg[strings.IndexByte(arg, '=')+1:] + value, err := strconv.ParseFloat(text, 64) + if err != nil || value <= 0 { + return errors.New("timeout must be a positive number") + } + timeoutSeconds = value + default: + remaining = append(remaining, arg) + } } - remaining := fs.Args() if len(remaining) != 2 { return errors.New("usage: devkit port check ") } @@ -359,7 +377,7 @@ func runPortCheck(args []string) error { if err != nil || port < 1 || port > 65535 { return errors.New("port must be an integer between 1 and 65535") } - timeout := time.Duration(*timeoutSeconds * float64(time.Second)) + timeout := time.Duration(timeoutSeconds * float64(time.Second)) if err := CheckTCPPort(remaining[0], port, timeout); err != nil { fmt.Fprintf(os.Stdout, "closed: %s\n", err) return err diff --git a/main_test.go b/main_test.go new file mode 100644 index 0000000..0bb9fc3 --- /dev/null +++ b/main_test.go @@ -0,0 +1,179 @@ +package main + +import ( + "bytes" + "net" + "os" + "os/exec" + "path/filepath" + "runtime" + "strings" + "testing" + "time" +) + +func TestFormatJSON(t *testing.T) { + tests := []struct { + name string + input string + want string + wantErr bool + }{ + {name: "object", input: `{"b":2,"a":[1,true,null]}`, want: "{\n \"a\": [\n 1,\n true,\n null\n ],\n \"b\": 2\n}\n"}, + {name: "large integer remains exact", input: `{"n":9007199254740993}`, want: "9007199254740993", wantErr: false}, + {name: "empty object", input: `{}`, want: "{}\n"}, + {name: "trailing data", input: `{} {}`, wantErr: true}, + {name: "malformed", input: `{"a":}`, wantErr: true}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + got, err := FormatJSON([]byte(tt.input)) + if tt.wantErr { + if err == nil { + t.Fatal("FormatJSON() expected an error") + } + return + } + if err != nil { + t.Fatalf("FormatJSON() error = %v", err) + } + if tt.name == "large integer remains exact" { + if !bytes.Contains(got, []byte(tt.want)) { + t.Fatalf("FormatJSON() = %s, want exact integer %s", got, tt.want) + } + return + } + if string(got) != tt.want { + t.Fatalf("FormatJSON() = %q, want %q", got, tt.want) + } + }) + } +} + +func TestJSONYAMLRoundTrip(t *testing.T) { + input := []byte(`{"name":"devkit","enabled":true,"count":3,"items":["a",null],"nested":{"ok":false}}`) + yamlOutput, err := JSONToYAML(input) + if err != nil { + t.Fatalf("JSONToYAML() error = %v", err) + } + jsonOutput, err := YAMLToJSON(yamlOutput) + if err != nil { + t.Fatalf("YAMLToJSON() error = %v", err) + } + for _, want := range []string{"devkit", "enabled", "count", "items", "nested"} { + if !bytes.Contains(jsonOutput, []byte(want)) { + t.Fatalf("YAMLToJSON() = %s, missing %q", jsonOutput, want) + } + } +} + +func TestYAMLToJSONEdgeCases(t *testing.T) { + tests := []struct { + name string + input string + want string + wantErr string + }{ + {name: "null and booleans", input: "a: null\nb: true\nc: false\n", want: "null"}, + {name: "sequence", input: "- red\n- green\n- blue\n", want: "red"}, + {name: "quoted string", input: "value: \"0123\"\n", want: "0123"}, + {name: "empty document", input: "", want: "null"}, + {name: "infinite float", input: "value: .inf\n", wantErr: "not representable"}, + {name: "non string key", input: "1: value\n", wantErr: "not a string"}, + {name: "duplicate key", input: "a: 1\na: 2\n", wantErr: "duplicate"}, + {name: "malformed", input: "a: [one, two\n", wantErr: "invalid YAML"}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + got, err := YAMLToJSON([]byte(tt.input)) + if tt.wantErr != "" { + if err == nil || !strings.Contains(err.Error(), tt.wantErr) { + t.Fatalf("YAMLToJSON() error = %v, want containing %q", err, tt.wantErr) + } + return + } + if err != nil { + t.Fatalf("YAMLToJSON() error = %v", err) + } + if !bytes.Contains(got, []byte(tt.want)) { + t.Fatalf("YAMLToJSON() = %s, want containing %q", got, tt.want) + } + }) + } +} + +func TestCheckTCPPort(t *testing.T) { + listener, err := net.Listen("tcp", "127.0.0.1:0") + if err != nil { + t.Skipf("cannot listen: %v", err) + } + defer listener.Close() + + done := make(chan struct{}) + go func() { + conn, err := listener.Accept() + if err == nil { + conn.Close() + } + close(done) + }() + port := listener.Addr().(*net.TCPAddr).Port + if err := CheckTCPPort("127.0.0.1", port, time.Second); err != nil { + t.Fatalf("CheckTCPPort() error = %v", err) + } + <-done + + if err := CheckTCPPort("127.0.0.1", 1, 20*time.Millisecond); err == nil { + t.Fatal("CheckTCPPort() unexpectedly succeeded") + } +} + +func TestCLIEndToEnd(t *testing.T) { + if runtime.GOOS == "windows" { + t.Skip("subprocess executable path is covered by the build matrix") + } + dir := t.TempDir() + binary := filepath.Join(dir, "devkit") + build := exec.Command("go", "build", "-o", binary, ".") + build.Dir = "." + if output, err := build.CombinedOutput(); err != nil { + t.Fatalf("go build failed: %v\n%s", err, output) + } + + tests := []struct { + name string + args []string + input string + want string + wantErr bool + }{ + {name: "format stdin", args: []string{"json", "format", "-"}, input: `{"ok":true}`, want: "\"ok\": true"}, + {name: "json to yaml alias", args: []string{"json-to-yaml", "-"}, input: `{"ok":true}`, want: "ok: true"}, + {name: "yaml to json", args: []string{"yaml", "to-json", "-"}, input: "ok: true\n", want: "\"ok\": true"}, + {name: "bad JSON", args: []string{"json", "format", "-"}, input: `{bad`, wantErr: true}, + {name: "help", args: []string{"--help"}, want: "devkit"}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + cmd := exec.Command(binary, tt.args...) + cmd.Stdin = strings.NewReader(tt.input) + output, err := cmd.CombinedOutput() + if tt.wantErr { + if err == nil { + t.Fatalf("command unexpectedly succeeded: %s", output) + } + return + } + if err != nil { + t.Fatalf("command failed: %v\n%s", err, output) + } + if !bytes.Contains(output, []byte(tt.want)) { + t.Fatalf("output = %q, want containing %q", output, tt.want) + } + }) + } +} + +func TestMain(m *testing.M) { + os.Exit(m.Run()) +} From f65dc3191edb4b2b00d385f0575916a159918ab1 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 23 Nov 2026 03:02:24 +0330 Subject: [PATCH 4/5] Keep number types in JSON to YAML conversion json.Number values were emitted as quoted YAML strings (1 -> "1"), so a JSON -> YAML -> JSON round trip silently changed types. Also fix misleading error messages and a duplicated port-check error. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_0183H1i14AVAdwx5KFXBDo7Q --- main.go | 34 ++++++++++++++++++++++++++++++---- main_test.go | 24 ++++++++++++++++++++++++ 2 files changed, 54 insertions(+), 4 deletions(-) diff --git a/main.go b/main.go index 7c3b7d8..e9a3387 100644 --- a/main.go +++ b/main.go @@ -81,13 +81,39 @@ func JSONToYAML(data []byte) ([]byte, error) { } return nil, fmt.Errorf("invalid JSON: %w", err) } - output, err := yaml.Marshal(value) + output, err := yaml.Marshal(numbersToYAMLNodes(value)) if err != nil { return nil, fmt.Errorf("convert JSON to YAML: %w", err) } return output, nil } +// numbersToYAMLNodes replaces json.Number values with YAML scalar nodes tagged +// as !!int or !!float. Without this, yaml.v3 sees json.Number as a string and +// emits quoted values ("1"), which silently changes the data type. +func numbersToYAMLNodes(value any) any { + switch v := value.(type) { + case json.Number: + tag := "!!int" + if strings.ContainsAny(string(v), ".eE") { + tag = "!!float" + } + return &yaml.Node{Kind: yaml.ScalarNode, Tag: tag, Value: string(v)} + case map[string]any: + for key, item := range v { + v[key] = numbersToYAMLNodes(item) + } + return v + case []any: + for i, item := range v { + v[i] = numbersToYAMLNodes(item) + } + return v + default: + return value + } +} + func yamlNodeToJSONCompatible(node *yaml.Node) (any, error) { switch node.Kind { case yaml.DocumentNode: @@ -257,7 +283,7 @@ func run(args []string) error { return nil case "json": if len(args) < 2 { - return errors.New("json command requires format, to-yaml, or tojson") + return errors.New("json command requires format or to-yaml") } switch args[1] { case "format": @@ -285,7 +311,7 @@ func run(args []string) error { } case "yaml": if len(args) < 2 { - return errors.New("yaml command requires to-json or tojson") + return errors.New("yaml command requires to-json") } switch args[1] { case "to-json", "tojson", "2json": @@ -379,7 +405,7 @@ func runPortCheck(args []string) error { } timeout := time.Duration(timeoutSeconds * float64(time.Second)) if err := CheckTCPPort(remaining[0], port, timeout); err != nil { - fmt.Fprintf(os.Stdout, "closed: %s\n", err) + fmt.Fprintln(os.Stdout, "closed") return err } fmt.Fprintln(os.Stdout, "open") diff --git a/main_test.go b/main_test.go index 0bb9fc3..b5b134a 100644 --- a/main_test.go +++ b/main_test.go @@ -177,3 +177,27 @@ func TestCLIEndToEnd(t *testing.T) { func TestMain(m *testing.M) { os.Exit(m.Run()) } + +func TestJSONToYAMLKeepsNumberTypes(t *testing.T) { + input := []byte(`{"int":1,"neg":-7,"float":1.5,"big":12345678901234567890,"nested":[3,{"x":4}],"str":"5"}`) + yamlOutput, err := JSONToYAML(input) + if err != nil { + t.Fatalf("JSONToYAML() error = %v", err) + } + for _, quoted := range []string{`"1"`, `"-7"`, `"1.5"`, `"12345678901234567890"`} { + if bytes.Contains(yamlOutput, []byte(quoted)) { + t.Fatalf("JSONToYAML() quoted a number %s:\n%s", quoted, yamlOutput) + } + } + if !bytes.Contains(yamlOutput, []byte(`str: "5"`)) { + t.Fatalf("JSONToYAML() lost the string type of \"5\":\n%s", yamlOutput) + } + back, err := YAMLToJSON(yamlOutput) + if err != nil { + t.Fatalf("YAMLToJSON() error = %v", err) + } + want, _ := FormatJSON(input) + if string(back) != string(want) { + t.Fatalf("round trip changed data:\n got %s\nwant %s", back, want) + } +} From 1330c3c4984214cae4f71173b0d8feae8136bd7c Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 23 Nov 2026 03:18:51 +0330 Subject: [PATCH 5/5] CI: build with current stable Go Go 1.22 binaries lack the LC_UUID load command that current macOS dyld requires, so the macOS test job aborted before running tests (also failing on the base branch). go.mod still declares 1.22 as the minimum language version. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_0183H1i14AVAdwx5KFXBDo7Q --- .github/workflows/release.yml | 2 +- .github/workflows/test.yml | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 932452e..af69f7f 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -37,7 +37,7 @@ jobs: - uses: actions/checkout@v4 - uses: actions/setup-go@v5 with: - go-version: "1.22.x" + go-version: "stable" cache: true - name: Build shell: bash diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index b26b366..042ac1f 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -18,7 +18,7 @@ jobs: - uses: actions/checkout@v4 - uses: actions/setup-go@v5 with: - go-version: "1.22.x" + go-version: "stable" cache: true - name: Format check run: test -z "$(gofmt -l .)" || (gofmt -l . && exit 1)