示例#1
0
class TestBibEntry(unittest.TestCase):
    """Tests for BibEntry class in `bibfile.py`"""

    # setup
    bfile = bibfile.BibFile()
    bibgrammar.Parse(bib1, bfile)

    ## setup for make_citekey tests
    label_style = dict(
        name_template='v{}_|l{}',
        max_names=2,
        name_name_sep='+',
        etal='etal',
        anonymous='anon',
        lower_name=False,
        article="%(names)s-%(year)s",
        book="%(names)s-%(year)s",
        misc="%(names)s-%(year)s",
        default_type="%(names)s-%(year)s",
    )

    def test_make_citation_key_simple(self):
        """Make a citation key from an entry"""
        ck = self.bfile.entries[1].make_citekey(style=self.label_style)
        self.assertEqual(ck, "Isaac+Schwilk-2010")

    def test_make_citation_key_von(self):
        """Make a citation key from an entry with von parts"""
        ck = self.bfile.entries[0].make_citekey(style=self.label_style)
        self.assertEqual(ck, "von_Hagel+vander_Meer-2010")

    def test_make_citation_three_names(self):
        """Make a citation key from an entry with more than two names"""
        ck = self.bfile.entries[2].make_citekey(style=self.label_style)
        self.assertEqual(ck, "Schwilk+Isaac+etal-2012")
示例#2
0
def main():
    '''Command line version of tool'''
    import sys
    from bibstuff import bibgrammar

    from optparse import OptionParser

    usage = "%prog [options] filename(s)"

    parser = OptionParser(usage=usage, version="%prog " + __version__)
    parser.add_option("-y", "--yearsep", action="store", type="string", \
          dest="yearsep", default = ':', help="char to separate names and year")
    parser.add_option("-s", "--sep", action="store", type="string", \
          dest="sep",  default = '+', help="char to separate names")
    parser.add_option("-m", "--maxnames", action="store", type="int", \
          dest="maxnames",  default = 2, help="Max names to add to key")
    parser.add_option("-e", "--etal", action="store", type="string", \
          dest="etal",  default = 'etal',help="What to add after max names")
    parser.add_option("-v",
                      "--verbose",
                      action="store_true",
                      dest="verbose",
                      default=False,
                      help="Print INFO messages to stdout, default=%default")

    # get options
    (options, args) = parser.parse_args()
    if options.verbose:
        biblabel_logger.setLevel(logging.INFO)

    # get database as text from .bib file(s) or stdin
    if len(args) > 0:
        try:
            src = ''.join(open(f).read() for f in args)
        except:
            print 'Error in filelist'
    else:
        src = sys.stdin.read()

    bfile = bibfile.BibFile()
    bibgrammar.Parse(src, bfile)
    used_citekeys = []  # stores created keys
    for entry in bfile.entries:
        label = make_entry_citekey(entry,
                                   used_citekeys,
                                   max_names=options.maxnames,
                                   sep=options.sep,
                                   ysep=options.yearsep,
                                   etal=options.etal)
        #:note: citekey != key, be careful!
        entry.citekey = label
        used_citekeys.insert(
            0, label
        )  #prepend to take advantage (in make_entry_citekey) of possibly sorted bfile

    for entry in bfile.entries:
        print entry
示例#3
0
def convert_only_cited(input_rst_directory, input_bib_path, source_suffix,
                       bibstuff_path):
    #    print  input_rst_directory
    input_rst_directory = os.path.abspath(input_rst_directory)
    #     print  input_rst_directory

    #    print input_bib_path
    input_bib_path = os.path.abspath(input_bib_path)
    #    print input_bib_path
    bibstuff_path = os.path.abspath(bibstuff_path)
    #    print  bibstuff_path
    sys.path.append(bibstuff_path)
    output_bib_file = input_bib_path + '_cited.txt'
    #    print output_bib_file
    bibstuff_converter = os.path.join(bibstuff_path, 'bib4txt.py')
    src_as_string = ''
    #    now add all strings from all files
    #for file in fnmatch.filter(os.walk(input_rst_directory),'*.rst'):
    ### http://www.brunningonline.net/simon/blog/archives/002022.html
    for path, dirs, files in os.walk(
            input_rst_directory):  #os.walk(os.getcwd()):
        for file in [
                os.path.abspath(os.path.join(path, filename))
                for filename in files
                if fnmatch.fnmatch(filename, '*' + source_suffix)
        ]:
            #file = fnmatch.filter(file,'*.rst')
            print file
            rst_in = os.path.abspath(file)
            rst_reader = open(rst_in, 'r')
            rst_as_string = rst_reader.read()
            rst_reader.close()
            src_as_string = src_as_string + rst_as_string

