From 642bdf9672d1572354d27ddea5c5ba8b92f218ca Mon Sep 17 00:00:00 2001 From: Dafydd Harries Date: Mon, 18 Mar 2013 01:57:11 -0400 Subject: code for parsing license summaries Plus test runner. --- license.py | 70 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ test.py | 14 +++++++++++++ 2 files changed, 84 insertions(+) create mode 100644 license.py create mode 100755 test.py diff --git a/license.py b/license.py new file mode 100644 index 0000000..853cdc0 --- /dev/null +++ b/license.py @@ -0,0 +1,70 @@ + +class License(object): + def __init__(self, name): + self.name = name + + def __iter__(self): + yield self.name + + def __str__(self, depth=0): + return self.name + + def __repr__(self): + return '<%s %s>' % (self.__class__.__name__, self.name) + +class Licenses(object): + def __init__(self, xs): + self.xs = xs + + def __iter__(self): + for x in self.xs: + for y in iter(x): + yield y + + def __str__(self, depth=0): + j = ' %s ' % (self._join,) + ss = [x.__str__(depth=depth+1) for x in self.xs] + s = j.join(ss) + + if depth > 0: + s = '(%s)' % s + + return s + + def __repr__(self): + return '<%s %r>' % (self.__class__.__name__, self.xs) + +class AllLicenses(Licenses): + _join = '&' + +class AnyLicense(Licenses): + _join = '|' + +def parse_licenses(s): + """ + >>> print parse_licenses("X") + X + >>> print parse_licenses("X or Y or Z") + X | Y | Z + >>> print parse_licenses("X and Y and Z") + X & Y & Z + >>> parse_licenses("X or Y and Z") + , , ]>]> + >>> print parse_licenses("X or Y and Z") + X | (Y & Z) + >>> print parse_licenses("X and Y or Z") + (X & Y) | Z + >>> print parse_licenses("X, and Y or Z") + X & (Y | Z) + """ + + splits = ( + (', and ', AllLicenses), + (' or ', AnyLicense), + (' and ', AllLicenses)) + + for (split_str, cls) in splits: + if split_str in s: + return cls([parse_licenses(sub) for sub in s.split(split_str)]) + + return License(s) diff --git a/test.py b/test.py new file mode 100755 index 0000000..cbe79d6 --- /dev/null +++ b/test.py @@ -0,0 +1,14 @@ +#!/usr/bin/env python + +import os + +import nose.core + +if 'NOSE_TESTMATCH' not in os.environ: + os.environ['NOSE_TESTMATCH'] = '(?:^|[./])test(_|$)' + +if 'NOSE_WITH_DOCTEST' not in os.environ: + os.environ['NOSE_WITH_DOCTEST'] = '1' + +if __name__ == '__main__': + nose.core.run() -- cgit v1.2.3