From 8e7f4a71ac53b270c26cc1bb7b5846c13c1fb9da Mon Sep 17 00:00:00 2001 From: Louis Date: Thu, 27 Feb 2014 21:16:55 +0100 Subject: [PATCH] More Pylint formatting. Almost done! (#4) --- readme.md | 4 +- songbook.py => songbook | 10 +- {songbook => songbook_core}/__init__.py | 2 + {songbook => songbook_core}/authors.py | 144 +++++++++++------ {songbook => songbook_core}/build.py | 150 ++++++++++-------- {songbook => songbook_core}/errors.py | 16 +- {songbook => songbook_core}/files.py | 4 +- {songbook => songbook_core}/index.py | 48 +++--- {songbook => songbook_core}/plastex.py | 19 ++- .../plastex_patchedbabel.py | 12 +- .../plastex_songs.py | 12 +- {songbook => songbook_core}/songs.py | 25 +-- 12 files changed, 274 insertions(+), 172 deletions(-) rename songbook.py => songbook (90%) rename {songbook => songbook_core}/__init__.py (90%) rename {songbook => songbook_core}/authors.py (66%) rename {songbook => songbook_core}/build.py (63%) rename {songbook => songbook_core}/errors.py (54%) rename {songbook => songbook_core}/files.py (78%) rename {songbook => songbook_core}/index.py (82%) rename {songbook => songbook_core}/plastex.py (88%) rename songbook/plastex-patchedbabel.py => songbook_core/plastex_patchedbabel.py (82%) rename songbook/plastex-songs.py => songbook_core/plastex_songs.py (80%) rename {songbook => songbook_core}/songs.py (88%) diff --git a/readme.md b/readme.md index a307fd33..55a97355 100644 --- a/readme.md +++ b/readme.md @@ -20,12 +20,12 @@ is precised in the header. # Run -> /songbook.py +> /songbook > Look for existing songbook files in /books. For example: -> /songbook.py /books/songbook_en.sb +> /songbook /books/songbook_en.sb > songbook_en.pdf diff --git a/songbook.py b/songbook similarity index 90% rename from songbook.py rename to songbook index b27a05af..43b0d7ce 100755 --- a/songbook.py +++ b/songbook @@ -12,9 +12,9 @@ import os.path import textwrap import sys -from songbook.build import buildsongbook -from songbook import __VERSION__ -from songbook import errors +from songbook_core.build import buildsongbook +from songbook_core import __VERSION__ +from songbook_core import errors def argument_parser(args): @@ -43,7 +43,7 @@ def main(): """Main function:""" # Logging configuration - logging.basicConfig(name = 'songbook') + logging.basicConfig(name='songbook') logger = logging.getLogger('songbook') # set script locale to match user's @@ -72,7 +72,7 @@ def main(): else: songbook['datadir'] = os.path.dirname(songbook_path) try: - buildsongbook(songbook, basename, interactive = True, logger = logger) + buildsongbook(songbook, basename, interactive=True, logger=logger) except errors.SongbookError as error: logger.error(error) sys.exit(1) diff --git a/songbook/__init__.py b/songbook_core/__init__.py similarity index 90% rename from songbook/__init__.py rename to songbook_core/__init__.py index afaf37ac..b580af8b 100644 --- a/songbook/__init__.py +++ b/songbook_core/__init__.py @@ -1,3 +1,5 @@ +"""Global variables.""" + import os __VERSION__ = "3.7.2" diff --git a/songbook/authors.py b/songbook_core/authors.py similarity index 66% rename from songbook/authors.py rename to songbook_core/authors.py index 2e5ba4da..cea20439 100644 --- a/songbook/authors.py +++ b/songbook_core/authors.py @@ -52,43 +52,15 @@ def split_sep_author(string, sep): authors.append(string) return authors +################################################################################ +### Process authors tools. +################################################################################ -def processauthors(authors_string, after=[], ignore=[], sep=[]): - r"""Return a list of authors - - For example, we are processing: - # processauthors( - # "Lyrics by William Blake (from Milton, 1808), - music by Hubert Parry (1916), - and sung by The Royal\ Choir~of~Nowhere - (just here to show you how processing is done)", - # after = ["by"], - # ignore = ["anonymous"], - # sep = [re.compile('^(.*) and (.*)$')], - # ) - - - The "authors_string" string is processed as: - - 1) First, parenthesis (and its content) are removed. - # "Lyrics by William Blake, music by Hubert Parry, - and sung by The Royal\ Choir~of~Nowhere" - - 2) String is split, separators being comma and words from "sep". - # ["Lyrics by William Blake", "music by Hubert Parry", - "sung by The Royal\ Choir~of~Nowhere"] - - 3) Everything before words in "after" is removed. - # ["William Blake", "Hubert Parry", "The Royal\ Choir~of~Nowhere"] +def processauthors_removeparen(authors_string): + """Remove parentheses - 4) Strings containing words of "ignore" are dropped. - # ["William Blake", "Hubert Parry", The Royal\ Choir~of~Nowhere"] - - 5) First names are moved after last names - # ["Blake, William", "Parry, Hubert", Royal\ Choir~of~Nowhere, The"] + See docstring of processauthors() for more information. """ - - # Removing parentheses opening = 0 dest = "" for char in authors_string: @@ -98,17 +70,26 @@ def processauthors(authors_string, after=[], ignore=[], sep=[]): opening -= 1 elif opening == 0: dest += char - authors_string = dest + return dest + +def processauthors_split_string(authors_string, sep): + """Split strings - # Splitting strings + See docstring of processauthors() for more information. + """ authors_list = [authors_string] for sepword in sep: dest = [] for author in authors_list: dest.extend(split_sep_author(author, sepword)) authors_list = dest + return authors_list - # Removing stuff before "after" +def processauthors_remove_after(authors_list, after): + """Remove stuff before "after" + + See docstring of processauthors() for more information. + """ dest = [] for author in authors_list: for afterword in after: @@ -117,9 +98,13 @@ def processauthors(authors_string, after=[], ignore=[], sep=[]): author = match.group(1) break dest.append(author) - authors_list = dest + return dest + +def processauthors_ignore_authors(authors_list, ignore): + """Ignore ignored authors - # Ignoring ignored authors + See docstring of processauthors() for more information. + """ dest = [] for author in authors_list: ignored = False @@ -129,13 +114,25 @@ def processauthors(authors_string, after=[], ignore=[], sep=[]): break if not ignored: dest.append(author) - authors_list = dest + return dest - # Cleaning: removing empty authors and unnecessary spaces - authors_list = [author.lstrip() - for author in authors_list if author.lstrip()] +def processauthors_clean_authors(authors_list): + """Clean: remove empty authors and unnecessary spaces - # Moving first names after last names + See docstring of processauthors() for more information. + """ + return [ + author.lstrip() + for author + in authors_list + if author.lstrip() + ] + +def processauthors_invert_names(authors_list): + """Move first names after last names + + See docstring of processauthors() for more information. + """ dest = [] for author in authors_list: first, last = split_author_names(author) @@ -146,6 +143,61 @@ def processauthors(authors_string, after=[], ignore=[], sep=[]): }) else: dest.append(last.lstrip()) - authors_list = dest + return dest + +def processauthors(authors_string, after=None, ignore=None, sep=None): + r"""Return a list of authors + + For example, we are processing: + # processauthors( + # "Lyrics by William Blake (from Milton, 1808), + music by Hubert Parry (1916), + and sung by The Royal\ Choir~of~Nowhere + (just here to show you how processing is done)", + # after = ["by"], + # ignore = ["anonymous"], + # sep = [re.compile('^(.*) and (.*)$')], + # ) + + + The "authors_string" string is processed as: + + 1) First, parenthesis (and its content) are removed. + # "Lyrics by William Blake, music by Hubert Parry, + and sung by The Royal\ Choir~of~Nowhere" + + 2) String is split, separators being comma and words from "sep". + # ["Lyrics by William Blake", "music by Hubert Parry", + "sung by The Royal\ Choir~of~Nowhere"] + + 3) Everything before words in "after" is removed. + # ["William Blake", "Hubert Parry", "The Royal\ Choir~of~Nowhere"] + + 4) Strings containing words of "ignore" are dropped. + # ["William Blake", "Hubert Parry", The Royal\ Choir~of~Nowhere"] + + 5) First names are moved after last names + # ["Blake, William", "Parry, Hubert", Royal\ Choir~of~Nowhere, The"] + """ + + if not sep: + sep = [] + if not after: + after = [] + if not ignore: + ignore = [] + + return processauthors_invert_names( + processauthors_clean_authors( + processauthors_ignore_authors( + processauthors_remove_after( + processauthors_split_string( + processauthors_removeparen( + authors_string + ), + sep), + after), + ignore) + ) + ) - return authors_list diff --git a/songbook/build.py b/songbook_core/build.py similarity index 63% rename from songbook/build.py rename to songbook_core/build.py index 5d9acafa..8bb6fb02 100755 --- a/songbook/build.py +++ b/songbook_core/build.py @@ -10,26 +10,25 @@ import logging import os.path import re import subprocess -import sys -from songbook import __SHAREDIR__ -from songbook import errors -from songbook.files import recursiveFind -from songbook.index import processSXD -from songbook.songs import Song, SongsList +from songbook_core import __SHAREDIR__ +from songbook_core import errors +from songbook_core.files import recursive_find +from songbook_core.index import process_sxd +from songbook_core.songs import Song, SongsList EOL = "\n" -def parseTemplate(template): +def parse_template(template): """Return the list of parameters defined in the template.""" - embeddedJsonPattern = re.compile(r"^%%:") + embedded_json_pattern = re.compile(r"^%%:") with open(template) as template_file: code = [ line[3:-1] for line in template_file - if embeddedJsonPattern.match(line) + if embedded_json_pattern.match(line) ] data = json.loads(''.join(code)) @@ -39,15 +38,16 @@ def parseTemplate(template): return parameters -def toValue(parameter, data): +# pylint: disable=too-many-return-statements +def to_value(parameter, data): if "type" not in parameter: return data elif parameter["type"] == "stringlist": if "join" in parameter: - joinText = parameter["join"] + join_text = parameter["join"] else: - joinText = '' - return joinText.join(data) + join_text = '' + return join_text.join(data) elif parameter["type"] == "color": return data[1:] elif parameter["type"] == "font": @@ -58,24 +58,24 @@ def toValue(parameter, data): return data elif parameter["type"] == "flag": if "join" in parameter: - joinText = parameter["join"] + join_text = parameter["join"] else: - joinText = '' - return joinText.join(data) + join_text = '' + return join_text.join(data) -def formatDeclaration(name, parameter): +def format_declaration(name, parameter): value = "" if "default" in parameter: value = parameter["default"] return ( r'\def\set@{name}#1{{\def\get{name}{{#1}}}}'.format(name=name) + EOL - + formatDefinition(name, toValue(parameter, value)) + + format_definition(name, to_value(parameter, value)) ) -def formatDefinition(name, value): +def format_definition(name, value): return r'\set@{name}{{{value}}}'.format(name=name, value=value) + EOL @@ -103,9 +103,9 @@ def clean(basename): raise errors.CleaningError(basename + ext, exception) -def makeTexFile(sb, output): +def make_tex_file(songbook, output): """Create the LaTeX file corresponding to the .sb file given in argument.""" - datadir = sb['datadir'] + datadir = songbook['datadir'] name = output[:-4] template_dir = os.path.join(datadir, 'templates') songs = [] @@ -117,33 +117,33 @@ def makeTexFile(sb, output): authwords = {"after": ["by"], "ignore": ["unknown"], "sep": ["and"]} # parse the songbook data - if "template" in sb: - template = sb["template"] - del sb["template"] + if "template" in songbook: + template = songbook["template"] + del songbook["template"] else: template = os.path.join(__SHAREDIR__, "templates", "default.tmpl") - if "songs" in sb: - songs = sb["songs"] - del sb["songs"] - if "titleprefixwords" in sb: - prefixes = sb["titleprefixwords"] - for prefix in sb["titleprefixwords"]: + if "songs" in songbook: + songs = songbook["songs"] + del songbook["songs"] + if "titleprefixwords" in songbook: + prefixes = songbook["titleprefixwords"] + for prefix in songbook["titleprefixwords"]: prefixes_tex += r"\titleprefixword{%s}" % prefix + EOL - sb["titleprefixwords"] = prefixes_tex - if "authwords" in sb: + songbook["titleprefixwords"] = prefixes_tex + if "authwords" in songbook: # Populating default value for key in ["after", "sep", "ignore"]: - if key not in sb["authwords"]: - sb["authwords"][key] = authwords[key] + if key not in songbook["authwords"]: + songbook["authwords"][key] = authwords[key] # Processing authwords values - authwords = sb["authwords"] + authwords = songbook["authwords"] for key in ["after", "sep", "ignore"]: for word in authwords[key]: if key == "after": authwords_tex += r"\auth%sword{%s}" % ("by", word) + EOL else: authwords_tex += r"\auth%sword{%s}" % (key, word) + EOL - sb["authwords"] = authwords_tex + songbook["authwords"] = authwords_tex if "after" in authwords: authwords["after"] = [re.compile(r"^.*%s\b(.*)" % after) for after in authwords["after"]] @@ -152,52 +152,55 @@ def makeTexFile(sb, output): authwords["sep"] = [re.compile(r"^(.*)%s (.*)$" % sep) for sep in authwords["sep"]] - if "lang" not in sb: - sb["lang"] = "french" - if "sort" in sb: - sort = sb["sort"] - del sb["sort"] + if "lang" not in songbook: + songbook["lang"] = "french" + if "sort" in songbook: + sort = songbook["sort"] + del songbook["sort"] else: sort = [u"by", u"album", u"@title"] Song.sort = sort Song.prefixes = prefixes Song.authwords = authwords - parameters = parseTemplate(os.path.join(template_dir, template)) + parameters = parse_template(os.path.join(template_dir, template)) # compute songslist if songs == "all": songs = [ os.path.relpath(filename, os.path.join(datadir, 'songs')) for filename - in recursiveFind(os.path.join(datadir, 'songs'), '*.sg') + in recursive_find(os.path.join(datadir, 'songs'), '*.sg') ] - songslist = SongsList(datadir, sb["lang"]) + songslist = SongsList(datadir, songbook["lang"]) songslist.append_list(songs) - sb["languages"] = ",".join(songslist.languages()) + songbook["languages"] = ",".join(songslist.languages()) # output relevant fields out = codecs.open(output, 'w', 'utf-8') out.write('%% This file has been automatically generated, do not edit!\n') out.write(r'\makeatletter' + EOL) # output automatic parameters - out.write(formatDeclaration("name", {"default": name})) - out.write(formatDeclaration("songslist", {"type": "stringlist"})) + out.write(format_declaration("name", {"default": name})) + out.write(format_declaration("songslist", {"type": "stringlist"})) # output template parameter command for name, parameter in parameters.iteritems(): - out.write(formatDeclaration(name, parameter)) + out.write(format_declaration(name, parameter)) # output template parameter values - for name, value in sb.iteritems(): + for name, value in songbook.iteritems(): if name in parameters: - out.write(formatDefinition(name, toValue(parameters[name], value))) + out.write(format_definition( + name, + to_value(parameters[name], value), + )) if len(songs) > 0: - out.write(formatDefinition('songslist', songslist.latex())) + out.write(format_definition('songslist', songslist.latex())) out.write(r'\makeatother' + EOL) # output template - commentPattern = re.compile(r"^\s*%") + comment_pattern = re.compile(r"^\s*%") with codecs.open( os.path.join(template_dir, template), 'r', 'utf-8' ) as template_file: @@ -205,7 +208,7 @@ def makeTexFile(sb, output): line for line in template_file - if not commentPattern.match(line) + if not comment_pattern.match(line) ] for index, line in enumerate(content): @@ -225,24 +228,35 @@ def makeTexFile(sb, output): out.write(u''.join(content)) out.close() -def buildsongbook(sb, basename, interactive = False, logger = logging.getLogger()): +def buildsongbook( + songbook, + basename, + interactive=False, + logger=logging.getLogger() + ): """Build a songbook Arguments: - - sb: Python representation of the .sb songbook configuration file. + - songbook: Python representation of the .sb songbook configuration file. - basename: basename of the songbook to be built. - interactive: in False, do not expect anything from stdin. """ - texFile = basename + ".tex" + tex_file = basename + ".tex" # Make TeX file - makeTexFile(sb, texFile) + make_tex_file(songbook, tex_file) if not 'TEXINPUTS' in os.environ.keys(): os.environ['TEXINPUTS'] = '' - os.environ['TEXINPUTS'] += os.pathsep + os.path.join(__SHAREDIR__, 'latex') - os.environ['TEXINPUTS'] += os.pathsep + os.path.join(sb['datadir'], 'latex') + os.environ['TEXINPUTS'] += os.pathsep + os.path.join( + __SHAREDIR__, + 'latex', + ) + os.environ['TEXINPUTS'] += os.pathsep + os.path.join( + songbook['datadir'], + 'latex', + ) # pdflatex options pdflatex_options = [] @@ -251,20 +265,20 @@ def buildsongbook(sb, basename, interactive = False, logger = logging.getLogger( pdflatex_options.append("-halt-on-error") # First pdflatex pass - if subprocess.call(["pdflatex"] + pdflatex_options + [texFile]): + if subprocess.call(["pdflatex"] + pdflatex_options + [tex_file]): raise errors.LatexCompilationError(basename) # Make index - sxdFiles = glob.glob("%s_*.sxd" % basename) - for sxdFile in sxdFiles: - logger.info("processing " + sxdFile) - idx = processSXD(sxdFile) - indexFile = open(sxdFile[:-3] + "sbx", "w") - indexFile.write(idx.entriesToStr().encode('utf8')) - indexFile.close() + sxd_files = glob.glob("%s_*.sxd" % basename) + for sxd_file in sxd_files: + logger.info("processing " + sxd_file) + idx = process_sxd(sxd_file) + index_file = open(sxd_file[:-3] + "sbx", "w") + index_file.write(idx.entries_to_str().encode('utf8')) + index_file.close() # Second pdflatex pass - if subprocess.call(["pdflatex"] + pdflatex_options + [texFile]): + if subprocess.call(["pdflatex"] + pdflatex_options + [tex_file]): raise errors.LatexCompilationError(basename) # Cleaning diff --git a/songbook/errors.py b/songbook_core/errors.py similarity index 54% rename from songbook/errors.py rename to songbook_core/errors.py index 41a17f60..7a231042 100644 --- a/songbook/errors.py +++ b/songbook_core/errors.py @@ -4,23 +4,35 @@ """Songbook exceptions and errors.""" class SongbookError(Exception): + """Generic songbook error. + + Songbook errors should inherit from this one. + """ pass class LatexCompilationError(SongbookError): """Error during LaTeX compilation.""" def __init__(self, basename): + super(LatexCompilationError, self).__init__() self.basename = basename def __str__(self): - return """Error while pdfLaTeX compilation of "{basename}.tex" (see {basename}.log for more information).""".format(basename = self.basename) + return ( + """Error while pdfLaTeX compilation of "{basename}.tex" + (see {basename}.log for more information).""" + ).format(basename=self.basename) class CleaningError(SongbookError): """Error during cleaning of LaTeX auxiliary files.""" def __init__(self, filename, exception): + super(CleaningError, self).__init__() self.filename = filename self.exception = exception def __str__(self): - return """Error while removing "{filename}": {exception}.""".format(filename = self.filename, exception = str(self.exception)) + return """Error while removing "{filename}": {exception}.""".format( + filename=self.filename, + exception=str(self.exception) + ) diff --git a/songbook/files.py b/songbook_core/files.py similarity index 78% rename from songbook/files.py rename to songbook_core/files.py index 0f070617..65acc153 100644 --- a/songbook/files.py +++ b/songbook_core/files.py @@ -7,13 +7,13 @@ import fnmatch import os -def recursiveFind(root_directory, pattern): +def recursive_find(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 root, _, filenames in os.walk(root_directory): for filename in fnmatch.filter(filenames, pattern): matches.append(os.path.join(root, filename)) return matches diff --git a/songbook/index.py b/songbook_core/index.py similarity index 82% rename from songbook/index.py rename to songbook_core/index.py index 468bcdd7..2deb0d61 100644 --- a/songbook/index.py +++ b/songbook_core/index.py @@ -13,14 +13,14 @@ import locale import re import sys -from songbook.authors import processauthors -from songbook.plastex import simpleparse +from songbook_core.authors import processauthors +from songbook_core.plastex import simpleparse EOL = "\n" # Pattern set to ignore latex command in title prefix -keywordPattern = re.compile(r"^%(\w+)\s?(.*)$") -firstLetterPattern = re.compile(r"^(?:\{?\\\w+\}?)*[^\w]*(\w)") +KEYWORD_PATTERN = re.compile(r"^%(\w+)\s?(.*)$") +FIRST_LETTER_PATTERN = re.compile(r"^(?:\{?\\\w+\}?)*[^\w]*(\w)") def sortkey(value): @@ -32,7 +32,7 @@ def sortkey(value): return locale.strxfrm(unidecode(simpleparse(value).replace(' ', 'A'))) -def processSXD(filename): +def process_sxd(filename): """Parse sxd file. Return an Index object. @@ -47,11 +47,11 @@ def processSXD(filename): idx = Index(data[0]) while len(data) > i and data[i].startswith('%'): - keywords = keywordPattern.match(data[i]).groups() + keywords = KEYWORD_PATTERN.match(data[i]).groups() idx.keyword(keywords[0], keywords[1]) i += 1 - idx.compileKeywords() + idx.compile_keywords() for i in range(i, len(data), 3): entry = data[i:i + 3] idx.add(entry[0], entry[1], entry[2]) @@ -59,7 +59,7 @@ def processSXD(filename): return idx -class Index: +class Index(object): """Title, author or scripture Index representation.""" def __init__(self, indextype): @@ -76,9 +76,10 @@ class Index: else: self.indextype = "" - def filter(self, key): - letter = firstLetterPattern.match(key).group(1) - if re.match('\d', letter): + @staticmethod + def filter(key): + letter = FIRST_LETTER_PATTERN.match(key).group(1) + if re.match(r'\d', letter): letter = '0-9' return (letter.upper(), key) @@ -87,7 +88,7 @@ class Index: self.keywords[key] = [] self.keywords[key].append(word) - def compileKeywords(self): + def compile_keywords(self): if self.indextype == "TITLE": if 'prefix' in self.keywords: for prefix in self.keywords['prefix']: @@ -146,27 +147,34 @@ class Index: **self.authwords): self._raw_add(author, number, link) - def refToStr(self, ref): + @staticmethod + def ref_to_str(ref): if sys.version_info >= (2, 6): return r'\hyperlink{{{0[link]}}}{{{0[num]}}}'.format(ref) else: return r'\hyperlink{%(link)s}{%(num)s}' % ref - def entryToStr(self, key, entry): + def entry_to_str(self, key, entry): if sys.version_info >= (2, 6): - return unicode(r'\idxentry{{{0}}}{{{1}}}' + EOL).format(key, r'\\'.join(map(self.refToStr, entry))) + return unicode(r'\idxentry{{{0}}}{{{1}}}' + EOL).format( + key, + r'\\'.join([self.ref_to_str(ref) for ref in entry]), + ) else: - return unicode(r'\idxentry{%s}{%s}' + EOL) % (key, r'\\'.join(map(self.refToStr, entry))) + return unicode(r'\idxentry{%s}{%s}' + EOL) % ( + key, + r'\\'.join([self.ref_to_str(ref) for ref in entry]), + ) - def idxBlockToStr(self, letter, entries): + def idxblock_to_str(self, letter, entries): string = r'\begin{idxblock}{' + letter + '}' + EOL for key in sorted(entries.keys(), key=sortkey): - string += self.entryToStr(key, entries[key]) + string += self.entry_to_str(key, entries[key]) string += r'\end{idxblock}' + EOL return string - def entriesToStr(self): + def entries_to_str(self): string = "" for letter in sorted(self.data.keys()): - string += self.idxBlockToStr(letter, self.data[letter]) + string += self.idxblock_to_str(letter, self.data[letter]) return string diff --git a/songbook/plastex.py b/songbook_core/plastex.py similarity index 88% rename from songbook/plastex.py rename to songbook_core/plastex.py index fc486341..6b921d0b 100755 --- a/songbook/plastex.py +++ b/songbook_core/plastex.py @@ -12,7 +12,7 @@ import os import sys -def processUnbreakableSpace(node): +def process_unbr_spaces(node): r"""Replace '~' and '\ ' in node by nodes that will be rendered as unbreakable space. @@ -22,7 +22,7 @@ def processUnbreakableSpace(node): (type(node) == Sentences.NoLineBreak and node.source == '~ ')): node.unicode = unichr(160) for child in node.childNodes: - processUnbreakableSpace(child) + process_unbr_spaces(child) return node @@ -33,28 +33,31 @@ def simpleparse(text): tex = TeX() tex.input(text.decode('utf8')) doc = tex.parse() - return processUnbreakableSpace(doc.textContent) + return process_unbr_spaces(doc.textContent) -class SongParser: +class SongParser(object): """Analyseur syntaxique de fichiers .sg""" + def __init__(self): + pass + @staticmethod - def _create_TeX(): + def create_tex(): """Create a TeX object, ready to parse a tex file.""" tex = TeX() tex.disableLogging() tex.ownerDocument.context.loadBaseMacros() sys.path.append(os.path.dirname(__file__)) - tex.ownerDocument.context.loadPackage(tex, "plastex-patchedbabel") - tex.ownerDocument.context.loadPackage(tex, "plastex-songs") + tex.ownerDocument.context.loadPackage(tex, "plastex_patchedbabel") + tex.ownerDocument.context.loadPackage(tex, "plastex_songs") sys.path.pop() return tex @classmethod 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')) return tex.parse() diff --git a/songbook/plastex-patchedbabel.py b/songbook_core/plastex_patchedbabel.py similarity index 82% rename from songbook/plastex-patchedbabel.py rename to songbook_core/plastex_patchedbabel.py index 44dbd53c..2f3b159a 100644 --- a/songbook/plastex-patchedbabel.py +++ b/songbook_core/plastex_patchedbabel.py @@ -1,7 +1,7 @@ #!/usr/bin/env python # -*- coding: utf-8 -*- -"""Patch pour le paquet Babel de PlasTeX +r"""Patch pour le paquet Babel de PlasTeX Un bug dans PlasTeX intervient lorsqu'on essaye d'analyser une commande LaTeX \selectlanguage{}, que nous voulons utiliser ici. Un patch a été proposé aux @@ -27,8 +27,8 @@ trop gros. > Traceback (most recent call last): > [...] -> File "/usr/lib/pymodules/python2.7/plasTeX/Packages/babel.py", line 18, in invoke -> context.loadLanguage(self.attributes['lang'], self.ownerDocument) +> File "/usr/lib/pymodules/python2.7/plasTeX/Packages/babel.py", line 18, in +> invoke context.loadLanguage(self.attributes['lang'], self.ownerDocument) > NameError: global name 'context' is not defined 3 bis) Si elle n'apparait pas : youpi ! Supprimez ce fichier ! @@ -42,6 +42,7 @@ Louis from plasTeX import Command +# pylint: disable=invalid-name,too-many-public-methods class selectlanguage(Command): """Patch of vanilla selectlanguage class. @@ -50,5 +51,8 @@ class selectlanguage(Command): def invoke(self, tex): res = Command.invoke(self, tex) - self.ownerDocument.context.loadLanguage(self.attributes['lang'], self.ownerDocument) + self.ownerDocument.context.loadLanguage( # pylint: disable=no-member + self.attributes['lang'], + self.ownerDocument + ) return res diff --git a/songbook/plastex-songs.py b/songbook_core/plastex_songs.py similarity index 80% rename from songbook/plastex-songs.py rename to songbook_core/plastex_songs.py index 6ec14b47..9e39da1f 100644 --- a/songbook/plastex-songs.py +++ b/songbook_core/plastex_songs.py @@ -6,7 +6,7 @@ import plasTeX -from songbook.plastex import processUnbreakableSpace +from songbook_core.plastex import process_unbr_spaces def split_linebreak(texlist): @@ -18,7 +18,8 @@ def split_linebreak(texlist): Alternative name\\ Another alternative name - This function takes the object representation of a list of titles, and return a list of titles. + This function takes the object representation of a list of titles, and + return a list of titles. """ return_list = [] current = [] @@ -27,13 +28,14 @@ def split_linebreak(texlist): return_list.append(current) current = [] else: - current.append(processUnbreakableSpace(token).textContent.encode('utf-8')) + current.append( + process_unbr_spaces(token).textContent.encode('utf-8')) if current: return_list.append(current) return return_list -class beginsong(plasTeX.Command): +class beginsong(plasTeX.Command): # pylint: disable=invalid-name,too-many-public-methods """Class parsing the LaTeX song environment.""" args = '{titles}[ args:dict ]' @@ -53,7 +55,7 @@ class beginsong(plasTeX.Command): args = {} for (key, val) in self.attributes['args'].iteritems(): if isinstance(val, plasTeX.DOM.Element): - args[key] = processUnbreakableSpace(val).textContent.encode('utf-8') + args[key] = process_unbr_spaces(val).textContent.encode('utf-8') elif isinstance(val, unicode): args[key] = val.encode('utf-8') elif isinstance(val, str): diff --git a/songbook/songs.py b/songbook_core/songs.py similarity index 88% rename from songbook/songs.py rename to songbook_core/songs.py index 3b39f3de..f6ba4942 100644 --- a/songbook/songs.py +++ b/songbook_core/songs.py @@ -9,11 +9,12 @@ import locale import os.path import re -from songbook.authors import processauthors -from songbook.plastex import parsetex +from songbook_core.authors import processauthors +from songbook_core.plastex import parsetex -class Song: +# pylint: disable=too-few-public-methods +class Song(object): """Song management""" #: Ordre de tri @@ -25,12 +26,16 @@ class Song: def __init__(self, path, languages, titles, args): self.titles = titles - self.normalized_titles = [locale.strxfrm( - unprefixed_title(unidecode(unicode(title, "utf-8")), - self.prefixes - ) - ) - for title in titles] + self.normalized_titles = [ + locale.strxfrm( + unprefixed_title( + unidecode(unicode(title, "utf-8")), + self.prefixes + ) + ) + for title + in titles + ] self.args = args self.path = path self.languages = languages @@ -80,7 +85,7 @@ def unprefixed_title(title, prefixes): return title -class SongsList: +class SongsList(object): """Manipulation et traitement de liste de chansons""" def __init__(self, library, language):