• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# Copyright 2015 gRPC authors.
2#
3# Licensed under the Apache License, Version 2.0 (the "License");
4# you may not use this file except in compliance with the License.
5# You may obtain a copy of the License at
6#
7#     http://www.apache.org/licenses/LICENSE-2.0
8#
9# Unless required by applicable law or agreed to in writing, software
10# distributed under the License is distributed on an "AS IS" BASIS,
11# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12# See the License for the specific language governing permissions and
13# limitations under the License.
14"""Helper to watch a (set) of directories for modifications."""
15
16import os
17import time
18from six import string_types
19
20
21class DirWatcher(object):
22    """Helper to watch a (set) of directories for modifications."""
23
24    def __init__(self, paths):
25        if isinstance(paths, string_types):
26            paths = [paths]
27        self._done = False
28        self.paths = list(paths)
29        self.lastrun = time.time()
30        self._cache = self._calculate()
31
32    def _calculate(self):
33        """Walk over all subscribed paths, check most recent mtime."""
34        most_recent_change = None
35        for path in self.paths:
36            if not os.path.exists(path):
37                continue
38            if not os.path.isdir(path):
39                continue
40            for root, _, files in os.walk(path):
41                for f in files:
42                    if f and f[0] == '.': continue
43                    try:
44                        st = os.stat(os.path.join(root, f))
45                    except OSError as e:
46                        if e.errno == os.errno.ENOENT:
47                            continue
48                        raise
49                    if most_recent_change is None:
50                        most_recent_change = st.st_mtime
51                    else:
52                        most_recent_change = max(most_recent_change,
53                                                 st.st_mtime)
54        return most_recent_change
55
56    def most_recent_change(self):
57        if time.time() - self.lastrun > 1:
58            self._cache = self._calculate()
59            self.lastrun = time.time()
60        return self._cache
61