| 1 |
# Copyright Mozilla Foundation |
| 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 |
|
| 15 |
from __future__ import annotations |
| 16 |
|
| 17 |
from collections.abc import Iterator |
| 18 |
from os import sep, walk |
| 19 |
from os.path import isdir, join, relpath |
| 20 |
|
| 21 |
from gitignorant import Rule, check_match, parse_gitignore_file |
| 22 |
|
| 23 |
|
| 24 |
def walk_files( |
| 25 |
root: str, dirs: list[str] | None = None, ignorepath: str | None = ".l10n-ignore" |
| 26 |
) -> Iterator[str]: |
| 27 |
""" |
| 28 |
Iterate through all files under the `root` directory. |
| 29 |
Use `dirs` to limit the search to only some subdirectories under `root`. |
| 30 |
|
| 31 |
All files and directories with names starting with `.` are ignored. |
| 32 |
To ignore other files, include a `.l10n-ignore` file in `root`, |
| 33 |
or some other location passed in as `ignorepath`. |
| 34 |
This file uses git-ignore syntax, |
| 35 |
and is always based in the `root` directory. |
| 36 |
""" |
| 37 |
if not isdir(root): |
| 38 |
raise ValueError(f"Not a directory: {root}") |
| 39 |
ignore = [Rule(negative=False, content=".*")] |
| 40 |
if ignorepath: |
| 41 |
try: |
| 42 |
with open(join(root, ignorepath), encoding="utf-8") as file: |
| 43 |
ignore += parse_gitignore_file(file) |
| 44 |
except OSError: |
| 45 |
pass |
| 46 |
for dir in (join(root, p) for p in dirs) if dirs else (root,): |
| 47 |
for dirpath, dirnames, filenames in walk(dir): |
| 48 |
idx = len(dirnames) - 1 |
| 49 |
while idx >= 0: |
| 50 |
rp = relpath(join(dirpath, dirnames[idx]), start=root) |
| 51 |
if sep != "/": |
| 52 |
rp = rp.replace(sep, "/") |
| 53 |
if check_match(ignore, rp, is_dir=True): |
| 54 |
del dirnames[idx] |
| 55 |
idx -= 1 |
| 56 |
for fn in filenames: |
| 57 |
path = join(dirpath, fn) |
| 58 |
rp = relpath(path, start=root) |
| 59 |
if sep != "/": |
| 60 |
rp = rp.replace(sep, "/") |
| 61 |
if check_match(ignore, rp): |
| 62 |
continue |
| 63 |
yield path |