#    print src_as_string

    ebnf_dec = ebnf_sp.cites_rest
    src_parser = cite_parser = simpleparse.parser.Parser(ebnf_dec, root='src')

    bibfile_processor = bibfile.BibFile()
    bibfile_as_string = open(input_bib_path, 'r').read()
    bibgrammar.Parse(bibfile_as_string, bibfile_processor)
    parsed_bibfile = bibfile_processor

    result = bib4txt.make_text_output(src_as_string,
                                      src_parser,
                                      parsed_bibfile,
                                      style,
                                      citations_only=True)

    output = open(output_bib_file, 'w')
    output.write(result)
    output.close()
示例#4
0
class TestBibFile(unittest.TestCase):
    """Tests for `bibfile.py`"""

    # setup
    bfile = bibfile.BibFile()
    bibgrammar.Parse(bib1, bfile)

    def test_simple_read(self):
        """Check for read success on a simple .bib file"""
        self.assertEqual(len(self.bfile.entries), 5)
        self.assertEqual(self.bfile.entries[-1]['journal'],
                         'Journal of Desert Studies')

    def test_string_read(self):
        """Test if @string was read correctly"""
        s = 'Journal of Occasionally Reproducible Results'
        self.assertEqual(self.bfile.entries[-2]['journal'], s)

    def test_search_bibentry(self):
        """Check search"""
        ck = self.bfile.search_entries("Schwilk")[0]["citekey"]
        self.assertEqual(ck, "isaac.schwilk-2010")
示例#5
0
def main():
	'''Command-line tool.  See jabbrev.py -h for help'''

	input = sys.stdin
	output = sys.stdout
	
	try:
		from optparse import OptionParser
	except (ImportError, AttributeError):
		try:
			from optik import OptionParser
		except (ImportError, AttributeError):
			print "jabbrev needs python 2.3 or Greg Ward's optik module."
	
	usage = "usage: %prog [options] DATABASE_FILE [ABBREVIATION_FILE] "
	parser = OptionParser(usage=usage, version ="%prog " + __version__)
	 
	(options, args) = parser.parse_args()

	if len(args) > 2 :
		print "Too many arguments"
		sys.exit(1)
	try :
		# bibtex file is last argument
		bib = open(args[0]).read()
	except :
		print "No bibtex file found."
		sys.exit(1)
	if len(args) == 2 :
		input = open(args[1])
	else :
		input = sys.stdin.read()
			  
	bfile = bibfile.BibFile()
	bibgrammar.Parse(bib, bfile)

	journals = MakeMap(input.readlines())	
	Translate(bfile, journals)
示例#6
0
class TestBibEntryFormatter(unittest.TestCase):
	"""Test BibEntry formatting"""
	default_citation_template = bibstyles.default_templates.DEFAULT_CITATION_TEMPLATE

	test_entry = r"""@article{vanWilgen:1910,
	author={van Baer Wilgen, jr , Edward Charles},
	title =		   {A vljf test},
	year =		   1910,
	journal =	   {Testing quarterly},
	volume =	   {1},
	pages =		   {21--30}
}"""

	tbib = bibfile.BibFile()
	bibgrammar.Parse(test_entry, tbib)

	def test_bibentry_formatter(self):
		"""Test the formatter"""
		test_entry = self.tbib.entries[0]
		formatter = bibstyles.shared.EntryFormatter(self.default_citation_template)
		res = formatter.format_entry(test_entry)
		correct = "van Baer Wilgen, jr, Edward Charles. (1910) A vljf test. *Testing quarterly* 1, 21--30.  "
		self.assertEqual(res, correct)
示例#7
0
def convert_all_bib(input_bib_directory, bibstuff_path):
    """Sphinx extension to convert BibTeX file to ReSt files.
    
    """
    #print  'CURR:', os.path.abspath(os.path.curdir)
    input_bib_directory = os.path.abspath(input_bib_directory)
    bibstuff_path = os.path.abspath(bibstuff_path)
    sys.path.append(bibstuff_path)
    for name in fnmatch.filter(os.listdir(input_bib_directory), '*.bib'):
        #            print fnmatch.filter(os.listdir(input_directory),'*.bib')
        bib_in = os.path.join(input_bib_directory, name)
        # TODO: change into logging
        #            print bib_in
        #bib_in= bibfile_name = '_static/example.bib'
        bib_rst_out = bib_in + '_all.txt'


