forked from GoogleCloudPlatform/golang-samples
-
Notifications
You must be signed in to change notification settings - Fork 0
/
tasks.go
224 lines (190 loc) · 5.52 KB
/
tasks.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
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
// Copyright 2015 Google Inc. All rights reserved.
// Use of this source code is governed by the Apache 2.0
// license that can be found in the LICENSE file.
// [START datastore_all]
// A simple command-line task list manager to demonstrate using the
// cloud.google.com/go/datastore package.
package main
import (
"bufio"
"fmt"
"io"
"log"
"os"
"strconv"
"strings"
"text/tabwriter"
"time"
"cloud.google.com/go/datastore"
"golang.org/x/net/context"
)
func main() {
projID := os.Getenv("DATASTORE_PROJECT_ID")
if projID == "" {
log.Fatal(`You need to set the environment variable "DATASTORE_PROJECT_ID"`)
}
// [START datastore_build_service]
ctx := context.Background()
client, err := datastore.NewClient(ctx, projID)
// [END datastore_build_service]
if err != nil {
log.Fatalf("Could not create datastore client: %v", err)
}
// Print welcome message.
fmt.Println("Cloud Datastore Task List")
fmt.Println()
usage()
// Read commands from stdin.
scanner := bufio.NewScanner(os.Stdin)
fmt.Print("> ")
for scanner.Scan() {
cmd, args, n := parseCmd(scanner.Text())
switch cmd {
case "new":
if args == "" {
log.Printf("Missing description in %q command", cmd)
usage()
break
}
key, err := AddTask(ctx, client, args)
if err != nil {
log.Printf("Failed to create task: %v", err)
break
}
fmt.Printf("Created new task with ID %d\n", key.ID)
case "done":
if n == 0 {
log.Printf("Missing numerical task ID in %q command", cmd)
usage()
break
}
if err := MarkDone(ctx, client, n); err != nil {
log.Printf("Failed to mark task done: %v", err)
break
}
fmt.Printf("Task %d marked done\n", n)
case "list":
tasks, err := ListTasks(ctx, client)
if err != nil {
log.Printf("Failed to fetch task list: %v", err)
break
}
PrintTasks(os.Stdout, tasks)
case "delete":
if n == 0 {
log.Printf("Missing numerical task ID in %q command", cmd)
usage()
break
}
if err := DeleteTask(ctx, client, n); err != nil {
log.Printf("Failed to delete task: %v", err)
break
}
fmt.Printf("Task %d deleted\n", n)
default:
log.Printf("Unknown command %q", cmd)
usage()
}
fmt.Print("> ")
}
if err := scanner.Err(); err != nil {
log.Fatalf("Failed reading stdin: %v", err)
}
}
// [START datastore_add_entity]
// Task is the model used to store tasks in the datastore.
type Task struct {
Desc string `datastore:"description"`
Created time.Time `datastore:"created"`
Done bool `datastore:"done"`
id int64 // The integer ID used in the datastore.
}
// AddTask adds a task with the given description to the datastore,
// returning the key of the newly created entity.
func AddTask(ctx context.Context, client *datastore.Client, desc string) (*datastore.Key, error) {
task := &Task{
Desc: desc,
Created: time.Now(),
}
key := datastore.IncompleteKey("Task", nil)
return client.Put(ctx, key, task)
}
// [END datastore_add_entity]
// [START datastore_update_entity]
// MarkDone marks the task done with the given ID.
func MarkDone(ctx context.Context, client *datastore.Client, taskID int64) error {
// Create a key using the given integer ID.
key := datastore.IDKey("Task", taskID, nil)
// In a transaction load each task, set done to true and store.
_, err := client.RunInTransaction(ctx, func(tx *datastore.Transaction) error {
var task Task
if err := tx.Get(key, &task); err != nil {
return err
}
task.Done = true
_, err := tx.Put(key, &task)
return err
})
return err
}
// [END datastore_update_entity]
// [START datastore_retrieve_entities]
// ListTasks returns all the tasks in ascending order of creation time.
func ListTasks(ctx context.Context, client *datastore.Client) ([]*Task, error) {
var tasks []*Task
// Create a query to fetch all Task entities, ordered by "created".
query := datastore.NewQuery("Task").Order("created")
keys, err := client.GetAll(ctx, query, &tasks)
if err != nil {
return nil, err
}
// Set the id field on each Task from the corresponding key.
for i, key := range keys {
tasks[i].id = key.ID
}
return tasks, nil
}
// [END datastore_retrieve_entities]
// [START datastore_delete_entity]
// DeleteTask deletes the task with the given ID.
func DeleteTask(ctx context.Context, client *datastore.Client, taskID int64) error {
return client.Delete(ctx, datastore.IDKey("Task", taskID, nil))
}
// [END datastore_delete_entity]
// [START datastore_format_results]
// PrintTasks prints the tasks to the given writer.
func PrintTasks(w io.Writer, tasks []*Task) {
// Use a tab writer to help make results pretty.
tw := tabwriter.NewWriter(w, 8, 8, 1, ' ', 0) // Min cell size of 8.
fmt.Fprintf(tw, "ID\tDescription\tStatus\n")
for _, t := range tasks {
if t.Done {
fmt.Fprintf(tw, "%d\t%s\tdone\n", t.id, t.Desc)
} else {
fmt.Fprintf(tw, "%d\t%s\tcreated %v\n", t.id, t.Desc, t.Created)
}
}
tw.Flush()
}
// [END datastore_format_results]
func usage() {
fmt.Print(`Usage:
new <description> Adds a task with a description <description>
done <task-id> Marks a task as done
list Lists all tasks by creation time
delete <task-id> Deletes a task
`)
}
// parseCmd splits a line into a command and optional extra args.
// n will be set if the extra args can be parsed as an int64.
func parseCmd(line string) (cmd, args string, n int64) {
if f := strings.Fields(line); len(f) > 0 {
cmd = f[0]
args = strings.Join(f[1:], " ")
}
if i, err := strconv.ParseInt(args, 10, 64); err == nil {
n = i
}
return cmd, args, n
}
// [END datastore_all]