Browse Source

Complete the transition to support only language code

pull/124/head
Oliverpool 9 years ago
parent
commit
909d8120d0
  1. 6
      patacrep/content/song.py
  2. 10
      patacrep/data/templates/songs.tex
  3. 22
      patacrep/latex/__init__.py
  4. 38
      patacrep/songs/__init__.py
  5. 3
      patacrep/songs/chordpro/__init__.py
  6. 1
      patacrep/songs/chordpro/ast.py
  7. 4
      patacrep/songs/chordpro/data/html/song_header
  8. 4
      patacrep/songs/chordpro/data/latex/song
  9. 15
      patacrep/songs/latex/__init__.py
  10. 3
      patacrep/templates.py
  11. 2
      test/test_chordpro/lang.source
  12. 2
      test/test_chordpro/newline.html

6
patacrep/content/song.py

@ -60,8 +60,8 @@ def parse(keyword, argument, contentlist, config):
Return a list of Song() instances. Return a list of Song() instances.
""" """
plugins = config['_song_plugins'] plugins = config['_song_plugins']
if '_languages' not in config: if '_langs' not in config:
config['_languages'] = set() config['_langs'] = set()
songlist = [] songlist = []
for songdir in config['_songdir']: for songdir in config['_songdir']:
if contentlist: if contentlist:
@ -92,7 +92,7 @@ def parse(keyword, argument, contentlist, config):
datadir=songdir.datadir, datadir=songdir.datadir,
)) ))
songlist.append(renderer) songlist.append(renderer)
config["_languages"].add(renderer.song.language) config["_langs"].add(renderer.song.lang)
if len(songlist) > before: if len(songlist) > before:
break break
if len(songlist) == before: if len(songlist) == before:

10
patacrep/data/templates/songs.tex