#            print bib_rst_out
#            print bibstuff_path
#            bibstuff_converter = os.path.join(bibstuff_path, 'bib4txt.py')
##            print bibstuff_converter
#            subprocess.call(['python', bibstuff_converter, '--all', '-no '+bib_rst_out,
#                                        bib_in])

    bibfile_processor = bibfile.BibFile()
    bibfile_as_string = open(bib_in, 'r').read()
    bibgrammar.Parse(bibfile_as_string, bibfile_processor)
    entries = bibfile_processor.entries
    parsed_bibfile = bibfile_processor
    citation_manager = style.CitationManager(
        [parsed_bibfile], keys=None, citation_template=style.CITATION_TEMPLATE)
    citation_manager.make_citations(entries)
    myres = citation_manager.make_citations(entries)
    out = open(bib_rst_out, 'w')
    out.write(myres)
    out.close()
示例#8
0
def main():
    """Command-line tool.
	See bibsearch.py -h for help.
	"""

    from optparse import OptionParser

    usage = "usage: %prog [options] FILE [search strings]"
    parser = OptionParser(usage=usage, version="%prog " + __version__)

    parser.add_option("-k",
                      "--key",
                      action="store_true",
                      dest="citekey_output",
                      default=False,
                      help="Output citekey rather than reference")
    parser.add_option("-l",
                      "--long",
                      action="store_true",
                      dest="long_output",
                      default=False,
                      help="Output entire bibtex entry")
    parser.add_option("-r",
                      "--regex",
                      action="store_true",
                      dest="search_input",
                      default=False,
                      help="Search for regular expression rather than key")
    parser.add_option("-s",
                      "--stylefile",
                      action="store",
                      dest="stylefile",
                      default="default.py",
                      help="Specify user-chosen style file",
                      metavar="FILE")
    parser.add_option("-f",
                      "--field",
                      action="store",
                      type="string",
                      dest="field",
                      default=None,
                      help="Search only FIELD; default=%default.",
                      metavar="FIELD")
    parser.add_option("-v",
                      "--verbose",
                      action="store_true",
                      dest="verbose",
                      default=False,
                      help="Print INFO messages to stdout, default=%default")
    parser.add_option("-V",
                      "--very_verbose",
                      action="store_true",
                      dest="very_verbose",
                      default=False,
                      help="Print DEBUG messages to stdout, default=%default")

    (options, args) = parser.parse_args()
    if options.verbose:
        bibsearch_logger.setLevel(logging.INFO)
    if options.very_verbose:
        bibsearch_logger.setLevel(logging.DEBUG)
    bibsearch_logger.debug("Script running.\nargs=%s\nstyle file=%s" %
                           (args, options.stylefile))

    try:
        src = open(args[0]).read()
    except:
        print("Error: No bibtex file found.")
        sys.exit(1)
    # If no search string was sepcified was specified, read search strings from stdin
    if len(args) < 2:
        searches = string.split(sys.stdin.read())
    else:
        searches = args[1:]

    # create object to store parsed .bib file
    parsed_bibfile = bibfile.BibFile()
    # store a parsed .bib file in parsed_bibfile
    bibgrammar.Parse(src, parsed_bibfile)

    # list of entries
    entrylist = []
    if options.field:
        for s in searches:
            entrylist.extend(
                parsed_bibfile.search_entries(s, field=options.field))
    elif options.search_input:
        for s in searches:
            entrylist.extend(parsed_bibfile.search_entries(s))
    else:
        entrylist = parsed_bibfile.get_entrylist(searches, discard=True)

    if entrylist:  #found some matches -> output the list in desired format
        result = ""
        if options.citekey_output:
            result = "\n".join(e.citekey for e in entrylist)
        elif options.long_output:
            result = "\n".join(str(e) for e in entrylist)
        else:
            # style based formated references
            style_stmt = "import bibstuff.bibstyles.%s as style" % os.path.splitext(
                options.stylefile)[0]
            exec style_stmt in globals()
            citation_manager = style.CitationManager(
                [parsed_bibfile],
                citekeys=[e.citekey for e in entrylist],
                citation_template=style.CITATION_TEMPLATE)
            cite_processor = bibstyles.shared.CiteRefProcessor(
                citation_manager)
            result = citation_manager.make_citations()
        print(result)
    else:  #did not find any matches
        bibsearch_logger.info("No matches.")
