Browse Source

Added a pylintrc file; made code pylint compliant

pull/75/head
Louis 10 years ago
parent
commit
a09d3f5256
  1. 2
      patacrep/content/section.py
  2. 3
      patacrep/content/song.py
  3. 6
      patacrep/content/tex.py
  4. 13
      patacrep/errors.py
  5. 4
      patacrep/files.py
  6. 39
      patacrep/latex/syntax.py
  7. 27
      patacrep/songbook.py
  8. 2
      patacrep/songs/chordpro/lexer.py
  9. 38
      patacrep/songs/chordpro/syntax.py
  10. 33
      patacrep/songs/syntax.py
  11. 9
      patacrep/templates.py
  12. 5
      pylintrc

2
patacrep/content/section.py

@ -48,7 +48,7 @@ def parse(keyword, argument, contentlist, config):
) )
if (len(contentlist) not in [1, 2]): if (len(contentlist) not in [1, 2]):
raise ContentError(keyword, "Section can have one or two arguments.") raise ContentError(keyword, "Section can have one or two arguments.")
return [Section(keyword, *contentlist)] #pylint: disable=star-args return [Section(keyword, *contentlist)]
CONTENT_PLUGINS = dict([ CONTENT_PLUGINS = dict([

3
patacrep/content/song.py

@ -67,7 +67,8 @@ def parse(keyword, argument, contentlist, config):
LOGGER.debug('Parsing file "{}"'.format(filename)) LOGGER.debug('Parsing file "{}"'.format(filename))
extension = filename.split(".")[-1] extension = filename.split(".")[-1]
if extension not in plugins: if extension not in plugins:
LOGGER.warning(( LOGGER.warning(
(
'I do not know how to parse "{}": name does ' 'I do not know how to parse "{}": name does '
'not end with one of {}. Ignored.' 'not end with one of {}. Ignored.'
).format( ).format(

6
patacrep/content/tex.py

@ -48,8 +48,10 @@ def parse(keyword, argument, contentlist, config):
)) ))
break break
if not checked_file: if not checked_file:
LOGGER.warning("{} Compilation may fail later.".format( LOGGER.warning(
errors.notfound(filename, basefolders)) "{} Compilation may fail later.".format(
errors.notfound(filename, basefolders)
)
) )
continue continue
filelist.append(LaTeX(checked_file)) filelist.append(LaTeX(checked_file))

13
patacrep/errors.py

@ -39,7 +39,8 @@ class LatexCompilationError(SongbookError):
self.basename = basename self.basename = basename
def __str__(self): def __str__(self):
return ("""Error while pdfLaTeX compilation of "{basename}.tex" """ return (
"""Error while pdfLaTeX compilation of "{basename}.tex" """
"""(see {basename}.log for more information).""" """(see {basename}.log for more information)."""
).format(basename=self.basename) ).format(basename=self.basename)
@ -79,6 +80,16 @@ class UnknownStep(SongbookError):
def __str__(self): def __str__(self):
return """Compilation step "{step}" unknown.""".format(step=self.step) return """Compilation step "{step}" unknown.""".format(step=self.step)
class ParsingError(SongbookError):
"""Parsing error."""
def __init__(self, message):
super().__init__(self)
self.message = message
def __str__(self):
return self.message
def notfound(filename, paths, message=None): def notfound(filename, paths, message=None):
"""Return a string saying that file was not found in paths.""" """Return a string saying that file was not found in paths."""
if message is None: if message is None:

4
patacrep/files.py

@ -50,7 +50,8 @@ def path2posix(string):
(head, tail) = os.path.split(string) (head, tail) = os.path.split(string)
return posixpath.join( return posixpath.join(
path2posix(head), path2posix(head),
tail) tail,
)
@contextmanager @contextmanager
def chdir(path): def chdir(path):
@ -87,7 +88,6 @@ def load_plugins(datadirs, root_modules, keyword):
- keys are the keywords ; - keys are the keywords ;
- values are functions triggered when this keyword is met. - values are functions triggered when this keyword is met.
""" """
# pylint: disable=star-args
plugins = {} plugins = {}
directory_list = ( directory_list = (
[ [

39
patacrep/latex/syntax.py

@ -3,52 +3,25 @@
import logging import logging
import ply.yacc as yacc import ply.yacc as yacc
from patacrep.songs.syntax import Parser
from patacrep.latex.lexer import tokens, SimpleLexer, SongLexer from patacrep.latex.lexer import tokens, SimpleLexer, SongLexer
from patacrep.latex import ast from patacrep.latex import ast
from patacrep.errors import SongbookError from patacrep.errors import ParsingError
from patacrep.latex.detex import detex from patacrep.latex.detex import detex
LOGGER = logging.getLogger() LOGGER = logging.getLogger()
class ParsingError(SongbookError):
"""Parsing error."""
def __init__(self, message):
super().__init__(self)
self.message = message
def __str__(self):
return self.message
# pylint: disable=line-too-long # pylint: disable=line-too-long
class Parser: class LatexParser(Parser):
"""LaTeX parser.""" """LaTeX parser."""
def __init__(self, filename=None): def __init__(self, filename=None):
super().__init__()
self.tokens = tokens self.tokens = tokens
self.ast = ast.AST self.ast = ast.AST
self.ast.init_metadata() self.ast.init_metadata()
self.filename = filename self.filename = filename
@staticmethod
def __find_column(token):
"""Return the column of ``token``."""
last_cr = token.lexer.lexdata.rfind('\n', 0, token.lexpos)
if last_cr < 0:
last_cr = 0
column = (token.lexpos - last_cr) + 1
return column
def p_error(self, token):
"""Manage parsing errors."""
LOGGER.error(
"Error in file {}, line {} at position {}.".format(
str(self.filename),
token.lineno,
self.__find_column(token),
)
)
@staticmethod @staticmethod
def p_expression(symbols): def p_expression(symbols):
"""expression : brackets expression """expression : brackets expression
@ -238,7 +211,7 @@ def tex2plain(string):
"""Parse string and return its plain text version.""" """Parse string and return its plain text version."""
return detex( return detex(
silent_yacc( silent_yacc(
module=Parser(), module=LatexParser(),
).parse( ).parse(
string, string,
lexer=SimpleLexer().lexer, lexer=SimpleLexer().lexer,
@ -254,7 +227,7 @@ def parse_song(content, filename=None):
display error messages. display error messages.
""" """
return detex( return detex(
silent_yacc(module=Parser(filename)).parse( silent_yacc(module=LatexParser(filename)).parse(
content, content,
lexer=SongLexer().lexer, lexer=SongLexer().lexer,
).metadata ).metadata

27
patacrep/songbook.py

@ -41,25 +41,32 @@ def argument_parser(args):
"""Parse arguments""" """Parse arguments"""
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='%(prog)s ' + __version__) '--version', help='Show version', action='version',
version='%(prog)s ' + __version__,
)
parser.add_argument('book', nargs=1, help=textwrap.dedent("""\ parser.add_argument(
Book to compile. 'book', nargs=1, help=textwrap.dedent("Book to compile.")
""")) )
parser.add_argument('--datadir', '-d', nargs='+', type=str, action='append', parser.add_argument(
'--datadir', '-d', nargs='+', type=str, action='append',
help=textwrap.dedent("""\ help=textwrap.dedent("""\
Data location. Expected (not necessarily required) Data location. Expected (not necessarily required)
subdirectories are 'songs', 'img', 'latex', 'templates'. subdirectories are 'songs', 'img', 'latex', 'templates'.
""")) """)
)
parser.add_argument('--verbose', '-v', nargs=0, action=VerboseAction, parser.add_argument(
'--verbose', '-v', nargs=0, action=VerboseAction,
help=textwrap.dedent("""\ help=textwrap.dedent("""\
Show details about the compilation process. Show details about the compilation process.
""")) """)
)
parser.add_argument('--steps', '-s', nargs=1, type=str, parser.add_argument(
'--steps', '-s', nargs=1, type=str,
action=ParseStepsAction, action=ParseStepsAction,
help=textwrap.dedent("""\ help=textwrap.dedent("""\
Steps to run. Default is "{steps}". Steps to run. Default is "{steps}".

2
patacrep/songs/chordpro/lexer.py

@ -39,7 +39,7 @@ class ChordProLexer:
t_SPACE = r'[ \t]+' t_SPACE = r'[ \t]+'
t_chord_CHORD = r'[A-G7#m]+' # TODO This can be refined t_chord_CHORD = r'[A-G7#m]+'
t_directive_SPACE = r'[ \t]+' t_directive_SPACE = r'[ \t]+'
t_directive_KEYWORD = r'[a-zA-Z_]+' t_directive_KEYWORD = r'[a-zA-Z_]+'

38
patacrep/songs/chordpro/syntax.py

@ -1,54 +1,24 @@
# -*- coding: utf-8 -*-
"""ChordPro parser""" """ChordPro parser"""
import logging import logging
import ply.yacc as yacc import ply.yacc as yacc
from patacrep.errors import SongbookError from patacrep.songs.syntax import Parser
from patacrep.songs.chordpro import ast from patacrep.songs.chordpro import ast
from patacrep.songs.chordpro.lexer import tokens, ChordProLexer from patacrep.songs.chordpro.lexer import tokens, ChordProLexer
LOGGER = logging.getLogger() LOGGER = logging.getLogger()
class ParsingError(SongbookError): class ChordproParser(Parser):
"""Parsing error."""
def __init__(self, message):
super().__init__(self)
self.message = message
def __str__(self):
return self.message
class Parser:
"""ChordPro parser class""" """ChordPro parser class"""
start = "song" start = "song"
def __init__(self, filename=None): def __init__(self, filename=None):
super().__init__()
self.tokens = tokens self.tokens = tokens
self.filename = filename self.filename = filename
@staticmethod
def __find_column(token):
"""Return the column of ``token``."""
last_cr = token.lexer.lexdata.rfind('\n', 0, token.lexpos)
if last_cr < 0:
last_cr = 0
column = (token.lexpos - last_cr) + 1
return column
def p_error(self, token):
"""Manage parsing errors."""
if token:
LOGGER.error("Error in file {}, line {}:{}.".format(
str(self.filename),
token.lineno,
self.__find_column(token),
)
)
def p_song(self, symbols): def p_song(self, symbols):
"""song : block song """song : block song
| empty | empty
@ -208,7 +178,7 @@ class Parser:
def parse_song(content, filename=None): def parse_song(content, filename=None):
"""Parse song and return its metadata.""" """Parse song and return its metadata."""
return yacc.yacc( return yacc.yacc(
module=Parser(filename), module=ChordproParser(filename),
debug=0, debug=0,
write_tables=0, write_tables=0,
).parse( ).parse(

33
patacrep/songs/syntax.py

@ -0,0 +1,33 @@
"""Generic parsing classes and methods"""
import logging
LOGGER = logging.getLogger()
class Parser:
"""Parser class"""
# pylint: disable=too-few-public-methods
def __init__(self):
self.filename = "" # Will be overloaded
@staticmethod
def __find_column(token):
"""Return the column of ``token``."""
last_cr = token.lexer.lexdata.rfind('\n', 0, token.lexpos)
if last_cr < 0:
last_cr = 0
column = (token.lexpos - last_cr) + 1
return column
def p_error(self, token):
"""Manage parsing errors."""
if token:
LOGGER.error(
"Error in file {}, line {}:{}.".format(
str(self.filename),
token.lineno,
self.__find_column(token),
)
)

9
patacrep/templates.py

@ -20,7 +20,8 @@ _LATEX_SUBS = (
(re.compile(r'\.\.\.+'), r'\\ldots'), (re.compile(r'\.\.\.+'), r'\\ldots'),
) )
_VARIABLE_REGEXP = re.compile(r""" _VARIABLE_REGEXP = re.compile(
r"""
\(\*\ *variables\ *\*\) # Match (* variables *) \(\*\ *variables\ *\*\) # Match (* variables *)
( # Match and capture the following: ( # Match and capture the following:
(?: # Start of non-capturing group, used to match a single character (?: # Start of non-capturing group, used to match a single character
@ -101,8 +102,10 @@ class TexBookRenderer(TexRenderer):
''' '''
self.lang = lang self.lang = lang
# Load templates in filesystem ... # Load templates in filesystem ...
loaders = [FileSystemLoader(os.path.join(datadir, 'templates')) loaders = [
for datadir in datadirs] FileSystemLoader(os.path.join(datadir, 'templates'))
for datadir in datadirs
]
texenv = Environment( texenv = Environment(
loader=ChoiceLoader(loaders), loader=ChoiceLoader(loaders),
extensions=[VariablesExtension], extensions=[VariablesExtension],

5
pylintrc

@ -0,0 +1,5 @@
[VARIABLES]
dummy-variables-rgx=_|dummy
[MESSAGES CONTROL]
disable= logging-format-interpolation
Loading…
Cancel
Save