Browse Source

Merge pull request #98 from patacrep/api_getter

Changes to make it easier for patanet to access data
pull/105/head
Louis 9 years ago
parent
commit
f7847d4ab7
  1. 88
      patacrep/songs/__init__.py
  2. 8
      patacrep/songs/chordpro/__init__.py
  3. 9
      patacrep/songs/chordpro/ast.py
  4. 2
      patacrep/songs/chordpro/data/latex/content_image
  5. 2
      patacrep/songs/chordpro/data/latex/content_partition
  6. 2
      patacrep/songs/chordpro/data/latex/song

88
patacrep/songs/__init__.py

@ -194,47 +194,63 @@ class Song:
""" """
raise NotImplementedError() raise NotImplementedError()
def unprefixed_title(title, prefixes): def get_datadirs(self, subdir=None):
"""Remove the first prefix of the list in the beginning of title (if any). """Return an iterator of existing datadirs (with eventually a subdir)
""" """
for prefix in prefixes: for directory in self.config['datadir']:
match = re.compile(r"^(%s)\b\s*(.*)$" % prefix, re.LOCALE).match(title) fullpath = os.path.join(directory, subdir)
if match: if os.path.isdir(fullpath):
return match.group(2) yield fullpath
return title
def search_image(image, chordprofile, config): def search_file(self, filename, extensions=None, directories=None):
"""Return the file name of an image, so that LaTeX will find it. """Search for a file name.
:param str image: The name, as provided in the chordpro file. :param str filename: The name, as provided in the chordpro file (with or without extension).
:param str chordprofile: The name of the file including this image. :param list extensions: Possible extensions (with '.')
:param dict config: Songbook configuration dictionary. :param iterator directories: Other directories where to search for the file
The directory where the Song file is stored is added to the list.
The image can be: Returns None if nothing found.
"""
if extensions is None:
extensions = ['']
if directories is None:
directories = []
- in the same directory as the including song file; songdir = os.path.dirname(self.fullpath)
- in the same directory as the main LaTeX file;
- in some of the `DATADIR/img` directories.
If image is not found, the `image` argument is returned. for directory in [songdir] + list(directories):
""" for extension in extensions:
# Image is in the same folder as its song fullpath = os.path.join(directory, filename + extension)
texdir = os.path.dirname(chordprofile) if os.path.isfile(fullpath):
if os.path.exists(os.path.join(texdir, image)): return fullpath
return os.path.join(texdir, image) return None
# Image is in the same directory as the main tex file
rootdir = os.path.dirname(os.path.join(
os.getcwd(),
config['filename'],
))
if os.path.exists(os.path.join(rootdir, image)):
return image
# Image is in a datadir def search_image(self, filename):
for directory in config['datadir']: """Search for an image file"""
if os.path.exists(os.path.join(directory, 'img', image)): datadir_img = self.get_datadirs('img')
return os.path.join(directory, 'img', image) filepath = self.search_file(filename, ['', '.jpg', '.png'], datadir_img)
return filepath if filepath else filename
# Could not find image @property
return image def cover_filepath(self):
"""Get the path to the cover file (or None if not found)"""
filename = str(self.data.get('cov', ''))
if not filename:
return None
datadir_img = self.get_datadirs('img')
return self.search_file(filename, ['', '.jpg', '.png'], datadir_img)
def search_partition(self, filename):
"""Search for a lilypond file"""
filepath = self.search_file(filename, ['', '.ly'])
return filepath if filepath else filename
def unprefixed_title(title, prefixes):
"""Remove the first prefix of the list in the beginning of title (if any).
"""
for prefix in prefixes:
match = re.compile(r"^(%s)\b\s*(.*)$" % prefix, re.LOCALE).match(title)
if match:
return match.group(2)
return title

8
patacrep/songs/chordpro/__init__.py

@ -5,7 +5,7 @@ import pkg_resources
import os import os
from patacrep import encoding, files from patacrep import encoding, files
from patacrep.songs import Song, search_image 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
@ -42,7 +42,11 @@ class ChordproSong(Song):
os.path.abspath(pkg_resources.resource_filename(__name__, 'data')), os.path.abspath(pkg_resources.resource_filename(__name__, 'data')),
output_format, output_format,
))) )))
self.jinjaenv.filters['search_image'] = search_image
self.jinjaenv.filters['search_image'] = self.search_image
self.jinjaenv.filters['search_partition'] = self.search_partition
return self._render_ast( return self._render_ast(
context, context,
self.cached['song'].content, self.cached['song'].content,

9
patacrep/songs/chordpro/ast.py

@ -39,6 +39,10 @@ class OrderedLifoDict:
def __getitem__(self, key): def __getitem__(self, key):
return self._values[key] return self._values[key]
def get(self, key, default=None):
"""Same as :meth:`dict.get`."""
return self._values.get(key, default)
def _indent(string): def _indent(string):
"""Return and indented version of argument.""" """Return and indented version of argument."""
return "\n".join([" {}".format(line) for line in string.split('\n')]) return "\n".join([" {}".format(line) for line in string.split('\n')])
@ -337,6 +341,11 @@ class Define(Directive):
self.fingers = fingers # Can be None self.fingers = fingers # Can be None
super().__init__("define", None) super().__init__("define", None)
@property
def pretty_key(self):
"""Return the key with nicer (utf8) alteration"""
return self.key.chord.replace('&', '').replace('#', '')
def __str__(self): def __str__(self):
return None return None

2
patacrep/songs/chordpro/data/latex/content_image

@ -1 +1 @@
\image{(( content.argument|search_image(path, config) ))} \image{(( content.argument|search_image ))}

2
patacrep/songs/chordpro/data/latex/content_partition

@ -1 +1 @@
\lilypond{ ((- content.argument|search_image(path, config) -)) } \lilypond{ ((- content.argument|search_partition -)) }

2
patacrep/songs/chordpro/data/latex/song

@ -28,7 +28,7 @@
(* endif *) (* endif *)
(* endfor *) (* endfor *)
(* if 'cov' in metadata *) (* if 'cov' in metadata *)
cov={(( metadata["cov"].argument|search_image(path, config) ))}, cov={(( metadata["cov"].argument|search_image ))},
(* endif *) (* endif *)
(* for key in metadata.keys *) (* for key in metadata.keys *)
(( key.keyword ))={(( key.argument ))}, (( key.keyword ))={(( key.argument ))},

Loading…
Cancel
Save