From 0718ff1e5935a2b3db482ab6ac94b2c634020815 Mon Sep 17 00:00:00 2001 From: Louis Date: Wed, 19 Feb 2014 12:26:31 +0100 Subject: [PATCH] Added docstrings --- songbook.py | 5 +++++ songbook/__init__.py | 7 ++++-- songbook/authors.py | 17 +++++++++++--- songbook/build.py | 38 +++++++++++++++++++++++++++----- songbook/files.py | 7 +++++- songbook/index.py | 27 ++++++++++++----------- songbook/plastex-patchedbabel.py | 3 +++ songbook/plastex-songs.py | 18 +++++++++++++++ songbook/plastex.py | 4 ++++ songbook/songs.py | 4 ++++ 10 files changed, 105 insertions(+), 25 deletions(-) diff --git a/songbook.py b/songbook.py index 3fd2af2e..7dc75e4b 100755 --- a/songbook.py +++ b/songbook.py @@ -2,6 +2,8 @@ # -*- coding: utf-8 -*- # +"""Command line tool to compile songbooks using the songbook library.""" + import argparse import json import locale @@ -14,6 +16,7 @@ from songbook import __VERSION__ def argument_parser(args): + """Parse argumnts""" parser = argparse.ArgumentParser(description="A song book compiler") parser.add_argument('--version', help='Show version', action='version', @@ -35,6 +38,8 @@ def argument_parser(args): def main(): + """Main function:""" + # set script locale to match user's try: locale.setlocale(locale.LC_ALL, '') diff --git a/songbook/__init__.py b/songbook/__init__.py index 4071a4e2..afaf37ac 100644 --- a/songbook/__init__.py +++ b/songbook/__init__.py @@ -2,5 +2,8 @@ import os __VERSION__ = "3.7.2" -# Directory containing shared data (default templates, custom LaTeX packages, etc.) -__SHAREDIR__ = os.path.abspath(os.path.join(os.path.dirname(__file__), "..", "share")) +# Directory containing shared data (default templates, custom LaTeX packages, +# etc.) +__SHAREDIR__ = os.path.abspath( + os.path.join(os.path.dirname(__file__), "..", "share") + ) diff --git a/songbook/authors.py b/songbook/authors.py index 9ca095e5..2e5ba4da 100644 --- a/songbook/authors.py +++ b/songbook/authors.py @@ -1,9 +1,10 @@ #!/usr/bin/env python # -*- coding: utf-8 -*- +"""Authors string management.""" def split_author_names(string): - """Split author between first and last name. + r"""Split author between first and last name. The last space separates first and last name, but spaces following a backslash or a command are not separators. @@ -33,6 +34,15 @@ def split_author_names(string): def split_sep_author(string, sep): + """Split authors string according to separators. + + Arguments: + - string: string containing authors names ; + - sep: regexp matching a separator. + + >>> split_sep_author("Tintin and Milou", '^(.*) and (.*)$') + ["Tintin", "Milou"] + """ authors = [] match = sep.match(string) while match: @@ -44,7 +54,7 @@ def split_sep_author(string, sep): def processauthors(authors_string, after=[], ignore=[], sep=[]): - """Return a list of authors + r"""Return a list of authors For example, we are processing: # processauthors( @@ -54,9 +64,10 @@ def processauthors(authors_string, after=[], ignore=[], sep=[]): (just here to show you how processing is done)", # after = ["by"], # ignore = ["anonymous"], - # sep = ["and"] + # sep = [re.compile('^(.*) and (.*)$')], # ) + The "authors_string" string is processed as: 1) First, parenthesis (and its content) are removed. diff --git a/songbook/build.py b/songbook/build.py index 39fb33cc..056405d2 100755 --- a/songbook/build.py +++ b/songbook/build.py @@ -1,6 +1,8 @@ #!/usr/bin/env python # -*- coding: utf-8 -*- +"""Build a songbook, according to parameters found in a .sb file.""" + from subprocess import call import codecs import glob @@ -16,9 +18,15 @@ from songbook import __SHAREDIR__ def parseTemplate(template): + """Return the list of parameters defined in the template.""" embeddedJsonPattern = re.compile(r"^%%:") with open(template) as template_file: - code = [line[3:-1] for line in template_file if embeddedJsonPattern.match(line)] + code = [ + line[3:-1] + for line + in template_file + if embeddedJsonPattern.match(line) + ] data = json.loads(''.join(code)) parameters = dict() @@ -56,7 +64,8 @@ def formatDeclaration(name, parameter): value = "" if "default" in parameter: value = parameter["default"] - return ('\\def\\set@{name}#1{{\\def\\get{name}{{#1}}}}\n'.format(name=name) + return ( + '\\def\\set@{name}#1{{\\def\\get{name}{{#1}}}}\n'.format(name=name) + formatDefinition(name, toValue(parameter, value)) ) @@ -66,6 +75,10 @@ def formatDefinition(name, value): def clean(basename): + """Clean (some) temporary files used during compilation. + + Depending of the LaTeX modules used in the template, there may be others + that are note deleted by this function.""" generated_extensions = [ "_auth.sbx", "_auth.sxd", @@ -85,6 +98,7 @@ def clean(basename): def makeTexFile(sb, output): + """Create the LaTeX file corresponding to the .sb file given in argument.""" datadir = sb['datadir'] name = output[:-4] template_dir = os.path.join(datadir, 'templates') @@ -178,13 +192,25 @@ def makeTexFile(sb, output): # output template commentPattern = re.compile(r"^\s*%") - with codecs.open(os.path.join(template_dir, template), 'r', 'utf-8') as template_file: - content = [line for line in template_file if not commentPattern.match(line)] + with codecs.open( + os.path.join(template_dir, template), 'r', 'utf-8' + ) as template_file: + content = [ + line + for line + in template_file + if not commentPattern.match(line) + ] for index, line in enumerate(content): if re.compile("getDataImgDirectory").search(line): - if os.path.abspath(os.path.join(datadir, "img")).startswith(os.path.abspath(os.path.dirname(output))): - imgdir = os.path.relpath(os.path.join(datadir, "img"), os.path.dirname(output)) + if os.path.abspath(os.path.join(datadir, "img")).startswith( + os.path.abspath(os.path.dirname(output)) + ): + imgdir = os.path.relpath( + os.path.join(datadir, "img"), + os.path.dirname(output) + ) else: imgdir = os.path.abspath(os.path.join(datadir, "img")) line = line.replace("\\getDataImgDirectory", ' {%s/} ' % imgdir) diff --git a/songbook/files.py b/songbook/files.py index ce2cc6bd..0f070617 100644 --- a/songbook/files.py +++ b/songbook/files.py @@ -2,11 +2,16 @@ # -*- coding: utf-8 -*- # +"""File system utilities.""" + import fnmatch import os - def recursiveFind(root_directory, pattern): + """Recursively find files matching a pattern, from a root_directory. + + Return a list of files matching the pattern. + """ matches = [] for root, dirnames, filenames in os.walk(root_directory): for filename in fnmatch.filter(filenames, pattern): diff --git a/songbook/index.py b/songbook/index.py index 8a8485e7..2481e6ab 100644 --- a/songbook/index.py +++ b/songbook/index.py @@ -1,13 +1,12 @@ #!/usr/bin/python # -*- coding: utf-8 -*- -# Generate indexes files for the Crep's chordbook compilation. This is -# a replacement for the original makeindex program written in C that -# produces an index file (.sbx) from a file generated by the latex -# compilation of the songbook (.sxd). -# -# Usage : songbook-makeindex.py src -# src is the .sxd file generated by latex -# + +"""Manage indexes. + +Generate indexes files for the songbook compilation. This is a replacement for +the original makeindex program written in C that produces an index file (.sbx) +from a file generated by the latex compilation of the songbook (.sxd). +""" from unidecode import unidecode import locale @@ -32,11 +31,11 @@ def sortkey(value): return locale.strxfrm(unidecode(simpleparse(value).replace(' ', 'A'))) -def processSXDEntry(tab): - return (tab[0], tab[1], tab[2]) - - def processSXD(filename): + """Parse sxd file. + + Return an index object. + """ index_file = open(filename) data = [] for line in index_file: @@ -53,13 +52,15 @@ def processSXD(filename): idx.compileKeywords() for i in range(i, len(data), 3): - entry = processSXDEntry(data[i:i + 3]) + entry = data[i:i + 3] idx.add(entry[0], entry[1], entry[2]) return idx class index: + """Title, author or scripture index representation.""" + def __init__(self, indextype): self.data = dict() self.keywords = dict() diff --git a/songbook/plastex-patchedbabel.py b/songbook/plastex-patchedbabel.py index 5d39fa62..44dbd53c 100644 --- a/songbook/plastex-patchedbabel.py +++ b/songbook/plastex-patchedbabel.py @@ -43,6 +43,9 @@ Louis from plasTeX import Command class selectlanguage(Command): + """Patch of vanilla selectlanguage class. + + See module docstring for more information.""" args = 'lang:str' def invoke(self, tex): diff --git a/songbook/plastex-songs.py b/songbook/plastex-songs.py index beb3f615..6ec14b47 100644 --- a/songbook/plastex-songs.py +++ b/songbook/plastex-songs.py @@ -1,12 +1,25 @@ #!/usr/bin/env python # -*- coding: utf-8 -*- +"""Module to process song LaTeX environment. +""" + import plasTeX from songbook.plastex import processUnbreakableSpace def split_linebreak(texlist): + """Return a list of alternative title. + + A title can be defined with alternative names : + + A real name\\ + Alternative name\\ + Another alternative name + + This function takes the object representation of a list of titles, and return a list of titles. + """ return_list = [] current = [] for token in texlist: @@ -21,8 +34,13 @@ def split_linebreak(texlist): class beginsong(plasTeX.Command): + """Class parsing the LaTeX song environment.""" + args = '{titles}[ args:dict ]' + def invoke(self, tex): + """Parse an occurence of song environment.""" + plasTeX.Command.invoke(self, tex) # Parsing title diff --git a/songbook/plastex.py b/songbook/plastex.py index 5ba9a55d..d43c4ecb 100755 --- a/songbook/plastex.py +++ b/songbook/plastex.py @@ -1,6 +1,8 @@ #!/usr/bin/env python # -*- coding: utf-8 -*- +"""PlasTeX module to process song files.""" + from plasTeX.TeX import TeX from plasTeX.Base.LaTeX import Sentences @@ -40,6 +42,7 @@ class SongParser: @staticmethod def _create_TeX(): + """Create a TeX object, ready to parse a tex file.""" tex = TeX() tex.disableLogging() tex.ownerDocument.context.loadBaseMacros() @@ -51,6 +54,7 @@ class SongParser: @classmethod def parse(cls, filename): + """Parse a TeX file, and return its plasTeX representation.""" tex = cls._create_TeX() tex.input(codecs.open(filename, 'r+', 'utf-8', 'replace')) return tex.parse() diff --git a/songbook/songs.py b/songbook/songs.py index 943c6c7d..409f8b48 100644 --- a/songbook/songs.py +++ b/songbook/songs.py @@ -1,6 +1,8 @@ #!/usr/bin/env python # -*- coding: utf-8 -*- +"""Song management.""" + from unidecode import unidecode import glob import locale @@ -12,6 +14,8 @@ from songbook.plastex import parsetex class Song: + """Song management""" + #: Ordre de tri sort = [] #: Préfixes à ignorer pour le tri par titres