Esempio n. 1
0
    def load(self, fname=[], to_state=BIBOLAMAZIFILE_LOADED):
        """
        Load the given file into the current object.

        If `fname` is `None`, then reset the object to an empty state. If `fname` is not
        given or an empty ``list``, then use any previously loaded fname and its state.

        This function may be called several times with different states to incrementally
        load the file, for example::

            bibolamazifile.reset()
            # load up to 'parsed' state
            bibolamazifile.load(fname="somefile.bibolamazi.bib", to_state=BIBOLAMAZIFILE_PARSED)
            # continue loading up to fully 'loaded' state
            bibolamazifile.load(fname="somefile.bibolamazi.bib", to_state=BIBOLAMAZIFILE_LOADED)

        If `to_state` is given, will only attempt to load the file up to that state. This
        can be useful, e.g., in a config editor which needs to parse the sections of the
        file but does not need to worry about syntax errors. The state should be one of
        :py:const:`BIBOLAMAZIFILE_INIT`, :py:const:`BIBOLAMAZIFILE_READ`,
        :py:const:`BIBOLAMAZIFILE_PARSED` or :py:const:`BIBOLAMAZIFILE_LOADED`.
        """
        
        if (isinstance(fname, list) and not fname):
            # fname=[], so keep old file name and properties.
            pass
        else:
        #if (fname or not isinstance(fname, list)):
            # required to replace current file, if one open
            self._fname = fname
            self._dir = os.path.dirname(os.path.realpath(fname)) if fname is not None else None
            self._load_state = BIBOLAMAZIFILE_INIT
            self._header = None
            self._config = None
            self._config_data = None
            self._startconfigdatalineno = None
            self._rest = None
            self._cmds = None
            self._sources = None
            self._source_lists = []
            self._filters = []
            self._cache_accessors = {} # dict { class-type: class-instance }
            self._bibliographydata = None
            self._user_cache = BibUserCache(cache_version=butils.get_version())
            
        if (to_state >= BIBOLAMAZIFILE_READ  and  self._load_state < BIBOLAMAZIFILE_READ):
            try:
                with codecs.open(self._fname, 'r', encoding=BIBOLAMAZI_FILE_ENCODING) as f:
                    logger.longdebug("File "+repr(self._fname)+" opened.")
                    self._read_config_stream(f, self._fname)
            except IOError as e:
                raise BibolamaziError(u"Can't open file `%s': %s" %(self._fname, unicode(e)))

        if (to_state >= BIBOLAMAZIFILE_PARSED  and  self._load_state < BIBOLAMAZIFILE_PARSED):
            self._parse_config()

        if (to_state >= BIBOLAMAZIFILE_LOADED  and  self._load_state < BIBOLAMAZIFILE_LOADED):
            self._load_contents()

        return True
Esempio n. 2
0
    def saveToFile(self):
        """
        Save the current bibolamazi file object to disk.

        This will write to the file :py:meth:`fname()` in order:

          - the raw header data (:py:meth:`rawHeader()`) unchanged

          - the config section text (:py:meth:`rawConfig()`) unchanged

          - the bibliography data contained in :py:meth:`bibliographyData`, saved in
            BibTeX format.

        A warning message is included after the config section that the remainder of the
        file was automatically generated.

        As the file `fname` is expected to already exist, it is always silently
        overwritten (so be careful).
        """
        with codecs.open(self._fname, 'w', BIBOLAMAZI_FILE_ENCODING) as f:
            f.write(self._header)
            f.write(self._config)
            f.write(_repl(AFTER_CONFIG_TEXT, {
                r'__BIBOLAMAZI_VERSION__': butils.get_version(),
                r'__DATETIME_NOW__': datetime.now().isoformat()
                }))

            if (self._bibliographydata):
                #
                # Pybtex 0.18: bibtex writer uses entry.original_type instead of
                # entry.type. (Why?? no idea)
                #
                # So if any filters changed entry.type, reflect that in
                # entry.original_type.
                for key, entry in self._bibliographydata.entries.iteritems():
                    entry.original_type = entry.type

                #
                # Write to bibtex output
                #
                w = outputbibtex.Writer()
                w.write_stream(self._bibliographydata, f)
            
            logger.info("Updated output file `"+self._fname+"'.")

        # if we have cache to save, save it
        if (self._user_cache and self._user_cache.hasCache()):
            cachefname = self.cacheFileName()
            try:
                with open(cachefname, 'wb') as f:
                    logger.debug("Writing cache to file %s" %(cachefname))
                    self._user_cache.saveCache(f)
            except IOError as e:
                logger.debug("Couldn't save cache to file `%s'." %(cachefname))
                pass
Esempio n. 3
0
    def saveToFile(self, fname=None, cachefname=None):
        """
        Save the current bibolamazi file object to disk.

        This method will write the bibliography data to the file specified to by `fname`
        (or :py:meth:`fname()` if `fname=None`).  Specifically, we will write in order:

          - the raw header data (:py:meth:`rawHeader()`) unchanged

          - the config section text (:py:meth:`rawConfig()`) unchanged

          - the bibliography data contained in :py:meth:`bibliographyData`, saved in
            BibTeX format.

        A warning message is included after the config section that the remainder of the
        file was automatically generated.

        The cache is also saved, unless `cachefname=False`.  If `cachefname=None` (the
        default) or `cachefname=True`, the cache is saved to the *old* file name with
        extension '.bibolamazicache', that is, the one given by `self.fname()` and not in
        `fname`. (The rationale is that we want to be able to use the cache next time we
        open the file `self.fname()`.) You may also specify `cachefname=<file name>` to
        save the cache to a specific file name. NOTE: this file is silently overwritten.

        As the file `fname` is expected to already exist, it is always silently
        overwritten (so be careful). Same with the cache file.
        """
        if fname is None:
            fname = self._fname

        if cachefname is None or (isinstance(cachefname, bool) and cachefname):
            cachefname = self.cacheFileName()
        elif isinstance(cachefname, bool) and not cachefname:
            cachefname = ''
        else:
            pass # cachefname has a specific file name
            
        with codecs.open(fname, 'w', BIBOLAMAZI_FILE_ENCODING) as f:
            f.write(self._header)
            f.write(self._config)
            f.write(_repl(AFTER_CONFIG_TEXT, {
                r'__BIBOLAMAZI_VERSION__': butils.get_version(),
                r'__DATETIME_NOW__': datetime.now().isoformat()
                }))

            if (self._bibliographydata):
                #
                # Pybtex 0.18: bibtex writer uses entry.original_type instead of
                # entry.type. (Why?? no idea)
                #
                # So if any filters changed entry.type, reflect that in
                # entry.original_type.
                for key, entry in self._bibliographydata.entries.iteritems():
                    entry.original_type = entry.type

                #
                # Write to bibtex output
                #
                w = outputbibtex.Writer()
                w.write_stream(self._bibliographydata, f)
            
            logger.info("Updated output file `"+self._fname+"'.")

        # if we have cache to save, save it
        if (cachefname and self._user_cache and self._user_cache.hasCache()):
            try:
                with open(cachefname, 'wb') as f:
                    logger.debug("Writing cache to file %s" %(cachefname))
                    self._user_cache.saveCache(f)
            except IOError as e:
                logger.debug("Couldn't save cache to file `%s'." %(cachefname))
                pass