Example #1
0
def main():
    options = argument_parser(sys.argv[1:])
    
    datadir = os.path.abspath(str(options.datadir[0]))

    if not os.path.isdir(datadir):
        print("Error: '{}' is not a directory.".format(datadir))
        sys.exit(1)
    
    if not options.output:
        output = os.path.basename(datadir) + ".sbc"
    else:
        output = str(options.output)
    
    songdir = os.path.join(datadir, "songs")
    
    if not os.path.isdir(songdir):
        print("Error: no songs directory in '{}'.".format(datadir))
        sys.exit(1)
    
    songs = recursive_find(songdir, "*.sg")
    
    songspath = []
    
    for path in songs:
        songspath.append(relpath(path, datadir))

    with open(output, "w") as out:
        json.dump(songspath, out, indent=4)
Example #2
0
 def render(self, context):
     return r'\input{{{}}}'.format(
         files.path2posix(
             files.relpath(
                 self.filename,
                 os.path.dirname(context['filename']),
             )))
Example #3
0
def load_plugins():
    """Load all content plugins, and return a dictionary of those plugins.

    Return value: a dictionary where:
    - keys are the keywords ;
    - values are functions triggered when this keyword is met.
    """
    plugins = {}
    for name in glob.glob(os.path.join(os.path.dirname(__file__), "*.py")):
        if name.endswith(".py") and os.path.basename(name) != "__init__.py":
            plugin = importlib.import_module(
                    'patacrep.content.{}'.format(
                        os.path.basename(name[:-len('.py')])
                        )
                    )
            for (key, value) in plugin.CONTENT_PLUGINS.items():
                if key in plugins:
                    LOGGER.warning(
                            "File %s: Keyword '%s' is already used. Ignored.",
                            files.relpath(name),
                            key,
                            )
                    continue
                plugins[key] = value
    return plugins
Example #4
0
    def _clean_path(cls, elem):
        """Shorten the path relative to the `songs` directory"""

        latex_command_classes = (
            section.Section,
            songsection.SongSection,
            setcounter.CounterSetter,
            )
        if isinstance(elem, latex_command_classes):
            return elem.render(None)[1:]

        elif isinstance(elem, song.SongRenderer):
            songpath = os.path.join(os.path.dirname(__file__), 'datadir', 'songs')
            return files.path2posix(files.relpath(elem.song.fullpath, songpath))

        elif isinstance(elem, tex.LaTeX):
            return files.path2posix(elem.filename)

        else:
            raise Exception(elem)
Example #5
0
    def _clean_path(cls, elem):
        """Shorten the path relative to the `songs` directory"""
        if isinstance(elem, song.SongRenderer):
            songpath = os.path.join(os.path.dirname(__file__), 'datadir', 'songs')
            return files.path2posix(files.relpath(elem.song.fullpath, songpath))

        elif isinstance(elem, section.Section):
            if elem.short is None:
                return "{}:{}".format(elem.keyword, elem.name)
            else:
                return "{}:({}){}".format(elem.keyword, elem.short, elem.name)

        elif isinstance(elem, songsection.SongSection):
            return "{}:{}".format(elem.keyword, elem.name)

        elif isinstance(elem, tex.LaTeX):
            return files.path2posix(elem.filename)

        else:
            raise Exception(elem)
    def _clean_path(cls, elem):
        """Shorten the path relative to the `songs` directory"""

        latex_command_classes = (
            section.Section,
            songsection.SongSection,
            setcounter.CounterSetter,
            )
        if isinstance(elem, latex_command_classes):
            return elem.render(None)[1:]

        elif isinstance(elem, song.SongRenderer):
            songpath = os.path.join(os.path.dirname(__file__), 'datadir', 'songs')
            return files.path2posix(files.relpath(elem.song.fullpath, songpath))

        elif isinstance(elem, tex.LaTeX):
            return files.path2posix(elem.filename)

        else:
            raise Exception(elem)
Example #7
0
def parse(keyword, argument, contentlist, config):
    """Parse data associated with keyword 'song'.

    Arguments:
    - keyword: unused;
    - argument: unused;
    - contentlist: a list of strings, which are interpreted as regular
      expressions (interpreted using the glob module), referring to songs.
    - config: the current songbook configuration dictionary.

    Return a list of SongRenderer() instances.
    """
    if 'languages' not in config:
        config['_languages'] = set()
    songlist = []
    for songdir in config['_songdir']:
        if contentlist:
            break
        contentlist = [
                files.relpath(filename, songdir)
                for filename
                in files.recursive_find(songdir, "*.sg")
                ]
    for elem in contentlist:
        before = len(songlist)
        for songdir in config['_songdir']:
            for filename in glob.iglob(os.path.join(songdir, elem)):
                LOGGER.debug('Parsing file "{}"…'.format(filename))
                song = SongRenderer(filename, config)
                songlist.append(song)
                config["_languages"].update(song.languages)
            if len(songlist) > before:
                break
        if len(songlist) == before:
            # No songs were added
            LOGGER.warning(
                    "Expression '{}' did not match any file".format(elem)
                    )
    return songlist
Example #8
0
 def ordered_song_keys(songrenderer):
     """Return the list of values used to sort the song."""
     song = songrenderer.song
     songkey = []
     for key in sort:
         if key == "title":
             field = song.unprefixed_titles
         elif key == "path":
             field = song.fullpath
         elif key == "by":
             field = song.authors
         else:
             try:
                 field = song.data[key]
             except KeyError:
                 LOGGER.debug(
                     "Ignoring missing key '{}' for song {}.".format(
                         key,
                         files.relpath(song.fullpath),
                     ))
                 field = ""
         songkey.append(normalize_field(field))
     return songkey
Example #9
0
 def ordered_song_keys(song):
     """Return the list of values used to sort the song."""
     songkey = []
     for key in sort:
         if key == "@title":
             field = song.unprefixed_titles
         elif key == "@path":
             field = song.path
         elif key == "by":
             field = song.authors
         else:
             try:
                 field = song.args[key]
             except KeyError:
                 LOGGER.debug(
                         "Ignoring unknown key '{}' for song {}.".format(
                             key,
                             files.relpath(song.path),
                             )
                         )
                 field = ""
         songkey.append(normalize_field(field))
     return songkey
Example #10
0
 def render(self, context):
     return r'\input{{{}}}'.format(files.path2posix(files.relpath(
         self.filename,
         os.path.dirname(context['filename']),
         )))
Example #11
0
 def render(self, context):
     """Return the string that will render the song."""
     return r'\input{{{}}}'.format(files.relpath(
         self.path,
         os.path.dirname(context['filename'])
         ))