Browse Source

Added docstrings

pull/3/head
Louis 11 years ago
parent
commit
0718ff1e59
  1. 5
      songbook.py
  2. 7
      songbook/__init__.py
  3. 17
      songbook/authors.py
  4. 38
      songbook/build.py
  5. 7
      songbook/files.py
  6. 27
      songbook/index.py
  7. 3
      songbook/plastex-patchedbabel.py
  8. 18
      songbook/plastex-songs.py
  9. 4
      songbook/plastex.py
  10. 4
      songbook/songs.py

5
songbook.py

@ -2,6 +2,8 @@
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
# #
"""Command line tool to compile songbooks using the songbook library."""
import argparse import argparse
import json import json
import locale import locale
@ -14,6 +16,7 @@ from songbook import __VERSION__
def argument_parser(args): def argument_parser(args):
"""Parse argumnts"""
parser = argparse.ArgumentParser(description="A song book compiler") parser = argparse.ArgumentParser(description="A song book compiler")
parser.add_argument('--version', help='Show version', action='version', parser.add_argument('--version', help='Show version', action='version',
@ -35,6 +38,8 @@ def argument_parser(args):
def main(): def main():
"""Main function:"""
# set script locale to match user's # set script locale to match user's
try: try:
locale.setlocale(locale.LC_ALL, '') locale.setlocale(locale.LC_ALL, '')

7
songbook/__init__.py

@ -2,5 +2,8 @@ import os
__VERSION__ = "3.7.2" __VERSION__ = "3.7.2"
# Directory containing shared data (default templates, custom LaTeX packages, etc.) # Directory containing shared data (default templates, custom LaTeX packages,
__SHAREDIR__ = os.path.abspath(os.path.join(os.path.dirname(__file__), "..", "share")) # etc.)
__SHAREDIR__ = os.path.abspath(
os.path.join(os.path.dirname(__file__), "..", "share")
)

17
songbook/authors.py

@ -1,9 +1,10 @@
#!/usr/bin/env python #!/usr/bin/env python
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
"""Authors string management."""
def split_author_names(string): 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 The last space separates first and last name, but spaces following a
backslash or a command are not separators. backslash or a command are not separators.
@ -33,6 +34,15 @@ def split_author_names(string):
def split_sep_author(string, sep): 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 = [] authors = []
match = sep.match(string) match = sep.match(string)
while match: while match:
@ -44,7 +54,7 @@ def split_sep_author(string, sep):
def processauthors(authors_string, after=[], ignore=[], sep=[]): def processauthors(authors_string, after=[], ignore=[], sep=[]):
"""Return a list of authors r"""Return a list of authors
For example, we are processing: For example, we are processing:
# processauthors( # processauthors(
@ -54,9 +64,10 @@ def processauthors(authors_string, after=[], ignore=[], sep=[]):
(just here to show you how processing is done)", (just here to show you how processing is done)",
# after = ["by"], # after = ["by"],
# ignore = ["anonymous"], # ignore = ["anonymous"],
# sep = ["and"] # sep = [re.compile('^(.*) and (.*)$')],
# ) # )
The "authors_string" string is processed as: The "authors_string" string is processed as:
1) First, parenthesis (and its content) are removed. 1) First, parenthesis (and its content) are removed.

38
songbook/build.py