示例#9
0
def main():
    """Command-line tool.
    See bibsearch.py -h for help.
    """
    #set default input and output
    _infile = sys.stdin
    _outfile = sys.stdout

    from argparse import ArgumentParser
    _usage = "usage: %(prog)s [options] BIBTEX_FILE [search strings]"
    #from optparse import OptionParser
    #parser = OptionParser(usage=usage, version ="%prog " + __version__)

    parser = ArgumentParser(usage=_usage)
    parser.add_argument('--version', action='version', version=__version__)

    parser.add_argument("-k",
                        "--key",
                        action="store_true",
                        dest="citekey_output",
                        default=False,
                        help="Output citekey rather than reference")
    parser.add_argument("-l",
                        "--long",
                        action="store_true",
                        dest="long_output",
                        default=False,
                        help="Output entire bibtex entry")
    parser.add_argument("-r",
                        "--regex",
                        action="store_true",
                        dest="search_input",
                        default=False,
                        help="Search for regular expression rather than key")
    parser.add_argument("-F",
                        "--stylefile",
                        action="store",
                        dest="stylefile",
                        default="default.py",
                        help="Specify user-chosen style file",
                        metavar="FILE")
    parser.add_argument("-s",
                        "--style",
                        action="store",
                        dest="style",
                        default="default",
                        help="Specify user-chosen style")
    parser.add_argument("-f",
                        "--field",
                        action="store",
                        dest="field",
                        default=None,
                        help="Search only FIELD; default=%default.",
                        metavar="FIELD")
    #parser.add_argument("-v", "--verbose", action="store_true", dest="verbose", default=False, help="Print INFO messages to stdout, default=%default")
    parser.add_argument(
        "-V",
        "--verbosity",
        action="store",
        dest="verbosity",
        type=int,
        default=0,
        help="Print DEBUG messages to stdout, default=%default")
    parser.add_argument("bibtexFile",
                        action="store",
                        help="The bibtex file to search for the references.")
    parser.add_argument("searchstrings",
                        action="store",
                        nargs='*',
                        help="The strings to search for in the references.")

    args = parser.parse_args()
    if 1 == args.verbosity:
        bibsearch_logger.setLevel(logging.INFO)
    if 2 == args.verbosity:
        bibsearch_logger.setLevel(logging.DEBUG)
    bibsearch_logger.debug("Script running.\nargs=%s\nstyle file=%s" %
                           (args, args.stylefile))

    try:
        src = open(args.bibtexFile).read()
    except:
        print("Error: No bibtex file found.")
        sys.exit(1)
    # If no search string was sepcified was specified, read search strings from stdin
    if 0 == len(args.searchstrings):
        searches = str.split(sys.stdin.read())
    else:
        searches = args.searchstrings

    # create object to store parsed .bib file
    parsed_bibfile = bibfile.BibFile()
    # store a parsed .bib file in parsed_bibfile
    bibgrammar.Parse(src, parsed_bibfile)

    # list of entries
    entrylist = []
    if args.field:
        for s in searches:
            entrylist.extend(parsed_bibfile.search_entries(s,
                                                           field=args.field))
    elif args.search_input:
        for s in searches:
            entrylist.extend(parsed_bibfile.search_entries(s))
    else:
        entrylist = parsed_bibfile.get_entrylist(searches, discard=True)

    if entrylist:  #found some matches -> output the list in desired format
        result = ""
        if args.citekey_output:
            result = "\n".join(e.citekey for e in entrylist)
        elif args.long_output:
            result = "\n".join(str(e) for e in entrylist)
        else:
            #import a formatting style based on `style` command-line option
            style = importlib.import_module('bibstuff.bibstyles.%s' %
                                            args.style)
            """
            str2exec = "import bibstuff.bibstyles.%s as style"%stylename
            workaround = {}  #work around Python 2 exec vs Python 3 exec
            exec(str2exec, {}, workaround)
            style = workaround['style']
            #exec("import bibstuff.bibstyles.%s as style"%os.path.splitext(args.stylefile)[0])
            """
            str2exec = "import bibstuff.bibstyles.%s as style" % os.path.splitext(
                args.stylefile)[0]
            workaround = {}  #work around Python 2 exec vs Python 3 exec
            exec(str2exec, {}, workaround)
            style = workaround['style']
            citation_manager = style.CitationManager(
                [parsed_bibfile],
                citekeys=[e.citekey for e in entrylist],
                citation_template=style.CITATION_TEMPLATE)
            cite_processor = bibstyles.shared.CiteRefProcessor(
                citation_manager)
            result = citation_manager.make_citations()
        print(result)
    else:  #did not find any matches
        bibsearch_logger.info("No matches.")
