bkmrk_sort.py 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. #!/usr/bin/env python3
  2. import sys
  3. import copy
  4. import re
  5. import json
  6. SEPARATOR = "->"
  7. def loadConfig(configFile):
  8. config = ""
  9. for line in open(configFile):
  10. if line[0:2] != "//":
  11. config += line
  12. print(config)
  13. config = json.loads(config)
  14. for key, value in config.items():
  15. config[key] = value.split(SEPARATOR)
  16. return config
  17. def traverse(bookmrk, paths=[]):
  18. for i in bookmrk:
  19. if i['type'] == 'folder':
  20. paths.append(i['name'])
  21. for j in traverse(i['children'], paths):
  22. yield j
  23. del paths[-1]
  24. elif i['type'] == 'url':
  25. yield paths, i
  26. def move(bookmrks, name, src, dest):
  27. def getId(lst, name):
  28. for i in lst:
  29. if i['name'] == name:
  30. return lst.index(i)
  31. raise NameError('Folder is not exist')
  32. def get(lst, path):
  33. while len(path):
  34. lst = lst[getId(lst, path[0])]['children']
  35. del path[0]
  36. return lst
  37. # Must use a deepcopy here -- we don't want to change "configure"
  38. source = get(bookmrks, copy.deepcopy(src))
  39. dest = get(bookmrks, copy.deepcopy(dest))
  40. bookmrk = source[getId(source, name)]
  41. dest.append(bookmrk)
  42. del source[getId(source, name)]
  43. def keywordCheck(configure, name):
  44. for keyword in configure.keys():
  45. if re.search(keyword, name):
  46. return configure[keyword]
  47. return False
  48. bookmrk = json.loads(open("Bookmarks").read())
  49. configure = loadConfig("keywords.conf")
  50. # If we traverse & modify the bookmark at the same time,
  51. # we will get in many troubles. Use a copy to solve it.
  52. bookmrkNew = copy.deepcopy(bookmrk)
  53. for path, web in traverse(bookmrk['roots']['bookmark_bar']['children']):
  54. # Must use a deepcopy here, if we forget to do that,
  55. # we will change path -> get(path) -> traverse(paths).
  56. path = copy.deepcopy(path)
  57. name = web['name']
  58. dest = keywordCheck(configure, name)
  59. if dest:
  60. try:
  61. move(bookmrkNew['roots']['bookmark_bar']['children'],
  62. name, path, dest)
  63. except (TypeError, NameError):
  64. print('Warning: "%s" is not exist, skipped!' % dest,
  65. file=sys.stderr)
  66. bookmrkNew['checksum'] = ("Edited by chrome bookmrk sorter. "
  67. "Chrome, please fix your checksum!")
  68. print(json.dumps(bookmrkNew))