// SPDX-License-Identifier: AGPL-3.0-or-later package convert import ( "archive/zip" "bytes" "errors" "fmt" "net/url" "path" "regexp" "sort" "strconv" "strings" "time" "unicode/utf8" "gopkg.in/yaml.v3" ) // ---- Markdown folders: plain zips, Obsidian vaults, Bear exports ----------- // // A zip of Markdown files keeps its folders as pages: a folder becomes a page // with its notes under it, or the note named like the folder ("Guides.md" // next to "Guides/", or "Guides/Guides.md") is that page. Links between the // files and to images and other files in the zip are kept, as relative // Markdown links or as Obsidian [[wikilinks]] and ![[embeds]], which are // found by file name anywhere in the archive like Obsidian does. YAML front // matter becomes the page's properties and tags, and #tags in the text are // added to its tags. Bear's TextBundles (a .bear2bk backup, or exported // .textbundle folders) are a note each with their own assets. // ErrNoNotes is returned for an archive without Markdown notes in it. var ErrNoNotes = errors.New("the archive holds no Markdown notes") // VaultKind is what an archive of Markdown looks like it came from. type VaultKind string const ( VaultMarkdown VaultKind = "markdown" VaultObsidian VaultKind = "obsidian" VaultBear VaultKind = "bear" VaultNotion VaultKind = "notion" ) // DetectArchive tells a Notion export from a folder of Markdown files. It // only looks at the names in the zip. func DetectArchive(data []byte) (VaultKind, error) { zr, err := zip.NewReader(bytes.NewReader(data), int64(len(data))) if err != nil { return "", fmt.Errorf("not a zip file: %w", err) } notion, markdown := 0, 0 kind := VaultMarkdown for _, f := range zr.File { name := strings.ReplaceAll(f.Name, "\\", "/") for _, part := range strings.Split(name, "/") { switch { case part == ".obsidian": kind = VaultObsidian case strings.HasSuffix(strings.ToLower(part), ".textbundle"): if kind != VaultObsidian { kind = VaultBear } } } base := path.Base(name) ext := strings.ToLower(path.Ext(base)) if notionID.MatchString(strings.TrimSuffix(base, path.Ext(base))) { notion++ } switch ext { case ".md", ".markdown": markdown++ case ".zip": // Large Notion exports come as zips inside a zip. if strings.HasPrefix(strings.ToLower(base), "export-") { notion++ } } } if notion > 0 && kind == VaultMarkdown && notion*2 >= markdown { return VaultNotion, nil } if markdown == 0 && kind != VaultBear { // HTML pages only: Notion's HTML export is read the same way. return VaultNotion, nil } return kind, nil } // ImportedPage is one page of a multi-page import. Parent is the index of // its parent page in the list, or -1 at the top. Links to other pages of the // import use PageRef as their URL, files AssetRef. Tags are tag names, Props // the front matter values by name (strings, numbers, booleans, dates as // "YYYY-MM-DD", and lists of strings). type ImportedPage = NotionPage type vaultNote struct { file string // the Markdown file in the zip key string // path without extension; for a TextBundle, the bundle without ".textbundle" dir string // where its relative links start title string isDir bool // a folder without a note of its own } type vaultReader struct { *notionReader kind VaultKind root string // a single folder that holds everything, stripped from names byKey map[string]int byName map[string][]int // lower-case file name without extension -> pages fileFor map[string][]string refs []string // targets of the wikilinks of the note being read } // ReadVault reads a zip of Markdown notes (kind from DetectArchive). Pages // come parents first. func ReadVault(data []byte, kind VaultKind) ([]NotionPage, []Asset, error) { v := &vaultReader{ notionReader: ¬ionReader{files: map[string]*zip.File{}, assetAt: map[string]string{}, pageAt: map[string]int{}}, kind: kind, byKey: map[string]int{}, byName: map[string][]int{}, fileFor: map[string][]string{}, } if err := v.open(data, false); err != nil { return nil, nil, err } // Hidden folders (.obsidian, .trash, .git) are not part of the notes. for name := range v.files { for _, part := range strings.Split(name, "/") { if strings.HasPrefix(part, ".") || part == "__MACOSX" { delete(v.files, name) break } } } v.root = commonRoot(v.files) notes := v.findNotes() if len(notes) == 0 { return nil, nil, ErrNoNotes } if len(notes) > maxNotionPages { return nil, nil, fmt.Errorf("the archive has more than %d pages", maxNotionPages) } for i, n := range notes { v.byKey[strings.ToLower(n.key)] = i if n.file != "" { v.pageAt[n.file] = i } if !n.isDir { name := strings.ToLower(path.Base(n.key)) v.byName[name] = append(v.byName[name], i) } } for name := range v.files { base := strings.ToLower(path.Base(name)) v.fileFor[base] = append(v.fileFor[base], name) } for _, list := range v.fileFor { // The shortest path wins, like Obsidian's "shortest path" links. sort.Slice(list, func(i, j int) bool { return len(list[i]) < len(list[j]) || len(list[i]) == len(list[j]) && list[i] < list[j] }) } pages := make([]NotionPage, len(notes)) for i, n := range notes { parent := -1 for dir := path.Dir(n.key); dir != "." && dir != "/" && dir != ""; dir = path.Dir(dir) { if p, ok := v.byKey[strings.ToLower(dir)]; ok && p != i { parent = p break } } page := NotionPage{Title: n.title, Parent: parent, Doc: Node{Type: "doc", Content: []Node{{Type: "paragraph"}}}} if n.file != "" { var err error if page, err = v.readNote(n, parent); err != nil { return nil, nil, fmt.Errorf("%s: %w", v.shown(n.file), err) } } if v.err != nil { return nil, nil, v.err } pages[i] = page } return pages, v.assets, nil } // shown is a file's name as the user knows it (with the archive's root folder). func (v *vaultReader) shown(name string) string { return path.Join(v.root, name) } // commonRoot is the one folder every file is in ("" when there is none), and // takes it off the names: zipping a vault folder puts it around everything. func commonRoot(files map[string]*zip.File) string { root := "" for name := range files { first, _, ok := strings.Cut(name, "/") if !ok || (root != "" && first != root) || strings.HasSuffix(strings.ToLower(first), ".textbundle") { return "" } root = first } if root == "" { return "" } moved := make(map[string]*zip.File, len(files)) for name, f := range files { moved[strings.TrimPrefix(name, root+"/")] = f } for name := range files { delete(files, name) } for name, f := range moved { files[name] = f } return root } // findNotes lists the pages: notes, TextBundles, and folders, sorted so that // parents come first. func (v *vaultReader) findNotes() []vaultNote { var notes []vaultNote seen := map[string]bool{} bundles := map[string]bool{} for name := range v.files { // A TextBundle is a folder "Name.textbundle" with text.md (or // .markdown, .txt) and an assets folder. dir, base := path.Split(name) dir = strings.TrimSuffix(dir, "/") if strings.HasSuffix(strings.ToLower(dir), ".textbundle") && strings.HasPrefix(strings.ToLower(base), "text.") { if bundles[dir] { continue } bundles[dir] = true key := dir[:len(dir)-len(".textbundle")] notes = append(notes, vaultNote{file: name, key: key, dir: dir, title: path.Base(key)}) seen[strings.ToLower(key)] = true } } docwellExport := v.files["index.md"] != nil && hasPrefixFile(v.files, "_files/") for name := range v.files { lower := strings.ToLower(name) ext := path.Ext(lower) if ext != ".md" && ext != ".markdown" && ext != ".txt" { continue } if strings.Contains(lower, ".textbundle/") || strings.HasSuffix(lower, ".excalidraw.md") { continue } if docwellExport && (name == "index.md" || strings.HasPrefix(name, "_files/")) { continue // Docwell's own space export: its index and files are not pages. } if ext == ".txt" && v.kind != VaultBear { continue // Plain text files in a vault are attachments. } key := strings.TrimSuffix(name, path.Ext(name)) if seen[strings.ToLower(key)] { continue } seen[strings.ToLower(key)] = true notes = append(notes, vaultNote{file: name, key: key, dir: path.Dir(name), title: path.Base(key)}) } // Folders that hold notes are pages, unless a note stands for them: // "Guides.md" next to "Guides/", or "Guides/Guides.md". dirs := map[string]bool{} for _, n := range notes { for d := path.Dir(n.key); d != "." && d != ""; d = path.Dir(d) { dirs[d] = true } } for d := range dirs { if seen[strings.ToLower(d)] { continue } inner := strings.ToLower(d + "/" + path.Base(d)) folderNote := -1 for i, n := range notes { if strings.ToLower(n.key) == inner { folderNote = i } } if folderNote >= 0 { // The note moves up to be the folder's page. notes[folderNote].key = d seen[strings.ToLower(d)] = true continue } seen[strings.ToLower(d)] = true notes = append(notes, vaultNote{key: d, title: path.Base(d), isDir: true}) } sort.Slice(notes, func(i, j int) bool { di, dj := strings.Count(notes[i].key, "/"), strings.Count(notes[j].key, "/") if di != dj { return di < dj } return strings.ToLower(notes[i].key) < strings.ToLower(notes[j].key) }) return notes } func hasPrefixFile(files map[string]*zip.File, prefix string) bool { for name := range files { if strings.HasPrefix(name, prefix) { return true } } return false } func (v *vaultReader) readNote(n vaultNote, parent int) (NotionPage, error) { data, err := v.read(v.files[n.file]) if err != nil { return NotionPage{}, err } data = bytes.TrimPrefix(data, []byte(utf8BOM)) if !utf8.Valid(data) { return NotionPage{}, errors.New("is not UTF-8 text") } text := strings.ReplaceAll(string(data), "\r\n", "\n") meta, body := frontMatter(text) v.refs = nil md, inlineTags := v.prepare(body) doc, err := FromMarkdownWith(md, ImportOptions{Resolve: func(u string) (string, bool) { return v.resolve(n.dir, u) }}) if err != nil { return NotionPage{}, err } title := n.title if h1, rest := Title(doc); h1 != "" { // Obsidian names a note by its file; Bear and most Markdown by the // first heading. A heading that repeats the file name goes either way. if v.kind != VaultObsidian || strings.EqualFold(strings.TrimSpace(h1), n.title) { title, doc = strings.TrimSpace(h1), rest } } if len(doc.Content) == 0 { doc.Content = []Node{{Type: "paragraph"}} } page := NotionPage{Title: title, Parent: parent, Doc: doc} tags, props := splitMeta(meta) if t, ok := props["title"].(string); ok && strings.TrimSpace(t) != "" { page.Title = strings.TrimSpace(t) delete(props, "title") } page.Tags = uniqueFold(append(tags, inlineTags...)) if len(props) > 0 { page.Props = props } return page, nil } // frontMatter splits YAML front matter ("---" lines around it, at the very // start) off a note. Front matter that is not a YAML map is left in the text. func frontMatter(text string) (map[string]any, string) { lines := strings.Split(text, "\n") if len(lines) < 2 || strings.TrimRight(lines[0], " \t") != "---" { return nil, text } for j := 1; j < len(lines); j++ { if l := strings.TrimRight(lines[j], " \t"); l != "---" && l != "..." { continue } var meta map[string]any if err := yaml.Unmarshal([]byte(strings.Join(lines[1:j], "\n")), &meta); err != nil { return nil, text } return meta, strings.Join(lines[j+1:], "\n") } return nil, text } // splitMeta turns front matter into tag names and property values. func splitMeta(meta map[string]any) ([]string, map[string]any) { var tags []string props := map[string]any{} keys := make([]string, 0, len(meta)) for k := range meta { keys = append(keys, k) } sort.Strings(keys) for _, k := range keys { val := meta[k] switch strings.ToLower(strings.TrimSpace(k)) { case "tags", "tag": for _, t := range metaList(val, true) { if t = strings.TrimPrefix(strings.TrimSpace(t), "#"); t != "" { tags = append(tags, t) } } continue case "aliases", "alias", "cssclass", "cssclasses", "position": continue } if v, ok := metaValue(val); ok { props[strings.TrimSpace(k)] = v } } return tags, props } var isoDateTime = regexp.MustCompile(`^\d{4}-\d{2}-\d{2}(?:[T ][0-9:.]+(?:Z|[+-]\d{2}:?\d{2})?)?$`) // metaValue is a front matter value as an import keeps it: a string, // float64, bool, a date ("YYYY-MM-DD"), or a list of strings. func metaValue(v any) (any, bool) { switch x := v.(type) { case nil: return nil, false case string: s := strings.TrimSpace(x) if s == "" { return nil, false } if isoDateTime.MatchString(s) { return s[:10], true } return s, true case bool: return x, true case int: return float64(x), true case int64: return float64(x), true case uint64: return float64(x), true case float64: return x, true case time.Time: return x.Format(time.DateOnly), true case []any: list := metaList(x, false) if len(list) == 0 { return nil, false } return list, true } return nil, false // Maps and other shapes have no property type. } // metaList reads a list of scalars; split also splits a single string at // commas and spaces (how tags are often written). func metaList(v any, split bool) []string { var out []string switch x := v.(type) { case string: if !split { return []string{x} } out = append(out, strings.FieldsFunc(x, func(r rune) bool { return r == ',' || r == ' ' })...) case []any: for _, item := range x { switch s := item.(type) { case string: if s = strings.TrimSpace(s); s != "" { out = append(out, s) } case int, int64, float64, bool: out = append(out, fmt.Sprint(s)) } } } return out } func uniqueFold(list []string) []string { var out []string seen := map[string]bool{} for _, s := range list { if s = strings.TrimSpace(s); s == "" || seen[strings.ToLower(s)] { continue } seen[strings.ToLower(s)] = true out = append(out, s) } return out } var ( wikilink = regexp.MustCompile(`(!?)\[\[([^\[\]\n|]+?)(?:\|([^\[\]\n]*))?\]\]`) obsidianNote = regexp.MustCompile(`(?s)%%.*?%%`) blockID = regexp.MustCompile(`\s\^[A-Za-z0-9-]+$`) inlineTag = regexp.MustCompile(`(?:^|\s)#([\p{L}\p{N}_][\p{L}\p{N}_/-]*)`) bearLongTag = regexp.MustCompile(`(?:^|\s)#([\p{L}\p{N}_][^#\n]*?[^\s#])#(?:$|[\s.,;:!?)])`) highlightMark = regexp.MustCompile(`==([^=\n]+)==`) calloutLine = regexp.MustCompile(`^(\s*>\s*)\[!([A-Za-z-]+)\][+-]?\s*(.*)$`) fence = regexp.MustCompile("^\\s{0,3}(`{3,}|~{3,})") sizeOnly = regexp.MustCompile(`^\d+(?:x\d+)?$`) ) // prepare rewrites what Markdown readers do not know: wikilinks and embeds // (to links whose target is "dwref:N", an entry of v.refs), Obsidian // callouts and comments, highlights and block ids. It also collects #tags. // Code blocks and inline code are left alone. func (v *vaultReader) prepare(md string) (string, []string) { md = obsidianNote.ReplaceAllString(md, "") var tags []string var out []string open := "" for _, line := range strings.Split(md, "\n") { if open != "" { if m := fence.FindStringSubmatch(line); m != nil && m[1][0] == open[0] && len(m[1]) >= len(open) && strings.TrimSpace(line[len(m[0]):]) == "" { open = "" } out = append(out, line) continue } if m := fence.FindStringSubmatch(line); m != nil { open = m[1] out = append(out, line) continue } if m := calloutLine.FindStringSubmatch(line); m != nil { out = append(out, m[1]+"[!"+calloutKind(m[2])+"]") if title := strings.TrimSpace(m[3]); title != "" { // The title is a paragraph of its own above the callout's text. out = append(out, m[1]+"**"+title+"**") line = strings.TrimRight(m[1], " ") } else { continue } } line = blockID.ReplaceAllString(line, "") line = outsideCode(line, func(s string) string { scan := s if v.kind == VaultBear { for _, m := range bearLongTag.FindAllStringSubmatch(s, -1) { tags = append(tags, m[1]) } scan = bearLongTag.ReplaceAllString(s, " ") } for _, m := range inlineTag.FindAllStringSubmatch(scan, -1) { if !onlyDigits(m[1]) { tags = append(tags, strings.TrimRight(m[1], "/-")) } } s = highlightMark.ReplaceAllString(s, "$1") return wikilink.ReplaceAllStringFunc(s, v.wikilink) }) out = append(out, line) } return strings.Join(out, "\n"), tags } func onlyDigits(s string) bool { for _, r := range s { if r < '0' || r > '9' { return false } } return true } // calloutKind maps an Obsidian callout type to the GitHub alert it reads as. func calloutKind(t string) string { switch strings.ToLower(t) { case "tip", "hint", "success", "check", "done": return "TIP" case "important", "question", "help", "faq", "example", "quote", "cite": return "IMPORTANT" case "warning", "caution", "attention": return "WARNING" case "failure", "fail", "missing", "danger", "error", "bug": return "CAUTION" } return "NOTE" } // outsideCode applies fn to the parts of a line that are not inline code. func outsideCode(line string, fn func(string) string) string { var b strings.Builder i := 0 for { j := strings.IndexByte(line[i:], '`') if j < 0 { b.WriteString(fn(line[i:])) return b.String() } j += i b.WriteString(fn(line[i:j])) n := j for n < len(line) && line[n] == '`' { n++ } ticks := line[j:n] end := strings.Index(line[n:], ticks) if end < 0 { b.WriteString(line[j:]) return b.String() } b.WriteString(line[j : n+end+len(ticks)]) i = n + end + len(ticks) } } var linkTextEscape = strings.NewReplacer(`\`, `\\`, "`", "\\`", "*", `\*`, "_", `\_`, "[", `\[`, "]", `\]`, "<", `\<`, ">", `\>`, "#", `\#`, "!", `\!`, "|", `\|`, "~", `\~`) // wikilink rewrites one [[target|alias]] or ![[embed]] as a Markdown link. func (v *vaultReader) wikilink(m string) string { parts := wikilink.FindStringSubmatch(m) embed, target, alias := parts[1] == "!", strings.TrimSuffix(strings.TrimSpace(parts[2]), `\`), strings.TrimSpace(parts[3]) if target == "" { return m } ref := "dwref:" + strconv.Itoa(len(v.refs)) v.refs = append(v.refs, target) name, heading, _ := strings.Cut(target, "#") name = strings.TrimSpace(name) text := alias if text == "" || (embed && sizeOnly.MatchString(text)) { text = path.Base(name) if heading = strings.TrimPrefix(strings.TrimSpace(heading), "^"); heading != "" && !embed { if name == "" { text = heading } else { text = path.Base(name) + " > " + heading } } } if text == "" { text = target } if embed && isImageName(name) { return "![" + linkTextEscape.Replace(text) + "](" + ref + ")" } return "[" + linkTextEscape.Replace(text) + "](" + ref + ")" } func isImageName(name string) bool { switch strings.ToLower(path.Ext(name)) { case ".png", ".jpg", ".jpeg", ".gif", ".webp", ".svg", ".bmp", ".avif": return true } return false } // resolve maps a link or image URL in a note whose links start at dir. func (v *vaultReader) resolve(dir, raw string) (string, bool) { raw = strings.TrimSpace(raw) if rest, ok := strings.CutPrefix(raw, "dwref:"); ok { n, err := strconv.Atoi(rest) if err != nil || n >= len(v.refs) { return "", true } return v.target(dir, v.refs[n]), true } u, err := url.Parse(raw) if err != nil { return "", true } if u.Scheme != "" || u.Host != "" { return "", false // The usual check decides about outside links. } if u.Path == "" { return "", false // An anchor in the same note. } if out := v.target(dir, u.Path); out != "" { return out, true } return "", true // A file the archive left out. } // target finds a note or file by a link's path: next to the note, from the // archive's root, or failing those by its name alone (like Obsidian). func (v *vaultReader) target(dir, target string) string { name, _, _ := strings.Cut(target, "#") name = strings.TrimSpace(strings.ReplaceAll(name, "\\", "/")) if name == "" { return "" } ext := strings.ToLower(path.Ext(name)) isNote := ext == "" || ext == ".md" || ext == ".markdown" || (ext == ".txt" && v.kind == VaultBear) if !isNote && !v.isFile(dir, name) && v.isNoteName(dir, name) { isNote = true // "[[Meeting 2026.11.16]]": a dot in a note's name. } if isNote { key := name if ext == ".md" || ext == ".markdown" || ext == ".txt" { key = strings.TrimSuffix(name, path.Ext(name)) } for _, k := range []string{path.Join(dir, key), strings.TrimPrefix(path.Clean("/"+key), "/")} { if i, ok := v.byKey[strings.ToLower(k)]; ok { return PageRef(i) } } if list := v.byName[strings.ToLower(path.Base(key))]; len(list) > 0 { return PageRef(list[0]) } return "" } for _, p := range []string{path.Join(dir, name), strings.TrimPrefix(path.Clean("/"+name), "/")} { if _, ok := v.files[p]; ok { return v.asset(p) } } if list := v.fileFor[strings.ToLower(path.Base(name))]; len(list) > 0 { return v.asset(list[0]) } return "" } func (v *vaultReader) isFile(dir, name string) bool { if _, ok := v.files[path.Join(dir, name)]; ok { return true } return len(v.fileFor[strings.ToLower(path.Base(name))]) > 0 } func (v *vaultReader) isNoteName(dir, name string) bool { if _, ok := v.byKey[strings.ToLower(path.Join(dir, name))]; ok { return true } return len(v.byName[strings.ToLower(path.Base(name))]) > 0 } // asset is the placeholder of a file in the archive, read on first use. func (v *vaultReader) asset(p string) string { if ref, ok := v.assetAt[p]; ok { return ref } if i, ok := v.pageAt[p]; ok { return PageRef(i) } data, err := v.read(v.files[p]) if err != nil { if v.err == nil { v.err = fmt.Errorf("%s: %w", v.shown(p), err) } return "" } ref := AssetRef(len(v.assets)) v.assets = append(v.assets, Asset{Ref: ref, Name: path.Base(p), Data: data}) v.assetAt[p] = ref return ref }