Dotfiles, utilities, and other apparatus.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

94 lines
2.5 KiB

  1. #!/usr/bin/env python3
  2. import os
  3. import re
  4. import sys
  5. import sqlite3
  6. from panflute import *
  7. def resolve_target(target, page):
  8. if re.search('https?://|file:|tel:|mailto:', target):
  9. return target
  10. # At this point, we should be fairly confident the link is a wiki page.
  11. # Normalize it by removing the .html extension that pandoc throws on there:
  12. if target.endswith('.html'):
  13. target = os.path.splitext(target)[0]
  14. # Check for an absolute path (within the wiki):
  15. if target.startswith('/'):
  16. return target.replace('/', '', 1);
  17. page_elements = page.split('/')
  18. # Get rid of the page name:
  19. page_elements.pop()
  20. path_elements = page_elements + target.split('/')
  21. resolved_path = []
  22. while len(path_elements) > 0:
  23. el = path_elements.pop()
  24. if el == '..' and len(path_elements) > 0:
  25. # Discard a directory:
  26. path_elements.pop()
  27. else:
  28. resolved_path.append(el)
  29. resolved_path.reverse()
  30. return '/'.join(resolved_path)
  31. def extract_values(elem, doc):
  32. if isinstance(elem, Link):
  33. link_target = elem.url
  34. # Skip in-page anchors, for now:
  35. if link_target.startswith('#'):
  36. return;
  37. # Insert a row of data
  38. c.execute(
  39. "INSERT OR IGNORE INTO links VALUES (?, ?)",
  40. (
  41. pagename,
  42. resolve_target(link_target, pagename)
  43. )
  44. )
  45. conn.commit()
  46. # Ensure we're in the wiki directory:
  47. notes_dir = os.path.join(os.getenv('HOME'), 'notes')
  48. vimwiki_dir = os.path.join(notes_dir, 'vimwiki')
  49. os.chdir(notes_dir)
  50. conn = sqlite3.connect('metadata.db')
  51. c = conn.cursor()
  52. for input_file in sys.argv[1:]:
  53. # Trim leading dir and .wiki:
  54. # XXX: This is such hacky garbage, jiminy:
  55. pagename = input_file.replace('./vimwiki/', '', 1)
  56. pagename = pagename.replace(vimwiki_dir + '/', '', 1)
  57. pagename = os.path.splitext(pagename)[0]
  58. with open(input_file) as page:
  59. doc = convert_text(
  60. page.read(),
  61. input_format='vimwiki',
  62. standalone=True
  63. )
  64. title = doc.get_metadata('title')
  65. date = doc.get_metadata('date')
  66. # Log the name and metadata of the page:
  67. c.execute("DELETE FROM pages WHERE page = ?", (pagename,))
  68. c.execute("INSERT INTO pages VALUES (?, ?, ?)", (pagename, title, date))
  69. # Clear any links from this page in case something's been deleted:
  70. c.execute("DELETE FROM links WHERE page = ?", (pagename,))
  71. doc.walk(extract_values)
  72. conn.close()