1 # Copyright 2014 The Chromium Authors. All rights reserved. 2 # Use of this source code is governed by a BSD-style license that can be 3 # found in the LICENSE file. 4 5 import collections 6 import os 7 8 9 class PathSet(collections.MutableSet): 10 """A set of paths. 11 12 All mutation methods can take both directories or individual files, but the 13 iterator yields the individual files. All paths are automatically normalized. 14 """ 15 def __init__(self, iterable=None): 16 self._paths = set() 17 if iterable: 18 self |= iterable 19 20 def __contains__(self, path): 21 return os.path.realpath(path) in self._paths 22 23 def __iter__(self): 24 return iter(self._paths) 25 26 def __len__(self): 27 return len(self._paths) 28 29 def add(self, path): 30 path = os.path.realpath(path) 31 if os.path.isfile(path): 32 self._paths.add(path) 33 for root, _, files in os.walk(path): 34 for basename in files: 35 file_path = os.path.join(root, basename) 36 if os.path.isfile(file_path): 37 self._paths.add(file_path) 38 39 def discard(self, path): 40 path = os.path.realpath(path) 41 self._paths.discard(path) 42 for root, _, files in os.walk(path): 43 for basename in files: 44 self._paths.discard(os.path.join(root, basename)) 45