@ -52,7 +52,7 @@
"mandatory": true "mandatory": true
}, },
"lang": {"description": {"english": "Language", "french": "Langue"}, "lang": {"description": {"english": "Language", "french": "Langue"},
"default": {"en": "english", "fr": "french"} "default": {"english": "en", "french": "fr"}
}, },
"titleprefixwords": {"description": {"english": "Ignore some words in the beginning of song titles", "titleprefixwords": {"description": {"english": "Ignore some words in the beginning of song titles",
"french": "Ignore des mots dans le classement des chansons"}, "french": "Ignore des mots dans le classement des chansons"},
@ -80,11 +80,11 @@
(* block songbookpreambule *) (* block songbookpreambule *)
(( super() )) (( super() ))
(* for language in _languages -*) (* for lang in _langs -*)
\PassOptionsToPackage{((language))}{babel} \PassOptionsToPackage{(( lang2babel(lang) ))}{babel}
(* endfor *) (* endfor *)
\usepackage[(( lang2language(lang) ))]{babel} \usepackage[(( lang2babel(lang) ))]{babel}
\lang{(( lang2language(lang) ))} \lang{(( lang2babel(lang) ))}
\usepackage{graphicx} \usepackage{graphicx}
\graphicspath{ % \graphicspath{ %

22
patacrep/latex/__init__.py

@ -5,4 +5,26 @@ This module uses an LALR parser to try to parse LaTeX code. LaTeX language
will work on simple cases, but not on complex ones. will work on simple cases, but not on complex ones.
""" """
import logging
from collections import OrderedDict
from patacrep.latex.syntax import tex2plain, parse_song from patacrep.latex.syntax import tex2plain, parse_song
LOGGER = logging.getLogger(__name__)
BABEL_LANGUAGES = OrderedDict((
('fr', 'french'),
('en', 'english'),
('de', 'german'),
('es', 'spanish'),
('it', 'italian'),
('pt', 'portuguese'),
))
def lang2babel(lang):
try:
return BABEL_LANGUAGES[lang]
except KeyError:
available = ", ".join(BABEL_LANGUAGES.keys())
LOGGER.error('Unknown lang code: ' + lang + '. Supported: ' + available)
return 'english'

38
patacrep/songs/__init__.py

@ -7,30 +7,12 @@ import logging
import os import os
import pickle import pickle
import re import re
from collections import OrderedDict
from patacrep.authors import process_listauthors from patacrep.authors import process_listauthors
from patacrep import files, encoding from patacrep import files, encoding
LOGGER = logging.getLogger(__name__) LOGGER = logging.getLogger(__name__)
BABEL_LANGUAGES = OrderedDict((
('fr', 'french'),
('en', 'english'),
('de', 'german'),
('es', 'spanish'),
('it', 'italian'),
('pt', 'portuguese'),
))
def lang2language(lang):
try:
return BABEL_LANGUAGES[lang]
except KeyError:
available = ", ".join(BABEL_LANGUAGES.keys())
LOGGER.error('Unknown lang code: ' + lang + '. Supported: ' + available)
return 'english'
def cached_name(datadir, filename): def cached_name(datadir, filename):
"""Return the filename of the cache version of the file.""" """Return the filename of the cache version of the file."""
fullpath = os.path.abspath(os.path.join(datadir, '.cache', filename)) fullpath = os.path.abspath(os.path.join(datadir, '.cache', filename))
@ -107,7 +89,7 @@ class Song:
"cached", "cached",
"data", "data",
"subpath", "subpath",
"language", "lang",
"authors", "authors",
"_filehash", "_filehash",
"_version", "_version",
@ -204,8 +186,7 @@ class Song:
- titles: the list of (raw) titles. This list will be processed to - titles: the list of (raw) titles. This list will be processed to
remove prefixes. remove prefixes.
- language: the main language of the song, as language recognized by - lang: the main language of the song, as language code..
the LaTeX babel package.
- authors: the list of (raw) authors. This list will be processed to - authors: the list of (raw) authors. This list will be processed to
'clean' it (see function :func:`patacrep.authors.processauthors`). 'clean' it (see function :func:`patacrep.authors.processauthors`).
- data: song metadata. Used (among others) to sort the songs. - data: song metadata. Used (among others) to sort the songs.
@ -264,21 +245,6 @@ class Song:
filepath = self.search_file(filename, ['', '.ly']) filepath = self.search_file(filename, ['', '.ly'])
return filepath if none_if_not_found or filepath else filename return filepath if none_if_not_found or filepath else filename
@property
def language(self):
"""Return the string corresponding to the babel (LaTeX) language"""
return lang2language(self.lang)
@language.setter
def language(self, language):
"""Set the language code"""
for lang, babel_language in BABEL_LANGUAGES.items():
if language == babel_language:
self.lang = lang
return
# TODO: raise a nice error
print('Unsupported language:' + language)
def unprefixed_title(title, prefixes): def unprefixed_title(title, prefixes):
"""Remove the first prefix of the list in the beginning of title (if any). """Remove the first prefix of the list in the beginning of title (if any).
""" """

3
patacrep/songs/chordpro/__init__.py

@ -9,6 +9,7 @@ from patacrep import encoding, files
from patacrep.songs import Song from patacrep.songs import Song
from patacrep.songs.chordpro.syntax import parse_song from patacrep.songs.chordpro.syntax import parse_song
from patacrep.templates import Renderer from patacrep.templates import Renderer
from patacrep.latex import lang2babel
class ChordproSong(Song): class ChordproSong(Song):
"""Chordpros song parser.""" """Chordpros song parser."""
@ -57,7 +58,6 @@ class ChordproSong(Song):
templatedirs = [] templatedirs = []
context = { context = {
'language': self.language,
'lang': self.lang, 'lang': self.lang,
"titles": self.titles, "titles": self.titles,
"authors": self.authors, "authors": self.authors,
@ -72,6 +72,7 @@ class ChordproSong(Song):
)) ))
jinjaenv.filters['search_image'] = self.search_image jinjaenv.filters['search_image'] = self.search_image
jinjaenv.filters['search_partition'] = self.search_partition jinjaenv.filters['search_partition'] = self.search_partition
jinjaenv.filters['lang2babel'] = lang2babel
try: try:
return Renderer( return Renderer(

1
patacrep/songs/chordpro/ast.py

@ -31,6 +31,7 @@ DIRECTIVE_SHORTCUTS = {
"c": "comment", "c": "comment",
"gc": "guitar_comment", "gc": "guitar_comment",
"cover": "cov", "cover": "cov",
"language": "lang",
} }
def directive_name(text): def directive_name(text):

4
patacrep/songs/chordpro/data/html/song_header

@ -17,8 +17,8 @@
(* endif *) (* endif *)
(* endfor *) (* endfor *)
(* if language is defined -*) (* if lang is defined -*)
<span class="song-language">Language: (( language ))</span><br> <span class="song-language">Lang: (( lang ))</span><br>
(* endif *) (* endif *)
(* include 'content_metadata_cover' *) (* include 'content_metadata_cover' *)

4
patacrep/songs/chordpro/data/latex/song

@ -1,5 +1,5 @@
(* if language is defined -*) (* if lang is defined -*)
\selectlanguage{((language))} \selectlanguage{(( lang2babel(lang) ))}
(* endif *) (* endif *)
(*- if metadata.columns is defined *) (*- if metadata.columns is defined *)

15
patacrep/songs/latex/__init__.py

@ -8,19 +8,19 @@ will work on simple cases, but not on complex ones.
import os import os
from patacrep import files, encoding from patacrep import files, encoding
from patacrep.latex import parse_song from patacrep.latex import parse_song, BABEL_LANGUAGES
from patacrep.songs import Song from patacrep.songs import Song
class LatexSong(Song): class LatexSong(Song):
"""LaTeX song parser.""" """LaTeX song parser."""
def _parse(self, __config): def _parse(self, __config):
"""Parse content, and return the dictinory of song data.""" """Parse content, and return the dictionary of song data."""
with encoding.open_read(self.fullpath, encoding=self.encoding) as song: with encoding.open_read(self.fullpath, encoding=self.encoding) as song:
self.data = parse_song(song.read(), self.fullpath) self.data = parse_song(song.read(), self.fullpath)
self.titles = self.data['@titles'] self.titles = self.data['@titles']
del self.data['@titles'] del self.data['@titles']
self.language = self.data['@language'] self.set_lang(self.data['@language'])
del self.data['@language'] del self.data['@language']
if "by" in self.data: if "by" in self.data:
self.authors = [self.data['by']] self.authors = [self.data['by']]
@ -38,6 +38,15 @@ class LatexSong(Song):
)) ))
return r'\import{{{}/}}{{{}}}'.format(os.path.dirname(path), os.path.basename(path)) return r'\import{{{}/}}{{{}}}'.format(os.path.dirname(path), os.path.basename(path))
def set_lang(self, language):
"""Set the language code"""
for lang, babel_language in BABEL_LANGUAGES.items():
if language == babel_language:
self.lang = lang
return
# TODO: add as custom language
LOGGER.error('Unsupported language:' + language)
SONG_PARSERS = { SONG_PARSERS = {
'is': LatexSong, 'is': LatexSong,
'sg': LatexSong, 'sg': LatexSong,

3
patacrep/templates.py

@ -9,6 +9,7 @@ import re
import json import json
from patacrep import errors, files, songs from patacrep import errors, files, songs
from patacrep.latex import lang2babel
import patacrep.encoding import patacrep.encoding
_LATEX_SUBS = ( _LATEX_SUBS = (
@ -84,7 +85,7 @@ class Renderer:
self.jinjaenv.trim_blocks = True self.jinjaenv.trim_blocks = True
self.jinjaenv.lstrip_blocks = True self.jinjaenv.lstrip_blocks = True
self.jinjaenv.globals["path2posix"] = files.path2posix self.jinjaenv.globals["path2posix"] = files.path2posix
self.jinjaenv.globals["lang2language"] = songs.lang2language self.jinjaenv.globals["lang2babel"] = lang2babel
self.template = self.jinjaenv.get_template(template) self.template = self.jinjaenv.get_template(template)

2
test/test_chordpro/lang.source

@ -1 +1 @@
{language: french} {language: fr}

2
test/test_chordpro/newline.html

@ -1,4 +1,4 @@
<span class="song-language">Language: english</span><br> <span class="song-language">Lang: en</span><br>

Loading…
Cancel
Save