PageRenderTime 41ms CodeModel.GetById 19ms RepoModel.GetById 1ms app.codeStats 0ms

/plugin/TagHighlight/module/loaddata.py

https://bitbucket.org/smichal88/tag-highlight-git-repo-mirror
Python | 143 lines | 115 code | 12 blank | 16 comment | 37 complexity | 14daa791df5f9d8259f114681827f17f MD5 | raw file
  1. #!/usr/bin/env python
  2. # Tag Highlighter:
  3. # Author: A. S. Budden <abudden _at_ gmail _dot_ com>
  4. # Copyright: Copyright (C) 2009-2013 A. S. Budden
  5. # Permission is hereby granted to use and distribute this code,
  6. # with or without modifications, provided that this copyright
  7. # notice is copied with it. Like anything else that's free,
  8. # the TagHighlight plugin is provided *as is* and comes with no
  9. # warranty of any kind, either expressed or implied. By using
  10. # this plugin, you agree that in no event will the copyright
  11. # holder be liable for any damages resulting from the use
  12. # of this software.
  13. # ---------------------------------------------------------------------
  14. from __future__ import print_function
  15. import os
  16. import glob
  17. import re
  18. try:
  19. from .debug import Debug
  20. except ValueError:
  21. def Debug(text, level):
  22. print(text)
  23. data_directory = None
  24. leadingTabRE = re.compile(r'^\t*')
  25. includeRE = re.compile(r'^%INCLUDE (?P<filename>.*)$')
  26. envRE = re.compile(r'\$\{(?P<envname>[A-Za-z0-9_]+)\}')
  27. def SetLoadDataDirectory(directory):
  28. global data_directory
  29. data_directory = directory
  30. def EntrySplit(entry, pattern):
  31. result = []
  32. parts = entry.strip().split(pattern, 1)
  33. if len(parts) == 1:
  34. result = parts
  35. elif ',' in parts[1]:
  36. result = [parts[0], parts[1].split(',')]
  37. else:
  38. result = parts
  39. return result
  40. def ParseEntries(entries, indent_level=0):
  41. index = 0
  42. while index < len(entries):
  43. line = entries[index].rstrip()
  44. m = leadingTabRE.match(line)
  45. this_indent_level = len(m.group(0))
  46. unindented = line[this_indent_level:]
  47. if len(line.strip()) == 0:
  48. # Empty line
  49. pass
  50. elif line.lstrip()[0] == '#':
  51. # Comment
  52. pass
  53. elif this_indent_level < indent_level:
  54. return {'Index': index, 'Result': result}
  55. elif this_indent_level == indent_level:
  56. if ':' in unindented:
  57. parts = EntrySplit(unindented, ':')
  58. key = parts[0]
  59. try:
  60. result
  61. except NameError:
  62. result = {}
  63. if not isinstance(result, dict):
  64. raise TypeError("Dictionary/List mismatch in '%s'" % key)
  65. if len(parts) > 1:
  66. result[key] = parts[1]
  67. else:
  68. try:
  69. result
  70. except NameError:
  71. result = []
  72. if not isinstance(result, list):
  73. raise TypeError("Dictionary/List mismatch: %r" % result)
  74. result += [unindented]
  75. else:
  76. sublist = entries[index:]
  77. subindent = indent_level+1
  78. parsed = ParseEntries(sublist, subindent)
  79. try:
  80. result
  81. except NameError:
  82. result = {}
  83. if key in result and isinstance(result[key], dict) and isinstance(parsed['Result'], dict):
  84. result[key] = dict(result[key].items() + parsed['Result'].items())
  85. else:
  86. result[key] = parsed['Result']
  87. index += parsed['Index'] - 1
  88. index += 1
  89. try:
  90. result
  91. except NameError:
  92. result = {}
  93. return {'Index': index, 'Result': result}
  94. def LoadFile(filename):
  95. fh = open(filename, 'r')
  96. entries = fh.readlines()
  97. index = 0
  98. while index < len(entries):
  99. m = includeRE.match(entries[index])
  100. if m is not None:
  101. # Include line
  102. inc_file = m.group('filename').strip()
  103. e = envRE.search(inc_file)
  104. try:
  105. while e is not None:
  106. inc_file = inc_file[:e.start()] + \
  107. os.environ[e.group('envname')] + \
  108. inc_file[e.end():]
  109. e = envRE.search(inc_file)
  110. except KeyError:
  111. raise
  112. pass
  113. if os.path.exists(inc_file):
  114. fhinc = open(inc_file, 'r')
  115. extra_entries = fhinc.readlines()
  116. fhinc.close()
  117. entries = entries[:index] + extra_entries + entries[index+1:]
  118. else:
  119. Debug("No such file: '%s'" % inc_file, "Warning")
  120. index += 1
  121. fh.close()
  122. return ParseEntries(entries)['Result']
  123. def LoadDataFile(relative):
  124. filename = os.path.join(data_directory,relative)
  125. return LoadFile(filename)
  126. def GlobData(matcher):
  127. files = glob.glob(os.path.join(data_directory, matcher))
  128. return [os.path.relpath(i,data_directory) for i in files]
  129. if __name__ == "__main__":
  130. import pprint
  131. pprint.pprint(LoadFile('testfile.txt'))