示例#10
0
def main():
    """Command-line tool.  See bib4txt.py -h for help.
	"""

    #set default input and output
    input = sys.stdin
    output = sys.stdout

    from optparse import OptionParser

    usage = """
	usage: %prog [options] BIB_DATABASE
	standard usage: %prog -i reST_FILE  -n -o refs_FILE BIB_DATABASE
	"""

    parser = OptionParser(usage=usage, version="%prog " + __version__)

    parser.add_option("-i",
                      "--infile",
                      action="store",
                      type="string",
                      dest="infile",
                      help="Parse FILE for citation references.",
                      metavar="FILE")
    parser.add_option("-o",
                      "--outfile",
                      action="store",
                      type="string",
                      dest="outfile",
                      help="Write formatted references to FILE",
                      metavar="FILE")
    parser.add_option("-n",
                      "--nuke",
                      action="store_true",
                      dest="overwrite",
                      default=False,
                      help="silently overwrite outfile, default=%default")
    parser.add_option("-s",
                      "--stylefile",
                      action="store",
                      dest="stylefile",
                      default="default.py",
                      help="Specify user-chosen style file",
                      metavar="FILE")
    parser.add_option("-v",
                      "--verbose",
                      action="store_true",
                      dest="verbose",
                      default=False,
                      help="Print INFO messages to stdout, default=%default")
    parser.add_option("-V",
                      "--very-verbose",
                      action="store_true",
                      dest="very_verbose",
                      default=False,
                      help="Print DEBUG messages to stdout, default=%default")
    parser.add_option(
        "-a",
        "--all",
        action="store_true",
        dest="entire_doc",
        default=False,
        help=
        "Output entire document, making citation reference substitutions, default=%default"
    )
    parser.add_option(
        "-x",
        "--xp",
        action="store_true",
        dest="xp_parse",
        default=False,
        help="Use experimental document parser, default=%default")
    parser.add_option("-L",
                      "--logger-level",
                      action="store",
                      type="int",
                      dest="logger_level",
                      help="Set logging level to integer value.")

    (options, args) = parser.parse_args()
    if options.logger_level:
        bib4txt_logger.setLevel(options.logger_level)
    elif options.very_verbose:
        bib4txt_logger.setLevel(logging.DEBUG)
    elif options.verbose:
        bib4txt_logger.setLevel(logging.INFO)
    bib4txt_logger.info(
        "Script running.\nargs=%s\ninfile=%s\noutfile=%s\nstyle file=%s" %
        (args, options.infile, options.outfile, options.stylefile))
    exec("import bibstuff.bibstyles.%s as style" %
         os.path.splitext(options.stylefile)[0])

    # open output file for writing (default: stdout)
    if options.outfile:
        if os.path.exists(options.outfile) and not options.overwrite:
            print "File %s exists:  use -n option to nuke (overwrite) this file." % (
                options.outfile)
            print "PLEASE CHECK FILE NAME CAREFULLY!"
            sys.exit(1)
        output = open(options.outfile, 'w')

    # read database (.bib) files
    bibfile_names = args
    bibfile_as_string = bibfiles2string(bibfile_names)
    if not bibfile_as_string:
        bib4txt_logger.warning("No BibTeX databases found.")
        sys.exit(1)

    # read input file (default: stdin)
    if options.infile:
        try:
            input = open(options.infile, 'r')
        except:
            print "Cannot open: " + options.infile
            sys.exit(1)

    if options.entire_doc:
        ebnf_dec = ebnf_sp.cites_rest
    else:
        ebnf_dec = ebnf_sp.cites_only_rest
    if options.xp_parse:
        ebnf_dec = ebnf_sp.cites_xp
    # Create a simpleparse.parser Parser based on the chosen grammar
    cite_parser = simpleparse.parser.Parser(ebnf_dec, root='src')

    # create object to store parsed .bib file
    bibfile_processor = bibfile.BibFile()
    bib4txt_logger.debug('Ready to parse bib file.')
    #store parsed .bib files in the bibfile_processor
    bibgrammar.Parse(bibfile_as_string, bibfile_processor)
    bib4txt_logger.info('bib file parsed.')

    result = make_text_output(input.read(),
                              cite_parser,
                              bibfile_processor,
                              style,
                              citations_only=not options.entire_doc)

    output.write(result)
    output.close()
    input.close()
