Example #1
0
File: config.py Project: huxuan/gtg
    def get(self, option):
        """ Get option from configuration.

        If the option is not specified in the configuration or is of invalid
        type, return default value. If there is no default value,
        None is returned
        """
        default_value = self._defaults.get(option)
        if default_value is None:
            log.warning('No default value for %s in %s', option,
                        self._section_name)

        get_function = self._type_function(default_value)

        try:
            value = get_function(option)
        except ValueError as e:
            value = None
            log.warning('Invalid configuration value "%s" for %s in %s: %s',
                        self._section.get(option), option, self._section_name,
                        e)

        if value is None and default_value is None:
            raise ValueError(
                'No valid configuration value or default value was '
                'found for %s in %s'.format(option, self._section_name))
        elif value is None:
            return default_value
        else:
            return value
Example #2
0
    def __init__(self):
        """
         Creates a dictionary of the currently available backend modules
        """
        super().__init__()
        if hasattr(self, "backend_modules"):
            # This object has already been constructed
            return
        self.backend_modules = {}
        backend_files = self._find_backend_files()
        # Create module names
        module_names = [f.replace(".py", "") for f in backend_files]
        log.debug("Backends found: " + str(module_names))
        # Load backend modules
        for module_name in module_names:
            extended_module_name = "GTG.backends." + module_name
            try:
                __import__(extended_module_name)
            except ImportError as exception:
                # Something is wrong with this backend, skipping
                log.warning("Backend %s could not be loaded: %s" %
                            (module_name, str(exception)))
                continue
            except Exception as exception:
                # Other exception log as errors
                log.error("Malformated backend %s: %s" %
                          (module_name, str(exception)))
                continue

            self.backend_modules[module_name] = \
                sys.modules[extended_module_name]
Example #3
0
File: editor.py Project: huxuan/gtg
    def init_dimensions(self):
        """ Restores position and size of task if possible """
        position = self.config.get('position')
        if position and len(position) == 2:
            try:
                self.window.move(int(position[0]), int(position[1]))
            except ValueError:
                log.warning('Invalid position configuration for task %s: %s',
                            self.task.get_id(), position)

        size = self.config.get('size')
        if size and len(size) == 2:
            try:
                self.window.resize(int(size[0]), int(size[1]))
            except ValueError:
                log.warning('Invalid size configuration for task %s: %s',
                            self.task.get_id(), size)
Example #4
0
File: config.py Project: huxuan/gtg
def open_config_file(config_file):
    """ Opens config file and makes additional checks

    Creates config file if it doesn't exist and makes sure it is readable and
    writable by user. That prevents surprise when user is not able to save
    configuration when exiting the app.
    """
    dirname = os.path.dirname(config_file)
    if not os.path.exists(dirname):
        os.makedirs(dirname)
    if not os.path.exists(config_file):
        open(config_file, "w").close()
    if not os.access(config_file, os.R_OK | os.W_OK):
        raise Exception("File " + config_file + " is a configuration file "
                        "for gtg, but it cannot be read or written. "
                        "Please check it")
    config = configparser.ConfigParser()
    try:
        config.read(config_file)
    except configparser.Error as e:
        log.warning("Problem with opening file %s: %s", config_file, e)
    return config
Example #5
0
    def new_search_tag(self, name, query, attributes={}):
        """
        Create a new search tag

        @returns GTG.core.tag.Tag: the new search tag/None for a invalid query
        """
        try:
            parameters = parse_search_query(query)
        except InvalidQuery as e:
            log.warning("Problem with parsing query '%s' (skipping): %s" %
                        (query, e.message))
            return None

        # Create own copy of attributes and add special attributes label, query
        init_attr = dict(attributes)
        init_attr["label"] = name
        init_attr["query"] = query

        tag = Tag(name, req=self.requester, attributes=init_attr)
        self._add_new_tag(name, tag, search_filter, parameters,
                          parent_id=SEARCH_TAG)
        self.save_tagtree()
        return tag
