aboutsummaryrefslogtreecommitdiffstats
path: root/brutha/directory.py
blob: 886c50677525a72d9940b8ca669b8b01ad9ed94d (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
# -*- coding: utf-8 -*-

import re
import os

from brutha.file import FlacFile, LossyFile
from brutha.util import escape


class NotInteresting(Exception):
    """
    A directory with no sound files whatsoever
    """
    pass


class Directory(object):
    def __init__(self, path, destpath, options=None, _files=None):
        assert os.path.isdir(path)
        self.path = path
        self.destpath = destpath
        self.options = {}
        if options:
            self.options.update(options)
        self._files = _files or \
            [f for f in os.listdir(self.path) if not os.path.isdir(f)]

    def commands(self):
        commands = []
        files = list(self.files())
        if not len(files):
            raise NotInteresting("No sound files")

        if not os.path.isdir(self.destpath):
            commands.append(self.mkdir())

        for f in files:
            commands.extend(f.pre())
        if not all([f.uptodate() for f in files]) and self.options['gain']:
            commands.append(self.vorbisgain())
        for f in files:
            commands.extend(f.post())
        return commands

    def wanted(self):
        d = os.path.normpath(self.destpath)
        while len(d) > 1:
            yield d
            # all parent directories are wanted, too
            d = os.path.normpath(os.path.join(d, os.path.pardir))
        for f in self.files():
            yield os.path.normpath(f.dest())

    def files(self):
        flacs = self.flacs()
        mp3s = self.mp3s()
        oggs = self.oggs()
        for flac in flacs:
            yield FlacFile(self.path, self.destpath, flac, self.options)
        for mp3 in mp3s:
            yield LossyFile(self.path, self.destpath, mp3, self.options)
        for ogg in oggs:
            yield LossyFile(self.path, self.destpath, ogg, self.options)

    def mkdir(self):
        return 'mkdir -p %s' % escape(os.path.join(self.destpath))

    def vorbisgain(self):
        return 'vorbisgain -q -s -f -a %s' % escape(os.path.join(self.destpath))

    def flacs(self):
        return self.type_files('flac')

    def mp3s(self):
        return self.type_files('mp3')

    def oggs(self):
        return self.type_files('ogg')

    def type_files(self, ext):
        pattern = re.compile(r'\.%s$' % re.escape(ext), flags=re.IGNORECASE)

        return [f for f in self._files if pattern.search(f)]