-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcorrect.go
More file actions
93 lines (87 loc) · 2.13 KB
/
Copy pathcorrect.go
File metadata and controls
93 lines (87 loc) · 2.13 KB
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
package main
import (
"bufio"
"fmt"
"os"
"strconv"
"strings"
"github.com/finkf/pcwgo/api"
"github.com/spf13/cobra"
)
func init() {
correctCommand.Flags().StringVarP(&opts.correct.typ, "type", "t",
"automatic", "set correction type")
correctCommand.Flags().BoolVarP(&opts.correct.stdin, "stdin", "i",
false, "read IDs and corrections from stdin")
}
var correctCommand = cobra.Command{
Use: "correct [ID CORRECTION]...",
Short: "Correct lines or words",
Args: cobra.MinimumNArgs(0),
RunE: doCorrect,
}
func doCorrect(_ *cobra.Command, args []string) error {
c := authenticate()
if !opts.correct.stdin {
for i := 1; i < len(args); i += 2 {
id := args[i-1]
cor := args[i]
if err := correct(c, id, opts.correct.typ, cor); err != nil {
return fmt.Errorf("cannot correct: %v", err)
}
}
return nil
}
s := bufio.NewScanner(os.Stdin)
for s.Scan() {
line := s.Text()
pos := strings.Index(line, " ")
if pos == -1 {
return fmt.Errorf("cannot correct: invalid input line: %q", line)
}
id := line[:pos]
cor := line[pos+1:]
if err := correct(c, id, opts.correct.typ, cor); err != nil {
return fmt.Errorf("cannot correct: %v", err)
}
}
if err := s.Err(); err != nil {
return fmt.Errorf("cannot correct: %v", err)
}
return nil
}
func correct(c *api.Client, id, typ, correction string) error {
cor, err := strconv.Unquote(`"` + correction + `"`)
if err != nil {
return fmt.Errorf("unqote %s: %v", correction, err)
}
var url string
var resp interface{}
var line api.Line
var token api.Token
var bid, pid, lid, wid, len int
switch n := parseIDs(id, &bid, &pid, &lid, &wid, &len); n {
case 3:
url = c.URL("books/%d/pages/%d/lines/%d?t=%s",
bid, pid, lid, typ)
resp = &line
case 4:
url = c.URL("books/%d/pages/%d/lines/%d/tokens/%d?t=%s",
bid, pid, lid, wid, typ)
resp = &token
case 5:
url = c.URL("books/%d/pages/%d/lines/%d/tokens/%d?t=%s&len=%d",
bid, pid, lid, wid, typ, len)
resp = &token
default:
return fmt.Errorf("invalid id: %q", id)
}
err = c.Put(url, struct {
Cor string `json:"correction"`
}{cor}, resp)
if err != nil {
return err
}
format(resp)
return nil
}