示例#11
0
def main():
    """Command-line tool.  See bib4txt.py -h for help.
    """

    #set default input and output
    _infile = sys.stdin
    _outfile = sys.stdout
    
    from argparse import ArgumentParser
    
    _usage = """
    usage: %(prog)s [options] BIB_DATABASE
    standard usage: %(prog)s -i reST_FILE  -n -o refs_FILE BIB_DATABASE
    """

    parser = ArgumentParser(usage=_usage)

    parser.add_argument('--version', action='version', version=__version__)

    parser.add_argument("-i", "--infile", action="store", dest="infile",
                      help="Parse FILE for citation references.", metavar="FILE")
    parser.add_argument("-o", "--outfile", action="store", dest="outfile",
                      help="Write formatted references to FILE", metavar="FILE")
    parser.add_argument("-n", "--nuke", action="store_true", dest="overwrite", default=False,
                      help="silently overwrite outfile, default=%(default)s")
    parser.add_argument("-F", "--stylefile", action="store",
                      dest="stylefile", default="default.py",
                      help="Specify user-chosen style file",metavar="FILE")
    parser.add_argument("-s", "--style", action="store", 
                      dest="style", default="default",
                      help="Specify user-chosen style (by style name).")
    #parser.add_argument("-v", "--verbose", action="store_true", dest="verbose", default=False, help="Print INFO messages to stdout, default=%(default)s")
    parser.add_argument("-V", "--verbosity", action="store", type=int, dest="verbosity", default=0,
                      help="2: print DEBUG messages; 1: print INFO messages; default=%(default)s")
    parser.add_argument("-a", "--all", action="store_true", dest="entire_doc", default=False,
                      help="Output entire document, making citation reference substitutions, default=%(default)s")
    parser.add_argument("-x", "--xp", action="store_true", dest="xp_parse",
                      default=False, help="Use experimental document parser, default=%(default)s")
    parser.add_argument("-L", "--logger-level", action="store", type=int, dest="logger_level",
                      help="Set logging level to integer value.")
    parser.add_argument("bibfiles", action="store", nargs='*',
                      help="The .bib files for the references.")

    args = parser.parse_args()
    if args.logger_level:
        bib4txt_logger.setLevel(args.logger_level)
    elif 2==args.verbosity:
        bib4txt_logger.setLevel(logging.DEBUG)
    elif 1==args.verbosity:
        bib4txt_logger.setLevel(logging.INFO)

    if args.stylefile != "default.py":
        bib4txt_logger.info("It is currently recommended to pass styles with the -s option.")
        stylename = os.path.splitext(args.stylefile)[0]
    else:
        stylename = args.style
        if "." in stylename:
            bib4txt_logger.warn("use the -f option to pass a style by filename")
            stylename = os.path.splitext(stylename)[0]

    bib4txt_logger.info(
            "\n".join([
            "Script running:",
            " bibfiles=%s",
            " infile=%s",
            " outfile=%s",
            " style=%s"
            ])%(args.bibfiles, args.infile, args.outfile, stylename)
            )
    #import a bibliography style based on `stylefile` command-line option
    #TODO: add error handling for unknown styles
    style = importlib.import_module('bibstuff.bibstyles.%s'%stylename)
    """
    str2exec = "import bibstuff.bibstyles.%s as style"%stylename
    workaround = {}  #work around Python 2 exec vs Python 3 exec
    exec(str2exec, {}, workaround)
    style = workaround['style']
    #exec("import bibstuff.bibstyles.%s as style"%os.path.splitext(args.stylefile)[0])
    """

    # open output file for writing (default: stdout)
    if args.outfile:
        if os.path.exists(args.outfile) and not args.overwrite:
            _msg = """ABORTED because output file %s already exists:
            Use -n option to nuke (overwrite) this file.
            PLEASE CHECK FILE NAME CAREFULLY!
            """%(args.outfile)
            print(_msg)
            sys.exit(1)
        _outfile = open(args.outfile,'w')

    # read database (.bib) files
    bibfile_names = args.bibfiles
    bibfile_as_string = bibfiles2string(bibfile_names)
    if not bibfile_as_string:
        bib4txt_logger.warning("No BibTeX databases found.")
        sys.exit(1)

    # read input file (default: stdin)
    if args.infile:
        try:
            _infile = open(args.infile, mode='r', encoding='utf-8')
        except TypeError:  #Python 2 did not accept encoding arg
            _infile = open(args.infile, mode='r')
        except:
            raise ValueError("Cannot open: "+args.infile)

    if args.entire_doc:
        ebnf_dec = ebnf_sp.cites_rest
    else:
        ebnf_dec = ebnf_sp.cites_only_rest
    if args.xp_parse:
        ebnf_dec = ebnf_sp.cites_xp
    # Create a simpleparse.parser Parser based on the chosen grammar
    cite_parser = simpleparse.parser.Parser(ebnf_dec, root='src')

    # create object to store parsed .bib file
    bibfile_processor = bibfile.BibFile()
    bib4txt_logger.debug('Ready to parse bib file.')
    #store parsed .bib files in the bibfile_processor
    bibgrammar.Parse(bibfile_as_string, bibfile_processor)
    bib4txt_logger.info('bib file parsed.')

    result = make_text_output(
        _infile.read(),
        cite_parser,
        bibfile_processor,
        style,
        citations_only = not args.entire_doc)

    _outfile.write(result)        
    _outfile.close()
    _infile.close()
