blob: c085731c8a1367a995d85bcf395981f2095a817f [file] [log] [blame]
martin f. krafftf37f0682013-06-14 16:36:20 +02001#
2# -*- coding: utf-8 -*-
3#
4# This file is part of reclass (http://github.com/madduck/reclass)
5#
6# Copyright © 2007–13 martin f. krafft <madduck@madduck.net>
7# Released under the terms of the Artistic Licence 2.0
8#
9import os
10import sys
11
12SKIPDIRS = ( '.git' , '.svn' , 'CVS', 'SCCS', '.hg', '_darcs' )
13FILE_EXTENSION = '.yml'
14
15def vvv(msg):
16 #print >>sys.stderr, msg
17 pass
18
19class Directory(object):
20
21 def __init__(self, path, fileclass=None):
22 ''' Initialise a directory object '''
23 self._path = path
24 self._fileclass = fileclass
25 self._files = {}
26
27 def _register_files(self, dirpath, filenames):
28 for f in filter(lambda f: f.endswith(FILE_EXTENSION), filenames):
29 vvv('REGISTER {0}'.format(f))
30 f = os.path.join(dirpath, f)
31 ptr = None if not self._fileclass else self._fileclass(f)
32 self._files[f] = ptr
33
34 files = property(lambda self: self._files)
35
36 def walk(self, register_fn=None):
37 def _error(error):
38 raise Exception('{0}: {1} ({2})'.format(error.filename, error.strerror, error.errno))
39 if not callable(register_fn): register_fn = self._register_files
40 for dirpath, dirnames, filenames in os.walk(self._path,
41 topdown=True,
42 onerror=_error,
43 followlinks=True):
44 vvv('RECURSE {0}, {1} files, {2} subdirectories'.format(
45 dirpath.replace(os.getcwd(), '.'), len(filenames), len(dirnames)))
46 for d in SKIPDIRS:
47 if d in dirnames:
48 vvv(' SKIP subdirectory {0}'.format(d))
49 dirnames.remove(d)
50 register_fn(dirpath, filenames)
51
52 def __repr__(self):
53 return '<{0} {1}>'.format(self.__class__.__name__, self._path)