Created
October 8, 2018 11:36
-
-
Save chroju/fd0d22790eff5f31ef606c393c6532a8 to your computer and use it in GitHub Desktop.
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" | |
"flag" | |
"fmt" | |
"io/ioutil" | |
"os" | |
"regexp" | |
"strings" | |
"time" | |
) | |
const OUTDIR = "output" | |
type Note struct { | |
Title string | |
Contents string | |
Updated time.Time | |
} | |
func main() { | |
flag.Parse() | |
args := flag.Args() | |
file, err := os.Open(args[0]) | |
if err != nil { | |
fmt.Println("file error") | |
os.Exit(1) | |
} | |
defer file.Close() | |
sc := bufio.NewScanner(file) | |
if _, err := os.Stat(OUTDIR); err != nil { | |
if err = os.Mkdir(OUTDIR, 0777); err != nil { | |
fmt.Printf("make dir ./%s failed", OUTDIR) | |
os.Exit(1) | |
} | |
} | |
var inContents = false | |
var note Note | |
for sc.Scan() { | |
text := sc.Text() | |
if strings.Contains(text, "<title>") { | |
re := regexp.MustCompile(".+<title>(.+)</title>.+") | |
note.Title = re.ReplaceAllString(text, "$1") + ".txt" | |
} else if strings.Contains(text, "<en-note") { | |
if strings.Contains(text, "</en-note>") { | |
re := regexp.MustCompile(".*<en-note>(.+)</en-note>.*") | |
contents := re.ReplaceAllString(text, "$1") | |
note.Contents = note.Contents + "\n" + contents | |
} else { | |
inContents = true | |
} | |
} else if strings.Contains(text, "</en-note>") { | |
inContents = false | |
} else if inContents { | |
note.Contents = note.Contents + "\n" + text | |
} else if strings.Contains(text, "<updated>") { | |
re := regexp.MustCompile(".+<updated>(.+)</updated>.+") | |
timeString := re.ReplaceAllString(text, "$1") | |
note.Updated, _ = time.Parse("20060102T150405Z", timeString) | |
re = regexp.MustCompile("</?[a-zA-Z]+/?>") | |
note.Contents = re.ReplaceAllString(note.Contents, "") | |
note.Title = strings.Replace(note.Title, "/", "-", -1) | |
path := OUTDIR + "/" + note.Title | |
ioutil.WriteFile(path, []byte(note.Contents+"\n"), 0666) | |
if err := os.Chtimes(path, note.Updated, note.Updated); err != nil { | |
fmt.Printf("write error %s\n", path) | |
} | |
note.Contents = "" | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment