]> git.phdru.name Git - bookmarks_db.git/blobdiff - db2bkmk.py
Minor refactoring
[bookmarks_db.git] / db2bkmk.py
index cc2bb82eec1eb73a116feab6c0b27080ac211bea..a9e0fd455aa73acb36589ef1afc7a0a2d740ef63 100755 (executable)
-#! /usr/local/bin/python -O
-"""
-   Convert FLAD database back to bookmarks.html suitable for Netscape Navigator
+#! /usr/bin/env python
+"""Convert a bkmk database back to bookmarks.html (or other format defined by writer)
 
-   Written by BroytMann, Jun 1997 - Mar 1999. Copyright (C) 1997-1999 PhiloSoft Design
+This file is a part of Bookmarks database and Internet robot.
 """
 
-import sys, os, string, shutil
-from getopt import getopt
-
-import fladm
-
-
-def write(str):
-   if private_level == 0: # Put in public all except private folder
-      public_html.write(str)
-   private_html.write(str)
-
-
-def unindent(old_level, new_level):
-   while old_level > new_level:
-      old_level = old_level - 1
-      write("    "*old_level + "</DL><p>\n")
-
-
-def gen_html(bookmarks_db, show_pbar, report_stats):
-   global pbar, record_no, urls_no, public_html, private_html, private_level
-
-   shutil.copy("header", "public.html")
-   shutil.copy("header", "private.html")
-
-   public_html = open("public.html", 'a')
-   private_html = open("private.html", 'a')
-
-   record_no = 0
-   urls_no = 0
-
-   save_level = 0
-   got_folder = 1 # Start as if we already have one folder
-   private_level = 0
-
-   for record in bookmarks_db:
-      record_no = record_no + 1
-
-      if show_pbar:
-         pbar.display(record_no)
-
-      level = string.atoi(record["Level"])
-
-      if level == save_level:
-         pass
-      elif level == save_level + 1:
-         if got_folder:
-            write("    "*(level - 1) + "<DL><p>\n")
-         else:
-            raise ValueError, "indent without folder"
-      elif level <= save_level - 1:
-         unindent(save_level, level)
-      else:
-         raise ValueError, "new level (%d) too big; must be %d - %d" % (level, save_level-1, save_level+1)
-
-      save_level = level
-      got_folder = record.has_key("Folder") # Test here to save got_folder for next loop
-
-      if private_level == save_level:
-         private_level = 0 # We've returned to saved private level - private folder is over
-
-      if record.has_key("URL"):
-         write("    "*level + '<DT><A HREF="%s" ADD_DATE="%s" LAST_VISIT="%s" LAST_MODIFIED="%s">%s</A>\n' % (record["URL"], record["AddDate"], record["LastVisit"], record["LastModified"], record["Title"]))
-         urls_no = urls_no + 1
-
-      elif record.has_key("Folder"):
-         # Dirty hacks here
-         if (record["Folder"] == "Private links") and (private_level == 0):
-            private_level = save_level # We found private folder - save its level
-
-         if record["Folder"] == "All the rest - Unclassified":
-            write("    "*level + '<DT><H3 NEWITEMHEADER ADD_DATE="%s">%s</H3>\n' % (record["AddDate"], record["Folder"]))
-         else:
-            write("    "*level + '<DT><H3 ADD_DATE="%s">%s</H3>\n' % (record["AddDate"], record["Folder"]))
-
-      elif record.has_key("Ruler"):
-         write("    "*level + "<HR>\n")
-
-      else:
-         raise KeyError, "neither \"URL\" nor \"Folder\" nor \"Ruler\" in record " + str(record)
-
-      if record.has_key("Comment") and (record["Comment"] <> ''):
-         write("<DD>%s\n" % string.join(string.split(record["Comment"], "<BR>"), "<BR>\n"))
+__author__ = "Oleg Broytman <phd@phdru.name>"
+__copyright__ = "Copyright (C) 2000-2012 PhiloSoft Design"
+__license__ = "GNU GPL"
 
-
-   if save_level >= 0:
-      unindent(save_level, 0)
-   else:
-      raise ValueError, "new level (%d) too little - must be >= 0" % save_level
-
-   public_html.close()
-   private_html.close()
-
-   if show_pbar:
-      del pbar
-
-   if report_stats:
-      print "Ok"
-
-
-def translate(bookmarks_db, transldb_name, transl, show_pbar, report_stats):
-   global pbar, record_no, urls_no, public_html, private_html, private_level
-
-   new_ext = str(transl)
-   os.rename("public.html", "public." + new_ext)
-   os.rename("private.html", "private." + new_ext)
-
-   transl_d = {}
-   transl_db = fladm.load_from_file(transldb_name, fladm.check_record, ["URL1", "URL2"], [""])
-                                     # This prevents any other key to appear in transl.db ^
-
-   # Generate translation dictionary (hash table)
-   if transl == 1:
-      for record in transl_db:
-         transl_d[record["URL1"]] = record["URL2"]
-   elif transl == 2:
-      for record in transl_db:
-         transl_d[record["URL2"]] = record["URL1"]
-   else:
-      raise ValueError, "transl (%d) must be 1 or 2" % transl
-
-   del transl_db # Save few bytes of memory
-   transl_k = transl_d.keys()
-
-   # Translate URLs
-   for record in bookmarks_db:
-      if record.has_key("URL") and (record["URL"] in transl_k):
-         record["URL"] = transl_d[record["URL"]]
-
-   gen_html(bookmarks_db, show_pbar, report_stats)
-
-   new_ext = str(3 - transl) # Translate 1 to 2, or 2 to 1
-   os.rename("public.html", "public." + new_ext)
-   os.rename("private.html", "private." + new_ext)
+import sys
 
 
 def run():
-   global pbar, record_no, urls_no, public_html, private_html, private_level
-
-   optlist, args = getopt(sys.argv[1:], "ist:r")
+   from getopt import getopt
+   optlist, args = getopt(sys.argv[1:], "sp:o:t:r")
 
-   show_pbar = 1
    report_stats = 1
+   prune = None
+
+   from writers import writer
+   output_filename = writer.filename
 
-   transldb_name = "" # dictionary translation; default is no translation
    transl = 0
+   transl_name = "" # dictionary translation; default is no translation
 
    for _opt, _arg in optlist:
-      if _opt == '-i':
-         show_pbar = 0
       if _opt == '-s':
          report_stats = 0
+      if _opt == '-p':
+         prune = _arg
+      if _opt == '-o':
+         output_filename = _arg
       if _opt == '-t':
-         transldb_name = _arg
          transl = 1
+         transl_name = _arg
       if _opt == '-r':
          transl = 2
    try:
@@ -168,52 +43,65 @@ def run():
 
    if args:
       sys.stderr.write("db2bkmk: too many arguments\n")
+      sys.stderr.write("Usage: db2bkmk [-s] [-p prune_folder] [-o filename] [-t trans] [-r]\n")
       sys.exit(1)
 
-   if show_pbar:
-      show_pbar = sys.stderr.isatty()
-
-   if show_pbar:
-      try:
-         from tty_pbar import ttyProgressBar
-      except ImportError:
-         show_pbar = 0
+   from storage import storage
+   storage = storage()
 
    if report_stats:
-      sys.stdout.write("Loading: ")
+      sys.stdout.write("Loading %s: " % storage.filename)
       sys.stdout.flush()
 
-   bookmarks_db = fladm.load_from_file("bookmarks.db", fladm.check_record, ["Level"])
+   root_folder = storage.load()
 
    if report_stats:
       print "Ok"
-      sys.stdout.write("Converting FLAD database to bookmarks.html: ")
+      sys.stdout.write("Writing %s: " % output_filename)
       sys.stdout.flush()
 
-   if show_pbar:
-      pbar = ttyProgressBar(0, len(bookmarks_db))
-
-   gen_html(bookmarks_db, show_pbar, report_stats)
 
    if transl:
-      if report_stats:
-         sys.stdout.write("Translating: ")
-         sys.stdout.flush()
+      new_ext = str(transl)
+      transl_d = {}
+
+      from m_lib.flad import fladm
+      transl_db = fladm.load_from_file(transl_name, fladm.check_record, ["URL1", "URL2"], [""])
+                                      # This prevents any other key to appear in transl_db ^
+
+      # Generate translation dictionary (hash table)
+      if transl == 1:
+         for record in transl_db:
+            transl_d[record["URL1"]] = record["URL2"]
+      elif transl == 2:
+         for record in transl_db:
+            transl_d[record["URL2"]] = record["URL1"]
+      else:
+         raise ValueError, "transl (%d) must be 1 or 2" % transl
 
-      if report_stats and show_pbar: # Display bar only without "-i";
-                                       # with "-s" skip it (one bar already
-                                       # displayed, and it is enough)
-         pbar = ttyProgressBar(0, len(bookmarks_db))
+      del transl_db # Save few bytes of memory
 
-      else:
-         show_pbar = 0
+      from bkmk_objects import Walker
+      class Transl(Walker):
+         def __init__(self, transl_d):
+            self.transl_d = transl_d
+
+         def bookmark(self, b, level):
+            href = b.href
+            transl_d = self.transl_d
 
-      translate(bookmarks_db, transldb_name, transl, show_pbar, report_stats)
+            if transl_d.has_key(href):
+               b.href = transl_d[href]
 
+      root_folder.walk_depth(Transl(transl_d))
+
+
+   outfile = open(output_filename, 'w')
+   root_folder.walk_depth(writer(outfile, prune))
+   outfile.close()
 
    if report_stats:
-      print record_no, "records proceed"
-      print urls_no, "urls created"
+      print "Ok"
 
 
 if __name__ == '__main__':