Skip to content

Commit abe6baf

Browse files
committed
self review
1 parent 858595c commit abe6baf

File tree

2 files changed

+42
-5
lines changed

2 files changed

+42
-5
lines changed

cmd/src/abc_variables_set.go

Lines changed: 9 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
package main
22

33
import (
4+
"bytes"
45
"context"
56
"encoding/json"
67
"flag"
@@ -99,15 +100,18 @@ Values are interpreted as JSON literals when valid. Otherwise they are sent as p
99100
}
100101

101102
func marshalABCVariableValue(raw string) (value string, remove bool, err error) {
102-
var parsed any
103-
if err := json.Unmarshal([]byte(raw), &parsed); err != nil {
104-
parsed = raw
103+
// Try to compact valid JSON literals first. This allows us to send null to delete values, as well as raw numbers.
104+
// If we that doesn't work for the given value, fall back to string encoding.
105+
var compact bytes.Buffer
106+
if err := json.Compact(&compact, []byte(raw)); err == nil {
107+
value := compact.String()
108+
return value, value == "null", nil
105109
}
106110

107-
encoded, err := json.Marshal(parsed)
111+
encoded, err := json.Marshal(raw)
108112
if err != nil {
109113
return "", false, err
110114
}
111115

112-
return string(encoded), parsed == nil, nil
116+
return string(encoded), false, nil
113117
}

cmd/src/abc_variables_set_test.go

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
package main
2+
3+
import "testing"
4+
5+
func TestMarshalABCVariableValuePreservesLargeIntegerLiteral(t *testing.T) {
6+
t.Parallel()
7+
8+
value, remove, err := marshalABCVariableValue("9007199254740993")
9+
if err != nil {
10+
t.Fatalf("marshalABCVariableValue returned error: %v", err)
11+
}
12+
if remove {
13+
t.Fatal("marshalABCVariableValue unexpectedly marked value for removal")
14+
}
15+
if value != "9007199254740993" {
16+
t.Fatalf("marshalABCVariableValue = %q, want %q", value, "9007199254740993")
17+
}
18+
}
19+
20+
func TestMarshalABCVariableValueTreatsNullAsRemoval(t *testing.T) {
21+
t.Parallel()
22+
23+
value, remove, err := marshalABCVariableValue("null")
24+
if err != nil {
25+
t.Fatalf("marshalABCVariableValue returned error: %v", err)
26+
}
27+
if !remove {
28+
t.Fatal("marshalABCVariableValue did not mark null for removal")
29+
}
30+
if value != "null" {
31+
t.Fatalf("marshalABCVariableValue = %q, want %q", value, "null")
32+
}
33+
}

0 commit comments

Comments
 (0)