From 0101065e79f0964e1f579ab44a6466e23b1f3908 Mon Sep 17 00:00:00 2001 From: Sam Thursfield Date: Thu, 16 Oct 2014 13:33:16 +0000 Subject: Enforce that morphology name should match file basename --- morphlib/morphloader.py | 24 +++++++++++++++++++++++- morphlib/morphologyfactory.py | 5 +++-- 2 files changed, 26 insertions(+), 3 deletions(-) diff --git a/morphlib/morphloader.py b/morphlib/morphloader.py index 8289b01e..4dde1c4e 100644 --- a/morphlib/morphloader.py +++ b/morphlib/morphloader.py @@ -18,6 +18,7 @@ import collections import logging +import os import warnings import yaml @@ -59,6 +60,14 @@ class MorphologyValidationError(morphlib.Error): pass +class InvalidNameError(MorphologyValidationError): + + def __init__(self, name, morph_filename, expected_name): + self.msg = ( + 'Morphology name %s does not correspond to filename %s, expected ' + '%s' % (name, morph_filename, expected_name)) + + class UnknownKindError(MorphologyValidationError): def __init__(self, kind, morph_filename): @@ -398,7 +407,7 @@ class MorphologyLoader(object): return morphlib.morphology.Morphology(obj) - def load_from_string(self, string, filename='string'): + def load_from_string(self, string, filename=None): '''Load a morphology from a string. Return the Morphology object. @@ -436,9 +445,22 @@ class MorphologyLoader(object): with morphlib.savefile.SaveFile(filename, 'w') as f: f.write(text) + def _morphology_name_from_filename(self, filename): + '''Calculate expected morphology name from its filename.''' + return os.path.splitext(os.path.basename(filename))[0] + def validate(self, morph): '''Validate a morphology.''' + # Check the 'name' field matches the filename. Strange errors can occur + # if the name doesn't match the filename and isntead duplicates that of + # a different morphology. + if morph.filename is not None: + expected_name = self._morphology_name_from_filename(morph.filename) + if morph['name'] != expected_name: + raise InvalidNameError(morph['name'], morph.filename, + expected_name) + # Validate that the kind field is there. self._require_field('kind', morph) diff --git a/morphlib/morphologyfactory.py b/morphlib/morphologyfactory.py index b0a0528d..43afc9c7 100644 --- a/morphlib/morphologyfactory.py +++ b/morphlib/morphologyfactory.py @@ -58,7 +58,8 @@ class MorphologyFactory(object): chatty=True) try: repo = self._lrc.get_repo(reponame) - morph = loader.load_from_string(repo.cat(sha1, filename)) + morph = loader.load_from_string(repo.cat(sha1, filename), + filename) except IOError: morph = None file_list = repo.ls_tree(sha1) @@ -69,7 +70,7 @@ class MorphologyFactory(object): chatty=True) try: text = self._rrc.cat_file(reponame, sha1, filename) - morph = loader.load_from_string(text) + morph = loader.load_from_string(text, filename) except morphlib.remoterepocache.CatFileError: morph = None file_list = self._rrc.ls_tree(reponame, sha1) -- cgit v1.2.1