Conghao97's picture tcftrees's picture
ProgramGen release
d086025
Raw History Blame Contribute Delete
16.7 kB
diff --git a/src/ppf/jabref/__init__.py b/src/ppf/jabref/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..6641c03c774d6a295cc7d6d18b28f0137e33f1fe
--- /dev/null
+++ b/src/ppf/jabref/__init__.py
@@ -0,0 +1,17 @@
+"""
+ppf.jabref
+++++++
+
+"""
+try:
+ from importlib_metadata import version
+except ImportError: # pragma: no cover
+ from importlib.metadata import version # pragma: no cover
+
+# import every function, class, etc. that should be visible in the package
+from .jabref import *
+
+__version__ = version(__name__)
+
+del jabref
+del utils
diff --git a/src/ppf/jabref/jabref.py b/src/ppf/jabref/jabref.py
new file mode 100644
index 0000000000000000000000000000000000000000..76a6bf25ef61a9a36d21d12cccfac55541d99b13
--- /dev/null
+++ b/src/ppf/jabref/jabref.py
@@ -0,0 +1,202 @@
+#!/usr/bin/env python3
+# -*- coding: utf-8 -*-
+"""
+Tools to work with JabRef database.
+"""
+
+from sqlalchemy import Column, ForeignKey
+from sqlalchemy import Integer, VARCHAR, Text
+from sqlalchemy.orm import relationship
+from sqlalchemy.orm.collections import attribute_mapped_collection
+from sqlalchemy.orm import declarative_base
+from sqlalchemy.ext.associationproxy import association_proxy
+import re
+from .utils import export
+
+
+Base = declarative_base()
+
+
+@export
+def citationkey2counter(citationkey):
+ """
+ 'a': 0, 'b': 1, ..., 'z': 25
+ 'aa': 26, 'ab': 27
+ 'aaa': 26 + 26**2 + 0, 'aab': 26 + 26**2 + 1
+ """
+
+ # Let n = len(citationkey).
+ # Then first count all keys used by keys of length <n:
+ counter = 0
+ for i in range(1, len(citationkey)):
+ counter += 26**i
+
+ # Then, add position of citationkey within keys of length n:
+ for i, c in enumerate(citationkey[::-1]):
+ digit = ord(c) - ord('a')
+ counter += digit * 26 ** i
+
+ return counter
+
+
+@export
+def counter2citationkey(counter):
+ """
+ 'a': 0, 'b': 1, ..., 'z': 25
+ 'aa': 26, 'ab': 27
+ 'aaa': 26 + 26**2 + 0, 'aab': 26 + 26**2 + 1
+ """
+
+ n = 1
+ while True:
+ if counter < 26 ** n:
+ break
+
+ counter -= 26 ** n
+ n += 1
+
+ citationkey = ['z'] * n
+ for i in range(n)[::-1]:
+ digit = counter // 26 ** i
+ counter = counter % 26 ** i
+ citationkey[-i - 1] = chr(digit + ord('a'))
+
+ return ''.join(citationkey)
+
+
+@export
+class Entry(Base):
+ """Represent a JabRef Entry."""
+
+ __tablename__ = 'ENTRY'
+
+ shared_id = Column('SHARED_ID', Integer, primary_key=True)
+ type = Column(VARCHAR(255), nullable=False)
+ version = Column(Integer, nullable=True)
+ _fields = relationship(
+ 'Field',
+ collection_class=attribute_mapped_collection('name'))
+
+ # Access like entry.fields['author'] returns 'A. Muller'
+ # which is nicer than using enttry.fields['author'].value:
+ fields = association_proxy('_fields', 'value')
+
+
+@export
+class Field(Base):
+ """Represent a JabRef Field."""
+
+ __tablename__ = 'FIELD'
+
+ entry_shared_id = Column(Integer, ForeignKey('ENTRY.SHARED_ID'),
+ primary_key=True)
+ name = Column(VARCHAR(255), primary_key=True)
+ value = Column(Text, nullable=True)
+
+
+@export
+def split_by_unescaped_sep(text, sep=':'):
+ """Split string at sep but only if not escaped."""
+ def remerge(s):
+ # s is a list of strings.
+ for i in range(len(s) - 1):
+ n_esc = len(s[i]) - len(s[i].rstrip('\\'))
+ if n_esc % 2 == 0:
+ continue
+ else:
+ new_s = s[:i] + [s[i] + sep + s[i + 1]] + s[i + 2:]
+ return remerge(new_s)
+ return s
+
+ # split by every sep (even unescaped ones)
+ # then re-merge strings that end in an uneven number of escape chars:
+ return remerge(text.split(sep))
+
+
+@export
+class Link():
+ """A JabRef link as used to link to files and URLs."""
+
+ def __init__(self, name, path, filetype):
+ self.name, self.path, self.filetype = name, path, filetype
+
+ def __repr__(self):
+ """Return string representation."""
+ return ':'.join([Link.escape(s)
+ for s in [self.name, self.path, self.filetype]])
+
+ @classmethod
+ def from_string(cls, string):
+ """Alternative constructor to create Link from JabRef link string."""
+ name, path, filetype = [cls.unescape(part) for part
+ in split_by_unescaped_sep(string, sep=':')]
+ return cls(name, path, filetype)
+
+ @staticmethod
+ def escape(s):
+ """Escape string s."""
+ escaped = re.sub(r'\\', r'\\\\', s)
+ escaped = re.sub(':', r'\:', escaped)
+ escaped = re.sub(';', r'\;', escaped)
+ return escaped
+
+ @staticmethod
+ def unescape(text):
+ r"""
+ Unescape string s.
+
+ Assumes that there are no unescaped \, ;, ; in s.
+ """
+ text = re.sub(r'\\;', ';', text)
+ text = re.sub(r'\\:', ':', text)
+ text = re.sub(r'\\\\', r'\\', text)
+ return text
+
+
+@export
+class File():
+ r"""
+ Represent a JabRef File entry.
+
+ A JabRef File entry is a ;-separated list of links. Each link is
+ a :-separated list of name, path, and type. Each field is an escaped
+ string (escape char is \, chars that need escaping are :, ;, and \).
+
+ Example: 'Preface:Books\\Preface.pdf:PDF;Chapter 1:Books\\Chapter1.pdf:PDF'
+ """
+
+ def __init__(self, list_of_links):
+ for link in list_of_links:
+ if type(link) is not Link:
+ raise TypeError(f'{link} is not a Link')
+ self._links = list_of_links
+
+ def __repr__(self):
+ return ';'.join([str(link) for link in self._links])
+
+ @classmethod
+ def from_string(cls, string):
+ """Create File from JabRef File entry."""
+ links = split_by_unescaped_sep(string, ';')
+ return cls([Link.from_string(link) for link in links])
+
+ def __getitem__(self, key):
+ return self._links[key]
+
+ def __setitem__(self, key, link):
+ if not isinstance(link, Link):
+ raise TypeError(f'{link} is not a Link')
+ self._links[key] = link
+
+ def __len__(self):
+ return len(self._links)
+
+ def append(self, link):
+ """Append link to File entry."""
+ if not isinstance(link, Link):
+ raise TypeError(f'{link} is not a Link')
+ self._links.append(link)
+
+ def pop(self, idx):
+ """Pop link from File entry."""
+ return self._links.pop(idx)
diff --git a/src/ppf/jabref/utils.py b/src/ppf/jabref/utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..5e0b33ba59cba4dc112b126b7caeac951a315c47
--- /dev/null
+++ b/src/ppf/jabref/utils.py
@@ -0,0 +1,18 @@
+#!/usr/bin/env python3
+# -*- coding: utf-8 -*-
+"""
+:author: Adrian Schlatter
+"""
+
+import sys
+
+
+def export(obj):
+ """
+ Decorator that adds obj to __all__
+ """
+
+ mod = sys.modules[obj.__module__]
+ mod.__all__ = getattr(mod, '__all__', []) + [obj.__name__]
+
+ return obj
diff --git a/tests/__init__.py b/tests/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..79cc26cb1d638b6b579710f0a53d8db2f92f3821
--- /dev/null
+++ b/tests/__init__.py
@@ -0,0 +1,5 @@
+# -*- coding: utf-8 -*-
+"""
+Declare this directory a package so that 'python setup.py test' finds
+the unittests here.
+"""
diff --git a/tests/test_File.py b/tests/test_File.py
new file mode 100644
index 0000000000000000000000000000000000000000..aa84d00e8dce292dfdef8f669b64f82a4623711c
--- /dev/null
+++ b/tests/test_File.py
@@ -0,0 +1,91 @@
+# -*- coding: utf-8 -*-
+"""
+Test File Class
+"""
+
+import unittest
+# import code to be tested here (add to your python path!)
+import ppf.jabref as dut
+
+
+class Test_File(unittest.TestCase):
+ """Test File class."""
+
+ def test_File_init(self):
+ """Test File creation."""
+ link1 = dut.Link(name='x', path='/bla/di/bla', filetype='DOCX')
+ link2 = dut.Link(name='whatever', path=r'..\what\ever', filetype='PDF')
+
+ list_of_links = [link1, link2]
+ file = dut.File(list_of_links)
+
+ self.assertTrue(file._links is list_of_links)
+
+ def test_File_init_rejects_non_links(self):
+ """Test File creation rejects non-Link entries."""
+ with self.assertRaises(TypeError):
+ dut.File([dut.Link('x', 'p', 'PDF'), 'not-a-link'])
+
+ def test_Link_from_string(self):
+ """Test Link creation from string."""
+ string = 'Pref:Bks\\Chpt0.pdf:PDF;Chapter 1:Bks\\Chpt1.pdf:PDF'
+ file = dut.File.from_string(string)
+
+ self.assertTrue(file._links[0].name == 'Pref')
+ self.assertTrue(file._links[0].path == 'Bks\\Chpt0.pdf')
+ self.assertTrue(file._links[0].filetype == 'PDF')
+ self.assertTrue(file._links[1].name == 'Chapter 1')
+ self.assertTrue(file._links[1].path == 'Bks\\Chpt1.pdf')
+ self.assertTrue(file._links[1].filetype == 'PDF')
+
+ def test_File_repr(self):
+ """Test File string representation."""
+ link1 = dut.Link(name='a', path='b:c', filetype='d')
+ link2 = dut.Link(name='e', path='f', filetype='g;h')
+ file = dut.File([link1, link2])
+ self.assertTrue(str(file) == r'a:b\:c:d;e:f:g\;h')
+
+
+class Test_File_List_Behavior(unittest.TestCase):
+ """Test list operations on File"""
+
+ def setUp(self):
+ self.list_of_links = [dut.Link('A', './docs/A.docx', 'DOCX'),
+ dut.Link('B', 'pdfs/B.pdf', 'PDF')]
+ self.file = dut.File(self.list_of_links)
+
+ def test_indexing(self):
+ self.assertTrue(self.file[0] == self.list_of_links[0])
+
+ def test_len(self):
+ self.assertTrue(len(self.file) == 2)
+
+ def test_append(self):
+ new_link = dut.Link('C', r'.\presentations\C.pptx', 'PPTX')
+ self.file.append(new_link)
+ self.assertTrue(len(self.file) == 3)
+
+ def test_append_rejects_non_link(self):
+ with self.assertRaises(TypeError):
+ self.file.append('not-a-link')
+
+ def test_setitem_rejects_non_link(self):
+ with self.assertRaises(TypeError):
+ self.file[0] = 'not-a-link'
+
+ def test_setitem(self):
+ new_link = dut.Link('C', 'docs/C.pdf', 'PDF')
+ self.file[1] = new_link
+ self.assertTrue(self.file[1] is new_link)
+
+ def test_remove(self):
+ original_link = self.list_of_links[0]
+ popped_link = self.file.pop(0)
+ self.assertTrue(len(self.file) == 1)
+ self.assertTrue(popped_link is original_link)
+
+
+if __name__ == '__main__':
+ # This enables running the unit tests by running this script which is
+ # much more convenient than 'python setup.py test' while developing tests.
+ unittest.main()
diff --git a/tests/test_Link.py b/tests/test_Link.py
new file mode 100644
index 0000000000000000000000000000000000000000..58f086f1e0e2a394f54de549a4ede9f3b177d33b
--- /dev/null
+++ b/tests/test_Link.py
@@ -0,0 +1,49 @@
+# -*- coding: utf-8 -*-
+"""
+Test Link Class
+"""
+
+import unittest
+# import code to be tested here (add to your python path!)
+import ppf.jabref as dut
+
+
+class Test_Link(unittest.TestCase):
+ """Test Link class."""
+
+ def test_Link_init(self):
+ """Test Link creation."""
+ link = dut.Link(name='Preface',
+ path='/There/is/a/preface/somewhere.pdf',
+ filetype='PDF')
+ self.assertTrue(link.name == 'Preface')
+ self.assertTrue(link.path == '/There/is/a/preface/somewhere.pdf')
+ self.assertTrue(link.filetype == 'PDF')
+
+ def test_Link_from_string(self):
+ """Test Link creation from string."""
+ string = 'Preface:/There/is/a/preface/somewhere.pdf:PDF'
+ link = dut.Link.from_string(string)
+ self.assertTrue(link.name == 'Preface')
+ self.assertTrue(link.path == '/There/is/a/preface/somewhere.pdf')
+ self.assertTrue(link.filetype == 'PDF')
+
+ def test_escape(self):
+ """Test Link.escape() for special characters."""
+ self.assertTrue(dut.Link.escape('a:b') == r'a\:b')
+ self.assertTrue(dut.Link.escape('a;b') == r'a\;b')
+ self.assertTrue(dut.Link.escape(r'a\b') == r'a\\b')
+ self.assertTrue(dut.Link.escape(r'a\:b') == r'a\\\:b')
+ self.assertTrue(dut.Link.escape(r'a\;b') == r'a\\\;b')
+ self.assertTrue(dut.Link.escape(r'a\:b\;c') == r'a\\\:b\\\;c')
+
+ def test_repr(self):
+ """Test Link string representation."""
+ link = dut.Link(name='A', path='B:C', filetype='D;E')
+ self.assertTrue(str(link) == r'A:B\:C:D\;E')
+
+
+if __name__ == '__main__':
+ # This enables running the unit tests by running this script which is
+ # much more convenient than 'python setup.py test' while developing tests.
+ unittest.main()
diff --git a/tests/test_citationkeymapping.py b/tests/test_citationkeymapping.py
new file mode 100644
index 0000000000000000000000000000000000000000..86de5f0f3bc80102f3406f723491fb10dc99fe6b
--- /dev/null
+++ b/tests/test_citationkeymapping.py
@@ -0,0 +1,41 @@
+# -*- coding: utf-8 -*-
+"""
+Test citationkey mapping Functions.
+"""
+
+import unittest
+# import code to be tested here (add to your python path!)
+import ppf.jabref as dut
+from functools import reduce
+
+
+class Test_CitationkeyMapping(unittest.TestCase):
+ """Test counter2citationkey() and citationkey2counter functions."""
+
+ def test_counter2citationkey(self):
+ """Test counter2citationkey with known values."""
+ numbers = [0, 26, 26 + 26**2]
+ ckeys_true = ['a', 'aa', 'aaa']
+ ckeys = [dut.counter2citationkey(c) for c in numbers]
+
+ equal = reduce(lambda a, b: a and b,
+ map(lambda p, q: p == q, ckeys_true, ckeys),
+ True)
+ self.assertTrue(equal)
+
+ def test_citationkey2counter(self):
+ """Test citationkey2counter with known values."""
+ numbers_true = [0, 26, 26 + 26**2]
+ ckeys = ['a', 'aa', 'aaa']
+ numbers = [dut.citationkey2counter(c) for c in ckeys]
+
+ equal = reduce(lambda a, b: a and b,
+ map(lambda p, q: p == q, numbers_true, numbers),
+ True)
+ self.assertTrue(equal)
+
+
+if __name__ == '__main__':
+ # This enables running the unit tests by running this script which is
+ # much more convenient than 'python setup.py test' while developing tests.
+ unittest.main()
diff --git a/tests/test_split_by_unescaped_sep.py b/tests/test_split_by_unescaped_sep.py
new file mode 100644
index 0000000000000000000000000000000000000000..73cc69f111e79d65f55aaa3ad5e6561a4d183882
--- /dev/null
+++ b/tests/test_split_by_unescaped_sep.py
@@ -0,0 +1,50 @@
+# -*- coding: utf-8 -*-
+"""
+Test Link Class
+"""
+
+import unittest
+# import code to be tested here (add to your python path!)
+import ppf.jabref as dut
+
+
+class Test_split_by_unescaped_sep(unittest.TestCase):
+ """Test split_by_unescaped_sep() function."""
+
+ def test_harmless(self):
+ """Test string without escaped chars."""
+ str = 'bla:di:bla'
+ split = dut.split_by_unescaped_sep(str, sep=':')
+ self.assertTrue(split[0] == 'bla')
+ self.assertTrue(split[1] == 'di')
+ self.assertTrue(split[2] == 'bla')
+
+ def test_escaped_colon(self):
+ """Test string with escaped colon."""
+ str = r'bla\:bla:di:bla'
+ split = dut.split_by_unescaped_sep(str, sep=':')
+ self.assertTrue(split[0] == r'bla\:bla')
+ self.assertTrue(split[1] == 'di')
+ self.assertTrue(split[2] == 'bla')
+
+ def test_backslash_before_colon(self):
+ """Test string with backslash before colon."""
+ str = r'bla:di\\:bla'
+ split = dut.split_by_unescaped_sep(str, sep=':')
+ self.assertTrue(split[0] == 'bla')
+ self.assertTrue(split[1] == r'di\\')
+ self.assertTrue(split[2] == 'bla')
+
+ def test_multibackslash(self):
+ """Test string with multiple backslashs."""
+ str = r'bla:di\\\::\\bla'
+ split = dut.split_by_unescaped_sep(str, sep=':')
+ self.assertTrue(split[0] == 'bla')
+ self.assertTrue(split[1] == r'di\\\:')
+ self.assertTrue(split[2] == r'\\bla')
+
+
+if __name__ == '__main__':
+ # This enables running the unit tests by running this script which is
+ # much more convenient than 'python setup.py test' while developing tests.
+ unittest.main()