-
Notifications
You must be signed in to change notification settings - Fork 21
/
cli.go
82 lines (73 loc) · 1.7 KB
/
cli.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
package main
import (
"bufio"
"log"
"os"
"strings"
"time"
"github.com/knadh/pfxsigner/internal/processor"
"github.com/urfave/cli"
)
// initCLI initializes CLI mode.
func initCLI(c *cli.Context) error {
// Start workers.
var (
num = c.Int("workers")
jobQ = make(chan processor.Job, 1000)
)
logger.Printf("starting %d workers", num)
proc.Wg.Add(num)
for n := 0; n < num; n++ {
go proc.Listen(jobQ)
}
// Start a separate goroutine to read stdin.
go func() {
log.Println("waiting for jobs from stdin")
if err := readJobsFromStdin(jobQ); err != nil {
log.Fatalf("error reading jobs from stdin: %v", err)
}
close(jobQ)
}()
// Wait until all jobs are done.
proc.Wg.Wait()
var (
s = proc.GetStats()
elapsed = time.Now().Sub(s.StartTime)
)
log.Printf("%d succeeded. %d failed.", s.JobsDone, s.JobsFailed)
log.Printf("%0.2f seconds. %0.2f / sec",
elapsed.Seconds(),
float64(s.JobsDone+s.JobsFailed)/elapsed.Seconds())
return nil
}
// readJobsFromStdin reads PDF jobs from stdin in the following format
// and sends them to workers for processing.
// inFile|outFile
// inFile|outFile
// inFile|outFile
// ...
func readJobsFromStdin(ch chan processor.Job) error {
s := bufio.NewScanner(os.Stdin)
for s.Scan() {
line := strings.TrimSpace(s.Text())
if len(line) == 0 {
continue
}
chunks := strings.Split(line, "|")
if len(line) == 0 {
continue
}
if len(chunks) != 3 || len(chunks[0]) == 0 || len(chunks[1]) == 0 || len(chunks[2]) == 0 {
logger.Printf("skipping invalid item: %s", line)
continue
}
ch <- processor.Job{
CertName: chunks[0],
InFile: chunks[1],
OutFile: chunks[2]}
}
if err := s.Err(); err != nil {
return err
}
return nil
}