示例#12
0
def main():
    '''Command line version of tool'''
    import sys
    import optparse
    import json

    class MyParser(optparse.OptionParser):
        def format_epilog(self, formatter):
            return self.epilog

    usage = "%prog [options] filename(s)"

    parser = MyParser(usage=usage,
                      version="%prog " + __version__,
                      epilog="""
More information:
The ``--style`` option takes a file name. See the file `citekey-style.json` in the
examples directory: The file must include only a valid JSON structure of the form:
{
  "name_template" : "v{_}_|l{}",
   "max_names" : "2",
   "name_name_sep" : "+",
   "etal" : "etal",
   "anonymous" : "anon",
   "lower_name" : "False",
   "article" : "%(names)s:%(year)s",
   "book" : "%(names)s:%(year)s",
   "misc" : "%(names)s:%(year)s",
   "default_type" : "%(names)s:%(year)s"
 }
""")

    parser.add_option("-s", "--style", action="store", type="string", \
           dest="style", default = '', help="File with label format (json)")
    parser.add_option("-v",
                      "--verbose",
                      action="store_true",
                      dest="verbose",
                      default=False,
                      help="Print INFO messages to stdout, default=%default")
    # :TODO: Add an options group stype_opts and an option for each style item
    # in the style dictionary.

    # get options
    (options, args) = parser.parse_args()
    if options.verbose:
        biblabel_logger.setLevel(logging.INFO)

    # update label style
    if options.style:
        try:
            new_style = json.load(open(options.style))
            citekey_label_style.update(new_style)
        except IOError:
            biblabel_logger.error("Missing style file: %s" % options.style,
                                  exc_info=True)
            exit(1)
        except ValueError:
            biblabel_logger.error(
                "Invalid style file: %s.  Style file should be JSON format dictionary"
                % options.style,
                exc_info=True)
            exit(1)

    # get database as text from .bib file(s) or stdin
    if len(args) > 0:
        try:
            src = ''.join(open(f).read() for f in args)
        except:
            biblabel_logger.error('Error in filelist')
    else:
        src = sys.stdin.read()

    bfile = bibfile.BibFile()
    bibgrammar.Parse(src, bfile)
    used_citekeys = []  # stores created keys
    for entry in bfile.entries:
        label = entry.make_citekey(used_citekeys, citekey_label_style)
        entry.citekey = label
        used_citekeys.insert(0, label)  # prepend to take advantage (in
        # make_entry_citekey) of possibly sorted
        # bfile
    for entry in bfile.entries:
        print entry