Last active
January 22, 2018 19:21
-
-
Save jaytaylor/3d6fe5762b1465a0b40ed254651acab8 to your computer and use it in GitHub Desktop.
Original starting place which inspired https://github.com/jaytaylor/iTerm2JTT
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"bufio" | |
"fmt" | |
"io" | |
"io/ioutil" | |
"os" | |
"regexp" | |
"strconv" | |
) | |
type Tip struct { | |
ID int | |
Title string | |
Body string | |
URL string | |
} | |
type Tips []Tip | |
func main() { | |
var r io.Reader = os.Stdin | |
if len(os.Args) > 1 { | |
f, err := os.Open(os.Args[1]) | |
if err != nil { | |
errExit(fmt.Errorf("opening file %q: %s", os.Args[1], err), 2) | |
} | |
defer func() { | |
if err = f.Close(); err != nil { | |
errExit(fmt.Errorf("closing file %q: %s", os.Args[1], err), 3) | |
} | |
}() | |
r = f | |
} | |
tips, err := parseTips(r) | |
if err != nil { | |
errExit(err, 1) | |
} | |
fmt.Printf("got some tips! %+v\n", tips) | |
} | |
func parseTips(r io.Reader) (Tips, error) { | |
var ( | |
startExpr = regexp.MustCompile(`@[ \t]*"([0-9]{3,})"`) | |
fieldExpr = regexp.MustCompile(`kTip(Title|Body|Url)Key[ \t]*:[ \t]*@[ \t]*"(.*)"`) | |
scanner = bufio.NewScanner(r) | |
tips = Tips{} | |
tip *Tip | |
line string | |
) | |
for scanner.Scan() { | |
if err := scanner.Err(); err != nil { | |
if err == io.EOF { | |
if tip != nil { | |
tips = append(tips, *tip) | |
} | |
return tips, nil | |
} | |
return nil, err | |
} | |
line = scanner.Text() | |
if matches := startExpr.FindStringSubmatch(line); len(matches) > 0 { | |
if tip != nil { | |
tips = append(tips, *tip) | |
} | |
id, err := strconv.Atoi(matches[1]) | |
if err != nil { | |
return nil, fmt.Errorf("parsing id %q: %s", matches[1], err) | |
} | |
tip = &Tip{ | |
ID: id, | |
} | |
} | |
if matches := fieldExpr.FindStringSubmatch(line); len(matches) > 0 { | |
if tip == nil { | |
tip = &Tip{} | |
} | |
switch matches[1] { | |
case "Title": | |
tip.Title = matches[2] | |
case "Body": | |
tip.Body = matches[2] | |
case "Url": | |
tip.URL = matches[2] | |
} | |
} | |
} | |
return tips, nil | |
} | |
func errExit(what interface{}, statusCode int) { | |
fmt.Fprintf(os.Stderr, "error: %s\n", what) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment