# -*- coding: iso-8859-2 -*-
# Wojciech Muła
# $Id: walk_dir.py,v 1.1 2007-01-06 16:01:24 wojtek Exp $

import os
import types

def find_file(paths, pred, enterdir=lambda path, depth: True):
	"""
	Function searches all paths listed on paths list and
	return first file that pred(file) is True.  Subdirectories
	are visited only if function 'enterdir' return True.

	Function 'pred' must accept two arguments: path, filename
	and returns either True or False

	Function 'enterdir' must accept two arguments: path
	and depth in directory tree (counted from 0).
	"""
	def aux(path, pred, enterdir, level):
		dir = os.listdir(path)
		for file in dir:
			if pred(path, file):
				return os.path.join(path, file)

		# not found, go deeper	
		for file in dir:
			newpath = os.path.join(path, file)
			if os.path.isdir(newpath) and enterdir(newpath, level):
				result = aux(newpath, pred, enterdir, level+1)
				if result:
					return result
		return None

	
	if type(paths) in types.StringTypes:
		return aux(paths, pred, enterdir, 0)
	else:
		for path in paths:
			file = aux(path, pred, enterdir, 0)
			if file:
				return file

def find_all_files(paths, pred, enterdir=lambda path, depth: True):
	"""
	Function searches all paths listed on paths list and
	return all files that pred(file) is True.  Subdirectories
	are visited only if function 'enterdir' return True.

	Function 'pred' must accept two arguments: path, filename
	and returns either True or False

	Function 'enterdir' must accept two arguments: path
	and depth in directory tree (counted from 0).
	"""
	def aux(path, pred, enterdir, level, list):
		dir = os.listdir(path)
		# XXX: use list comprehension
		for file in dir:
			if pred(path, file):
				list.append(os.path.join(path, file))

		# go deepper	
		for file in dir:
			newpath = os.path.join(path, file)
			if os.path.isdir(newpath) and enterdir(newpath, level):
				aux(newpath, pred, enterdir, level+1, list)
	
	L = []
	if type(paths) in types.StringTypes:
		aux(paths, pred, enterdir, 0, L)
	else:
		for path in paths:
			file = aux(path, pred, enterdir, 0, L)
	return L

