Coverage for klayout_pex/common/path_validation.py: 43%
28 statements
« prev ^ index » next coverage.py v7.11.0, created at 2025-10-31 20:14 +0000
« prev ^ index » next coverage.py v7.11.0, created at 2025-10-31 20:14 +0000
1#! /usr/bin/env python3
2#
3# --------------------------------------------------------------------------------
4# SPDX-FileCopyrightText: 2024-2025 Martin Jan Köhler and Harald Pretl
5# Johannes Kepler University, Institute for Integrated Circuits.
6#
7# This file is part of KPEX
8# (see https://github.com/iic-jku/klayout-pex).
9#
10# This program is free software: you can redistribute it and/or modify
11# it under the terms of the GNU General Public License as published by
12# the Free Software Foundation, either version 3 of the License, or
13# (at your option) any later version.
14#
15# This program is distributed in the hope that it will be useful,
16# but WITHOUT ANY WARRANTY; without even the implied warranty of
17# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18# GNU General Public License for more details.
19#
20# You should have received a copy of the GNU General Public License
21# along with this program. If not, see <http://www.gnu.org/licenses/>.
22# SPDX-License-Identifier: GPL-3.0-or-later
23# --------------------------------------------------------------------------------
24#
26from dataclasses import dataclass, field
27from pathlib import Path
28from typing import *
31@dataclass
32class FileValidationResult:
33 @dataclass
34 class Failure:
35 path: Path
36 reason: str
38 working_files: List[Path] = field(default_factory=list)
39 failures: List[Failure] = field(default_factory=list)
42def validate_files(file_paths: List[str | Path],
43 read_bytes: int = 4) -> FileValidationResult:
44 """
45 :param file_paths: paths to validate
46 :param read_bytes: how much bytes to read from the file
47 :return: file validation result object
49 # Example usage
50 files = ["file1.txt", "file2.txt", "missing_file.txt"]
51 result = validate_files(files)
53 print("Working files:", result.working_files)
54 print("Failed files:", result.failed_paths_and_reason)
55 """
56 result = FileValidationResult()
58 for path_str in file_paths:
59 path = Path(path_str)
60 if not path.exists():
61 result.failures.append(FileValidationResult.Failure(path_str, "File does not exist"))
62 continue
63 if not path.is_file():
64 result.failures.append(FileValidationResult.Failure(path_str, "Not a regular file"))
65 continue
66 try:
67 with open(path, "rb") as f:
68 f.read(read_bytes)
69 result.working_files.append(path_str)
70 except Exception as e:
71 result.failures.append(FileValidationResult.Failure(path_str, f"Unreadable: {e}"))
73 return result