Oleksandr Smirnov
Oleksandr Smirnov
olexsmir@gmail.com remove paragraphs from generated markdown, and log some things, 1 year ago
olexsmir@gmail.com remove paragraphs from generated markdown, and log some things, 1 year ago
| 1 | package main |
| 2 | |
| 3 | import ( |
| 4 | "fmt" |
| 5 | "log/slog" |
| 6 | "os" |
| 7 | "strings" |
| 8 | |
| 9 | "github.com/gomarkdown/markdown" |
| 10 | "github.com/gomarkdown/markdown/html" |
| 11 | mdParser "github.com/gomarkdown/markdown/parser" |
| 12 | "github.com/olexsmir/anpi/anki" |
| 13 | "github.com/olexsmir/anpi/parser" |
| 14 | ) |
| 15 | |
| 16 | const importFile = "import.yml" |
| 17 | |
| 18 | func main() { |
| 19 | if err := run(); err != nil { |
| 20 | fmt.Fprintf(os.Stderr, "error: %v\n", err) |
| 21 | os.Exit(1) |
| 22 | } |
| 23 | } |
| 24 | |
| 25 | func run() error { |
| 26 | anki := anki.NewAnkiClient() |
| 27 | |
| 28 | f, err := os.ReadFile(importFile) |
| 29 | if err != nil { |
| 30 | return err |
| 31 | } |
| 32 | |
| 33 | data, err := parser.Parse(f) |
| 34 | if err != nil { |
| 35 | return err |
| 36 | } |
| 37 | |
| 38 | for _, deck := range data { |
| 39 | for _, note := range deck.Notes { |
| 40 | fields := make(map[string]string) |
| 41 | for k, v := range note.Fields { |
| 42 | fields[deck.FieldLookUp(k)] = fromMarkdown(v) |
| 43 | } |
| 44 | |
| 45 | slog.Info("gotten fields", "fields", fields) |
| 46 | |
| 47 | tags := mergeTags(deck.Tags, note.Tags) |
| 48 | nid, err := anki.AddNote(deck.Deck, deck.Type, fields, tags) |
| 49 | if err != nil { |
| 50 | return err |
| 51 | } |
| 52 | |
| 53 | slog.Info("note added", "id", nid, "fields", fields) |
| 54 | } |
| 55 | } |
| 56 | |
| 57 | return nil |
| 58 | } |
| 59 | |
| 60 | func mergeTags(global, local []string) []string { |
| 61 | unique := make(map[string]struct{}) |
| 62 | |
| 63 | for _, tag := range global { |
| 64 | unique[tag] = struct{}{} |
| 65 | } |
| 66 | for _, tag := range local { |
| 67 | unique[tag] = struct{}{} |
| 68 | } |
| 69 | |
| 70 | result := make([]string, 0, len(unique)) |
| 71 | for tag := range unique { |
| 72 | result = append(result, tag) |
| 73 | } |
| 74 | |
| 75 | return result |
| 76 | } |
| 77 | |
| 78 | func fromMarkdown(inp string) string { |
| 79 | htmlFlags := html.CommonFlags | html.HrefTargetBlank |
| 80 | opts := html.RendererOptions{Flags: htmlFlags} |
| 81 | |
| 82 | p := mdParser.New() |
| 83 | doc := p.Parse([]byte(inp)) |
| 84 | |
| 85 | str := string(markdown.Render(doc, html.NewRenderer(opts))) |
| 86 | str = strings.ReplaceAll(str, "<p>", "") |
| 87 | str = strings.ReplaceAll(str, "</p>", "") |
| 88 | |
| 89 | return str |
| 90 | } |