-
Notifications
You must be signed in to change notification settings - Fork 0
/
cmd.go
65 lines (55 loc) · 1.02 KB
/
cmd.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
package cmd
import (
"bufio"
"fmt"
"io/ioutil"
"log"
"os"
"strings"
"github.com/alecthomas/kong"
"github.com/mvdan/xurls"
)
type options struct {
Verbose bool `help:"Verbose printing."`
Txt []string `arg:"" optional:""`
}
type ParseURLs struct {
options
}
func (c *ParseURLs) Run() (err error) {
kong.Parse(&c.options,
kong.Name("parseurls"),
kong.Description("Command line tool to parse urls from text files or stdin"),
kong.UsageOnError(),
)
if len(c.Txt) == 0 {
scan := bufio.NewScanner(os.Stdin)
for scan.Scan() {
text := scan.Text()
printURLs(text)
}
return scan.Err()
}
for _, txt := range c.Txt {
if c.Verbose {
log.Printf("processing %s", txt)
}
content, err := ioutil.ReadFile(txt)
if err != nil {
return err
}
printURLs(string(content))
}
return nil
}
func printURLs(text string) {
if text == "" {
return
}
for _, ref := range xurls.Strict.FindAllString(text, -1) {
if !strings.HasPrefix(ref, "http") {
continue
}
_, _ = fmt.Fprintln(os.Stdout, ref)
}
}