Skip to content

Commit ac67f0b

Browse files
authored
Merge pull request #23 from ryeguard/sr/cli
feat(cli): minimal cli
2 parents 460df54 + f7140f0 commit ac67f0b

File tree

3 files changed

+99
-0
lines changed

3 files changed

+99
-0
lines changed

cmd/calc/main.go

+55
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
package main
2+
3+
import (
4+
"encoding/json"
5+
"flag"
6+
"fmt"
7+
"io"
8+
"os"
9+
10+
"github.com/ryeguard/ddbcalc"
11+
)
12+
13+
var fileFlag = flag.String("file", "", "The file path and name to read. Must be a json file. Required.")
14+
15+
func readJSON(file string) (map[string]interface{}, error) {
16+
f, err := os.Open(file)
17+
if err != nil {
18+
return nil, fmt.Errorf("open: %w", err)
19+
}
20+
defer f.Close()
21+
22+
b, err := io.ReadAll(f)
23+
if err != nil {
24+
return nil, fmt.Errorf("read: %w", err)
25+
}
26+
27+
var data map[string]interface{}
28+
err = json.Unmarshal(b, &data)
29+
if err != nil {
30+
return nil, fmt.Errorf("unmarshal: %w", err)
31+
}
32+
33+
return data, nil
34+
}
35+
36+
func main() {
37+
flag.Parse()
38+
39+
if *fileFlag == "" {
40+
flag.PrintDefaults()
41+
os.Exit(1)
42+
}
43+
44+
data, err := readJSON(*fileFlag)
45+
if err != nil {
46+
panic(fmt.Sprintf("readJSON: %v", err))
47+
}
48+
49+
size, err := ddbcalc.StructSizeInBytes(data)
50+
if err != nil {
51+
panic(fmt.Sprintf("StructSizeInBytes: %v", err))
52+
}
53+
54+
fmt.Printf("The resulting DynamoDB item size is %d bytes\n", size)
55+
}

cmd/calc/main_test.go

+41
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
package main
2+
3+
import (
4+
"strings"
5+
"testing"
6+
)
7+
8+
func TestReadJSON(t *testing.T) {
9+
t.Run("read non-existent file", func(t *testing.T) {
10+
_, err := readJSON("non-existent.json")
11+
if err == nil {
12+
t.Fatalf("readJSON: expected error, got nil")
13+
}
14+
if !strings.HasPrefix(err.Error(), "open") {
15+
t.Fatalf("readJSON: expected error to start with 'open', got %v", err)
16+
}
17+
})
18+
19+
t.Run("read invalid file", func(t *testing.T) {
20+
_, err := readJSON("../../testdata/test_invalid.json")
21+
if err == nil {
22+
t.Fatalf("readJSON: expected error, got nil")
23+
}
24+
if !strings.HasPrefix(err.Error(), "unmarshal") {
25+
t.Fatalf("readJSON: expected error to start with 'unmarshal', got %v", err)
26+
}
27+
})
28+
29+
t.Run("read valid file", func(t *testing.T) {
30+
actual, err := readJSON("../../testdata/test_int.json")
31+
if err != nil {
32+
t.Fatalf("readJSON: %v", err)
33+
}
34+
if len(actual) == 0 {
35+
t.Fatalf("readJSON: expected non-empty map, got empty map")
36+
}
37+
if _, ok := actual["IntField"]; !ok {
38+
t.Fatalf("readJSON: expected key IntField, got %v", actual)
39+
}
40+
})
41+
}

testdata/test_invalid.json

+3
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
{
2+
"IntField": "101
3+
}

0 commit comments

Comments
 (0)