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
|
package main
import (
"bytes"
"encoding/hex"
"flag"
"fmt"
"io"
"os"
"strings"
"text/template"
"time"
"github.com/segmentio/ksuid"
)
var (
count int
format string
tpltxt string
verbose bool
)
func init() {
flag.IntVar(&count, "n", 1, "Number of KSUIDs to generate when called with no other arguments.")
flag.StringVar(&format, "f", "string", "One of string, inspect, time, timestamp, payload, raw, or template.")
flag.StringVar(&tpltxt, "t", "", "The Go template used to format the output.")
flag.BoolVar(&verbose, "v", false, "Turn on verbose mode.")
}
func main() {
flag.Parse()
args := flag.Args()
var print func(ksuid.KSUID)
switch format {
case "string":
print = printString
case "inspect":
print = printInspect
case "time":
print = printTime
case "timestamp":
print = printTimestamp
case "payload":
print = printPayload
case "raw":
print = printRaw
case "template":
print = printTemplate
default:
fmt.Println("Bad formatting function:", format)
os.Exit(1)
}
if len(args) == 0 {
for i := 0; i < count; i++ {
args = append(args, ksuid.New().String())
}
}
var ids []ksuid.KSUID
for _, arg := range args {
id, err := ksuid.Parse(arg)
if err != nil {
fmt.Printf("Error when parsing %q: %s\n\n", arg, err)
flag.PrintDefaults()
os.Exit(1)
}
ids = append(ids, id)
}
for _, id := range ids {
if verbose {
fmt.Printf("%s: ", id)
}
print(id)
}
}
func printString(id ksuid.KSUID) {
fmt.Println(id.String())
}
func printInspect(id ksuid.KSUID) {
const inspectFormat = `
REPRESENTATION:
String: %v
Raw: %v
COMPONENTS:
Time: %v
Timestamp: %v
Payload: %v
`
fmt.Printf(inspectFormat,
id.String(),
strings.ToUpper(hex.EncodeToString(id.Bytes())),
id.Time(),
id.Timestamp(),
strings.ToUpper(hex.EncodeToString(id.Payload())),
)
}
func printTime(id ksuid.KSUID) {
fmt.Println(id.Time())
}
func printTimestamp(id ksuid.KSUID) {
fmt.Println(id.Timestamp())
}
func printPayload(id ksuid.KSUID) {
os.Stdout.Write(id.Payload())
}
func printRaw(id ksuid.KSUID) {
os.Stdout.Write(id.Bytes())
}
func printTemplate(id ksuid.KSUID) {
b := &bytes.Buffer{}
t := template.Must(template.New("").Parse(tpltxt))
t.Execute(b, struct {
String string
Raw string
Time time.Time
Timestamp uint32
Payload string
}{
String: id.String(),
Raw: strings.ToUpper(hex.EncodeToString(id.Bytes())),
Time: id.Time(),
Timestamp: id.Timestamp(),
Payload: strings.ToUpper(hex.EncodeToString(id.Payload())),
})
b.WriteByte('\n')
io.Copy(os.Stdout, b)
}
|