From 8a9d2e60d0e3bb27678220d29b2af5c948af1785 Mon Sep 17 00:00:00 2001 From: Lertsenem Date: Mon, 14 Sep 2015 13:02:56 +0200 Subject: [PATCH] Adding Persoconf class Yep, OOP can be useful. --- persoconf/persoconf.py | 77 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 77 insertions(+) create mode 100644 persoconf/persoconf.py diff --git a/persoconf/persoconf.py b/persoconf/persoconf.py new file mode 100644 index 0000000..bb8c5f7 --- /dev/null +++ b/persoconf/persoconf.py @@ -0,0 +1,77 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- + +import os + +from metafile import Metafile, MalformedMetafileError, NoPathDefinedError + +class Persoconf(object): + """The root of a persoconf""" + + def __init__(self, path, metafile="META"): + self.path = path + self.metafile = metafile + + self.check_validity() + + + # -------------------------------------- + def check_validity(self): + """Check if this Persoconf has a valid path""" + + if not os.path.isdir(self.path): + if os.path.exists(self.path): + raise FileInsteadOfDirError("Persoconf root '%s' exists but " \ + "is a file" + % self.path ) + else: + raise PersoconfRootDoesNotExistError("Persoconf root '%s' " \ + "does not exist" + % self.path ) + + return + + # -------------------------------------- + def list_apps(self, logger=None): + """List all apps in the persoconf repo. Returns a dictionnary + { appname -> Metafile =""" + + apps_list = {} + + for potential_app in os.listdir(self.path): + + try: + # Try to initialize a metafile from the path. + appmeta = Metafile(json_path = self.path +"/"+ + potential_app +"/"+ + self.metafile) + + apps_list[appmeta.name] = appmeta + + except FileNotFoundError: + if logger is not None: + logger.info("No metafile %s in %s, probably not an app; " \ + "ignoring" + % (self.metafile, potential_app) ) + continue + + except MalformedMetafileError: + if logger is not None: + logger.warning("Malformed metafile %s in app %s ; ignoring" + % (self.metafile, potential_app) ) + continue + + return apps_list + + + +class FileInsteadOfDirError(Exception): + """We expected a directory but got a file instead""" + def __init__(self, message): + Exception.__init__(self, message) + + +class PersoconfRootDoesNotExistError(Exception): + """The Persoconf root directory was not created""" + def __init__(self, message): + Exception.__init__(self, message)