Browse Source

Merge pull request #37 from patacrep/ContentList

Gestion de la nouvelle syntaxe pour content
pull/32/head
Luthaf 11 years ago
parent
commit
0b21b5a834
  1. 23
      songbook_core/build.py
  2. 9
      songbook_core/data/examples/example.sb
  3. 12
      songbook_core/data/templates/songs.tex
  4. 50
      songbook_core/songs.py

23
songbook_core/build.py

@ -14,7 +14,7 @@ from songbook_core import __DATADIR__
from songbook_core import errors from songbook_core import errors
from songbook_core.files import recursive_find from songbook_core.files import recursive_find
from songbook_core.index import process_sxd from songbook_core.index import process_sxd
from songbook_core.songs import Song, SongsList from songbook_core.songs import Song, SongbookContent
from songbook_core.templates import TexRenderer from songbook_core.templates import TexRenderer
LOGGER = logging.getLogger(__name__) LOGGER = logging.getLogger(__name__)
@ -95,17 +95,26 @@ class Songbook(object):
# Compute song list # Compute song list
if self.config['content'] is None: if self.config['content'] is None:
self.config['content'] = [ self.config['content'] = [(
"song",
os.path.relpath( os.path.relpath(
filename, filename,
os.path.join(self.config['datadir'], 'songs'), os.path.join(self.config['datadir'], 'songs'),
) ))
for filename for filename
in recursive_find( in recursive_find(
os.path.join(self.config['datadir'], 'songs'), os.path.join(self.config['datadir'], 'songs'),
'*.sg', '*.sg',
) )
] ]
else:
content = self.config["content"]
self.config["content"] = []
for elem in content:
if isinstance(elem, unicode):
self.config["content"].append(("song", elem))
else:
self.config["content"].append((elem[0], elem[1]))
# Ensure self.config['authwords'] contains all entries # Ensure self.config['authwords'] contains all entries
for (key, value) in DEFAULT_AUTHWORDS.items(): for (key, value) in DEFAULT_AUTHWORDS.items():
@ -113,9 +122,9 @@ class Songbook(object):
self.config['authwords'][key] = value self.config['authwords'][key] = value
def _parse_songs(self): def _parse_songs(self):
"""Parse songs included in songbook.""" """Parse content included in songbook."""
self.songslist = SongsList(self.config['datadir']) self.contentlist = SongbookContent(self.config['datadir'])
self.songslist.append_list(self.config['content']) self.contentlist.append_list(self.config['content'])
def write_tex(self, output): def write_tex(self, output):
"""Build the '.tex' file corresponding to self. """Build the '.tex' file corresponding to self.
@ -133,7 +142,7 @@ class Songbook(object):
context = renderer.get_variables() context = renderer.get_variables()
context.update(self.config) context.update(self.config)
context['titleprefixkeys'] = ["after", "sep", "ignore"] context['titleprefixkeys'] = ["after", "sep", "ignore"]
context['songlist'] = self.songslist context['content'] = self.contentlist
context['filename'] = output.name[:-4] context['filename'] = output.name[:-4]
self._set_songs_default(context) self._set_songs_default(context)

9
songbook_core/data/examples/example.sb

@ -10,5 +10,12 @@
"authwords" : { "authwords" : {
"sep" : ["and", "et"] "sep" : ["and", "et"]
}, },
"datadir" : "." "datadir" : ".",
"content" : [["section", "Traditional"],
"chevaliers_de_la_table_ronde.sg",
"greensleeves.sg",
"vent_frais.sg",
["section", "Example"],
"example-fr.sg",
"example-en.sg"]
} }

12
songbook_core/data/templates/songs.tex

@ -25,7 +25,7 @@
(( super() )) (( super() ))
(* for lang in songlist.languages() *) (* for lang in content.languages() *)
\PassOptionsToPackage{((lang))}{babel} \PassOptionsToPackage{((lang))}{babel}
(* endfor *) (* endfor *)
\usepackage[((lang))]{babel} \usepackage[((lang))]{babel}
@ -38,8 +38,14 @@
\addcontentsline{toc}{section}{\songlistname} \addcontentsline{toc}{section}{\songlistname}
\begin{songs}{((indexes|default('')))} \begin{songs}{((indexes|default('')))}
(* for song in songlist.songs *) (* for type, elem in content.content *)
\input{((song.path))} (* if type=="song" *)
\input{((elem.path))}
(* elif type=="section" *)
\end{songs}
\songsection{((elem))}
\begin{songs}{((indexes|default('')))}
(* endif *)
(* endfor *) (* endfor *)
\end{songs} \end{songs}
(* endblock *) (* endblock *)

50
songbook_core/songs.py

@ -87,16 +87,16 @@ def unprefixed_title(title, prefixes):
return title return title
class SongsList(object): class SongbookContent(object):
"""Manipulation et traitement de liste de chansons""" """Manipulation et traitement de liste de chansons"""
def __init__(self, library): def __init__(self, library):
self._songdir = os.path.join(library, 'songs') self._songdir = os.path.join(library, 'songs')
# Liste triée des chansons # Sorted list of the content
self.songs = [] self.content = []
def append(self, filename): def append_song(self, filename):
"""Ajout d'une chanson à la liste """Ajout d'une chanson à la liste
Effets de bord : analyse syntaxique plus ou moins sommaire du fichier Effets de bord : analyse syntaxique plus ou moins sommaire du fichier
@ -104,36 +104,36 @@ class SongsList(object):
album, etc.). album, etc.).
""" """
LOGGER.debug('Parsing file "{}"'.format(filename)) LOGGER.debug('Parsing file "{}"'.format(filename))
# Exécution de PlasTeX # Data extraction from the song with plastex
data = parsetex(filename) data = parsetex(filename)
song = Song(filename, data['languages'], data['titles'], data['args']) song = Song(filename, data['languages'], data['titles'], data['args'])
low, high = 0, len(self.songs) self.content.append(("song", song))
while low != high:
middle = (low + high) / 2 def append(self, type, value):
if song < self.songs[middle]: """ Append a generic element to the content list"""
high = middle self.content.append((type, value))
else:
low = middle + 1
self.songs.insert(low, song)
def append_list(self, filelist): def append_list(self, contentlist):
"""Ajoute une liste de chansons à la liste """Ajoute une liste de chansons à la liste
L'argument est une liste de chaînes, représentant des noms de fichiers L'argument est une liste de chaînes, représentant des noms de fichiers
sous la forme d'expressions régulières destinées à être analysées avec sous la forme d'expressions régulières destinées à être analysées avec
le module glob. le module glob.
""" """
for regexp in filelist: for type, elem in contentlist:
before = len(self.songs) if type == "song":
for filename in glob.iglob(os.path.join(self._songdir, regexp)): # Add all the songs matching the regex
self.append(filename) before = len(self.content)
if len(self.songs) == before: for filename in glob.iglob(os.path.join(self._songdir, elem)):
# No songs were added self.append_song(filename)
LOGGER.warning( if len(self.content) == before:
"Expression '{}' did not match any file".format(regexp) # No songs were added
) LOGGER.warning(
"Expression '{}' did not match any file".format(regexp)
)
else:
self.append(type, elem)
def languages(self): def languages(self):
"""Renvoie la liste des langues utilisées par les chansons""" """Renvoie la liste des langues utilisées par les chansons"""
return set().union(*[set(song.languages) for song in self.songs]) return set().union(*[set(song.languages) for type, song in self.content if type=="song"])

Loading…
Cancel
Save