@ -1,6 +1,8 @@
#!/usr/bin/env python #!/usr/bin/env python
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
"""Build a songbook, according to parameters found in a .sb file."""
from subprocess import call from subprocess import call
import codecs import codecs
import glob import glob
@ -16,9 +18,15 @@ from songbook import __SHAREDIR__
def parseTemplate(template): def parseTemplate(template):
"""Return the list of parameters defined in the template."""
embeddedJsonPattern = re.compile(r"^%%:") embeddedJsonPattern = re.compile(r"^%%:")
with open(template) as template_file: 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)) data = json.loads(''.join(code))
parameters = dict() parameters = dict()
@ -56,7 +64,8 @@ def formatDeclaration(name, parameter):
value = "" value = ""
if "default" in parameter: if "default" in parameter:
value = parameter["default"] 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)) + formatDefinition(name, toValue(parameter, value))
) )
@ -66,6 +75,10 @@ def formatDefinition(name, value):
def clean(basename): 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 = [ generated_extensions = [
"_auth.sbx", "_auth.sbx",
"_auth.sxd", "_auth.sxd",
@ -85,6 +98,7 @@ def clean(basename):
def makeTexFile(sb, output): def makeTexFile(sb, output):
"""Create the LaTeX file corresponding to the .sb file given in argument."""
datadir = sb['datadir'] datadir = sb['datadir']
name = output[:-4] name = output[:-4]
template_dir = os.path.join(datadir, 'templates') template_dir = os.path.join(datadir, 'templates')
@ -178,13 +192,25 @@ def makeTexFile(sb, output):
# output template # output template
commentPattern = re.compile(r"^\s*%") commentPattern = re.compile(r"^\s*%")
with codecs.open(os.path.join(template_dir, template), 'r', 'utf-8') as template_file: with codecs.open(
content = [line for line in template_file if not commentPattern.match(line)] 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): for index, line in enumerate(content):
if re.compile("getDataImgDirectory").search(line): if re.compile("getDataImgDirectory").search(line):
if os.path.abspath(os.path.join(datadir, "img")).startswith(os.path.abspath(os.path.dirname(output))): if os.path.abspath(os.path.join(datadir, "img")).startswith(
imgdir = os.path.relpath(os.path.join(datadir, "img"), os.path.dirname(output)) os.path.abspath(os.path.dirname(output))
):
imgdir = os.path.relpath(
os.path.join(datadir, "img"),
os.path.dirname(output)
)
else: else:
imgdir = os.path.abspath(os.path.join(datadir, "img")) imgdir = os.path.abspath(os.path.join(datadir, "img"))
line = line.replace("\\getDataImgDirectory", ' {%s/} ' % imgdir) line = line.replace("\\getDataImgDirectory", ' {%s/} ' % imgdir)

7
songbook/files.py

@ -2,11 +2,16 @@
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
# #
"""File system utilities."""
import fnmatch import fnmatch
import os import os
def recursiveFind(root_directory, pattern): def recursiveFind(root_directory, pattern):
"""Recursively find files matching a pattern, from a root_directory.
Return a list of files matching the pattern.
"""
matches = [] matches = []
for root, dirnames, filenames in os.walk(root_directory): for root, dirnames, filenames in os.walk(root_directory):
for filename in fnmatch.filter(filenames, pattern): for filename in fnmatch.filter(filenames, pattern):

27
songbook/index.py

@ -1,13 +1,12 @@
#!/usr/bin/python #!/usr/bin/python
# -*- coding: utf-8 -*- # -*- 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 """Manage indexes.
# produces an index file (.sbx) from a file generated by the latex
# compilation of the songbook (.sxd). 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)
# Usage : songbook-makeindex.py src from a file generated by the latex compilation of the songbook (.sxd).
# src is the .sxd file generated by latex """
#
from unidecode import unidecode from unidecode import unidecode
import locale import locale
@ -32,11 +31,11 @@ def sortkey(value):
return locale.strxfrm(unidecode(simpleparse(value).replace(' ', 'A'))) return locale.strxfrm(unidecode(simpleparse(value).replace(' ', 'A')))
def processSXDEntry(tab):
return (tab[0], tab[1], tab[2])
def processSXD(filename): def processSXD(filename):
"""Parse sxd file.
Return an index object.
"""
index_file = open(filename) index_file = open(filename)
data = [] data = []
for line in index_file: for line in index_file:
@ -53,13 +52,15 @@ def processSXD(filename):
idx.compileKeywords() idx.compileKeywords()
for i in range(i, len(data), 3): 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]) idx.add(entry[0], entry[1], entry[2])
return idx return idx
class index: class index:
"""Title, author or scripture index representation."""
def __init__(self, indextype): def __init__(self, indextype):
self.data = dict() self.data = dict()
self.keywords = dict() self.keywords = dict()

3
songbook/plastex-patchedbabel.py

@ -43,6 +43,9 @@ Louis <spalax(at)gresille.org>
from plasTeX import Command from plasTeX import Command
class selectlanguage(Command): class selectlanguage(Command):
"""Patch of vanilla selectlanguage class.
See module docstring for more information."""
args = 'lang:str' args = 'lang:str'
def invoke(self, tex): def invoke(self, tex):

18
songbook/plastex-songs.py

@ -1,12 +1,25 @@
#!/usr/bin/env python #!/usr/bin/env python
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
"""Module to process song LaTeX environment.
"""
import plasTeX import plasTeX
from songbook.plastex import processUnbreakableSpace from songbook.plastex import processUnbreakableSpace
def split_linebreak(texlist): 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 = [] return_list = []
current = [] current = []
for token in texlist: for token in texlist:
@ -21,8 +34,13 @@ def split_linebreak(texlist):
class beginsong(plasTeX.Command): class beginsong(plasTeX.Command):
"""Class parsing the LaTeX song environment."""
args = '{titles}[ args:dict ]' args = '{titles}[ args:dict ]'
def invoke(self, tex): def invoke(self, tex):
"""Parse an occurence of song environment."""
plasTeX.Command.invoke(self, tex) plasTeX.Command.invoke(self, tex)
# Parsing title # Parsing title

4
songbook/plastex.py

@ -1,6 +1,8 @@
#!/usr/bin/env python #!/usr/bin/env python
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
"""PlasTeX module to process song files."""
from plasTeX.TeX import TeX from plasTeX.TeX import TeX
from plasTeX.Base.LaTeX import Sentences from plasTeX.Base.LaTeX import Sentences
@ -40,6 +42,7 @@ class SongParser:
@staticmethod @staticmethod
def _create_TeX(): def _create_TeX():
"""Create a TeX object, ready to parse a tex file."""
tex = TeX() tex = TeX()
tex.disableLogging() tex.disableLogging()
tex.ownerDocument.context.loadBaseMacros() tex.ownerDocument.context.loadBaseMacros()
@ -51,6 +54,7 @@ class SongParser:
@classmethod @classmethod
def parse(cls, filename): def parse(cls, filename):
"""Parse a TeX file, and return its plasTeX representation."""
tex = cls._create_TeX() tex = cls._create_TeX()
tex.input(codecs.open(filename, 'r+', 'utf-8', 'replace')) tex.input(codecs.open(filename, 'r+', 'utf-8', 'replace'))
return tex.parse() return tex.parse()

4
songbook/songs.py

@ -1,6 +1,8 @@
#!/usr/bin/env python #!/usr/bin/env python
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
"""Song management."""
from unidecode import unidecode from unidecode import unidecode
import glob import glob
import locale import locale
@ -12,6 +14,8 @@ from songbook.plastex import parsetex
class Song: class Song:
"""Song management"""
#: Ordre de tri #: Ordre de tri
sort = [] sort = []
#: Préfixes à ignorer pour le tri par titres #: Préfixes à ignorer pour le tri par titres

Loading…
Cancel
Save