meta.py 3.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  1. """
  2. Copyright (c) 2015, Waylan Limberg
  3. All rights reserved.
  4. Redistribution and use in source and binary forms, with or without modification,
  5. are permitted provided that the following conditions are met:
  6. 1. Redistributions of source code must retain the above copyright notice, this
  7. list of conditions and the following disclaimer.
  8. 2. Redistributions in binary form must reproduce the above copyright notice, this
  9. list of conditions and the following disclaimer in the documentation and/or other
  10. materials provided with the distribution.
  11. 3. Neither the name of the copyright holder nor the names of its contributors may
  12. be used to endorse or promote products derived from this software without
  13. specific prior written permission.
  14. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
  15. ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
  16. WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
  17. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
  18. INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
  19. BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  20. DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
  21. LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
  22. OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
  23. OF THE POSSIBILITY OF SUCH DAMAGE.
  24. MultiMarkdown Meta-Data
  25. Extracts, parses and transforms MultiMarkdown style data from documents.
  26. """
  27. import re
  28. import yaml
  29. try:
  30. from yaml import CSafeLoader as SafeLoader
  31. except ImportError: # pragma: no cover
  32. from yaml import SafeLoader
  33. #####################################################################
  34. # Data Parser #
  35. #####################################################################
  36. YAML_RE = re.compile(r'^-{3}[ \t]*\n(.*?\n)(?:\.{3}|-{3})[ \t]*\n', re.UNICODE | re.DOTALL)
  37. META_RE = re.compile(r'^[ ]{0,3}(?P<key>[A-Za-z0-9_-]+):\s*(?P<value>.*)')
  38. META_MORE_RE = re.compile(r'^([ ]{4}|\t)(\s*)(?P<value>.*)')
  39. def get_data(doc):
  40. """
  41. Extract meta-data from a text document.
  42. Returns a tuple of document and a data dict.
  43. """
  44. data = {}
  45. # First try YAML
  46. m = YAML_RE.match(doc)
  47. if m:
  48. try:
  49. data = yaml.load(m.group(1), SafeLoader)
  50. if isinstance(data, dict):
  51. doc = doc[m.end():].lstrip('\n')
  52. else:
  53. data = {}
  54. except Exception:
  55. pass
  56. return doc, data
  57. # No YAML deliminators. Try MultiMarkdown style
  58. lines = doc.replace('\r\n', '\n').replace('\r', '\n').split('\n')
  59. key = None
  60. while lines:
  61. line = lines.pop(0)
  62. if line.strip() == '':
  63. break # blank line - done
  64. m1 = META_RE.match(line)
  65. if m1:
  66. key = m1.group('key').lower().strip()
  67. value = m1.group('value').strip()
  68. if key in data:
  69. data[key] += ' {}'.format(value)
  70. else:
  71. data[key] = value
  72. else:
  73. m2 = META_MORE_RE.match(line)
  74. if m2 and key:
  75. # Add another line to existing key
  76. data[key] += ' {}'.format(m2.group('value').strip())
  77. else:
  78. lines.insert(0, line)
  79. break # no meta data - done
  80. return '\n'.join(lines).lstrip('\n'), data