Created
May 1, 2018 21:05
-
-
Save sgmac/29092a6abf14d700844747d8a8e4872f to your computer and use it in GitHub Desktop.
Managing opml feeds
This file contains hidden or 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 ( | |
"encoding/xml" | |
"flag" | |
"fmt" | |
"io/ioutil" | |
"log" | |
"os" | |
"strings" | |
"text/tabwriter" | |
) | |
var usage = `feedst: [options] filename | |
[options]: | |
-c Check. (Default does not check url.) | |
-p Print. (Default behaviour.) | |
` | |
type outline struct { | |
Title string `xml:"title,attr"` | |
URL string `xml:"htmlUrl,attr"` | |
Outline []outline `xml:"outline,omitempty"` | |
} | |
type opml struct { | |
XMLName xml.Name `xml:"opml"` | |
Title string `xml:"head>title"` | |
Outlines []outline `xml:"body>outline"` | |
} | |
func main() { | |
var c, p bool | |
flag.BoolVar(&c, "c", false, "") | |
flag.BoolVar(&p, "p", true, "") | |
flag.Usage = func() { | |
fmt.Fprintf(os.Stdout, "%s", usage) | |
os.Exit(1) | |
} | |
flag.Parse() | |
if flag.NArg() < 1 { | |
flag.Usage() | |
} | |
filename := flag.Arg(0) | |
opml, err := readFile(filename) | |
if err != nil { | |
log.Fatal(err) | |
} | |
extract(opml) | |
} | |
func extract(o *opml) { | |
w := tabwriter.NewWriter(os.Stdout, 40, 8, 0, ' ', 0) | |
var header string | |
categories := make(map[string][]outline) | |
elementsByCategory := make(map[string]int) | |
// Generate header based on category | |
for i, e := range o.Outlines { | |
categories[e.Title] = e.Outline | |
elementsByCategory[e.Title] = len(e.Outline) | |
header = header + fmt.Sprintf("%s", strings.ToUpper(e.Title)) | |
if i < (len(o.Outlines) - 1) { | |
header = header + "\t" | |
} | |
} | |
fmt.Fprintln(w, header) | |
fmt.Println(elementsByCategory) | |
w.Flush() | |
} | |
func readFile(filename string) (*opml, error) { | |
data, err := ioutil.ReadFile(filename) | |
if err != nil { | |
return nil, err | |
} | |
opml := new(opml) | |
err = xml.Unmarshal(data, &opml) | |
if err != nil { | |
return nil, fmt.Errorf(fmt.Sprintf("xml.Decode: %s", err)) | |
} | |
return opml, nil | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment