File size: 16,743 Bytes
d086025 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 | 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()
|