This repository has been archived by the owner on Aug 28, 2021. It is now read-only.
/
main.go
92 lines (77 loc) · 2.13 KB
/
main.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
// Copyright 2016 Attic Labs, Inc. All rights reserved.
// Licensed under the Apache License, version 2.0:
// http://www.apache.org/licenses/LICENSE-2.0
package main
import (
"fmt"
"os"
"github.com/attic-labs/kingpin"
"github.com/attic-labs/noms/go/config"
"github.com/attic-labs/noms/go/datas"
"github.com/attic-labs/noms/go/marshal"
"github.com/attic-labs/noms/go/types"
"github.com/attic-labs/noms/go/util/verbose"
)
func main() {
app := kingpin.New("hr", "")
var dsStr = app.Flag("ds", "noms dataset to read/write from").Required().String()
addCmd := app.Command("add-person", "Add a new person")
id := addCmd.Arg("id", "unique person id").Required().Uint64()
name := addCmd.Arg("name", "person name").Required().String()
title := addCmd.Arg("title", "person title").Required().String()
app.Command("list-persons", "list current persons")
verbose.RegisterVerboseFlags(app)
cmd := kingpin.MustParse(app.Parse(os.Args[1:]))
cfg := config.NewResolver()
db, ds, err := cfg.GetDataset(*dsStr)
if err != nil {
fmt.Fprintf(os.Stderr, "Could not create dataset: %s\n", err)
return
}
defer db.Close()
switch cmd {
case "add-person":
addPerson(db, ds, *id, *name, *title)
case "list-persons":
listPersons(ds)
}
}
type Person struct {
Name, Title string
Id uint64
}
func addPerson(db datas.Database, ds datas.Dataset, id uint64, name, title string) {
np, err := marshal.Marshal(db, Person{name, title, id})
if err != nil {
fmt.Fprintln(os.Stderr, err)
return
}
_, err = db.CommitValue(ds, getPersons(ds).Edit().Set(types.Number(id), np).Map())
if err != nil {
fmt.Fprintf(os.Stderr, "Error committing: %s\n", err)
return
}
}
func listPersons(ds datas.Dataset) {
d := getPersons(ds)
if d.Empty() {
fmt.Println("No people found")
return
}
d.IterAll(func(k, v types.Value) {
var p Person
err := marshal.Unmarshal(v, &p)
if err != nil {
fmt.Fprintln(os.Stderr, err)
return
}
fmt.Printf("%s (id: %d, title: %s)\n", p.Name, p.Id, p.Title)
})
}
func getPersons(ds datas.Dataset) types.Map {
hv, ok := ds.MaybeHeadValue()
if ok {
return hv.(types.Map)
}
return types.NewMap(ds.Database())
}