Example #6
0
def openxmlfile(zefile, root):
    """ Open an XML file in a robust way

    If file could not be opened, try:
        - file__
        - file.bak.0
        - file.bak.1
        - .... until BACKUP_NBR

    If file doesn't exist, create a new file """

    # reset _USED_BACKUP and _BACKUP_FILE_INFO
    global _USED_BACKUP
    global _BACKUP_FILE_INFO
    _USED_BACKUP = False
    _BACKUP_FILE_INFO = ""
    tmpfile = zefile + '__'
    try:
        if os.path.exists(zefile):
            return _try_openxmlfile(zefile, root)
        elif os.path.exists(tmpfile):
            log.warning("Something happened to %s. Using backup" % zefile)
            os.rename(tmpfile, zefile)
            _USED_BACKUP = True
            _BACKUP_FILE_INFO = "Recovered from backup made on: " + \
                datetime.datetime.fromtimestamp(
                    os.path.getmtime(tmpfile)).strftime('%Y-%m-%d')
            return _try_openxmlfile(zefile, root)

    except IOError as msg:
        print(msg)
        sys.exit(1)

    except xml.parsers.expat.ExpatError as msg:
        errormsg = "Error parsing XML file %s: %s" % (zefile, msg)
        log.error(errormsg)
        if os.path.exists(tmpfile):
            log.warning("Something happened to %s. Using backup" % zefile)
            os.rename(tmpfile, zefile)
            _USED_BACKUP = True
            _BACKUP_FILE_INFO = "Recovered from backup made on: " + \
                datetime.datetime.fromtimestamp(
                    os.path.getmtime(tmpfile)).strftime('%Y-%m-%d')
            # Ok, try one more time now
            try:
                return _try_openxmlfile(zefile, root)
            except Exception as msg:
                log.warning('Failed with reason: %s' % msg)

    # Try to revert to backup
    backup_name = _get_backup_name(zefile)
    for i in range(BACKUP_NBR):
        backup_file = "%s.bak.%d" % (backup_name, i)
        if os.path.exists(backup_file):
            log.info("Trying to restore backup file %s" % backup_file)
            _USED_BACKUP = True
            _BACKUP_FILE_INFO = "Recovered from backup made on: " + \
                datetime.datetime.fromtimestamp(
                    os.path.getmtime(backup_file)).strftime('%Y-%m-%d')
            try:
                return _try_openxmlfile(backup_file, root)
            except Exception as msg:
                log.warning('Failed with reason: %s' % msg)

    log.info("No suitable backup was found")

    # Creating empty file
    doc, xmlproject = emptydoc(root)
    newfile = savexml(zefile, doc)
    if not newfile:
        log.error("Could not create a new file %s" % zefile)
        sys.exit(1)
    # set _USED_BACKUP even if there's a failure to notify about the same
    _USED_BACKUP = True
    _BACKUP_FILE_INFO = "No backups found. Created a new file"
    return _try_openxmlfile(zefile, root)

    # exit if execution reached this statement
    sys.exit(1)
Example #7
0
File: rtm.py Project: huxuan/gtg
    _use_jsonlib = True
except ImportError:
    try:
        import json as json
        assert json
        _use_jsonlib = True
    except ImportError:
        try:
            from django.utils import simplejson as json
            _use_jsonlib = True
        except ImportError:
            pass

if not _use_jsonlib:
    log.warning("simplejson module is not available, "
                "falling back to the internal JSON parser. "
                "Please consider installing the simplejson module from "
                "http://pypi.python.org/pypi/simplejson.")

__author__ = 'Sridhar Ratnakumar <http://nearfar.org/>'
__all__ = (
    'API',
    'createRTM',
    'set_log_level',
)

SERVICE_URL = 'http://api.rememberthemilk.com/services/rest/'
AUTH_SERVICE_URL = 'http://www.rememberthemilk.com/services/auth/'


class RTMError(Exception):
    pass