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 -*-
#
"""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, '')

7
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")
)

17
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.

38
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)

7
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):

27
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()

3
songbook/plastex-patchedbabel.py

@ -43,6 +43,9 @@ Louis <spalax(at)gresille.org>
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):

18
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

4
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()

4
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

Loading…
Cancel
Save