pyproject_json.py 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. # Copyright (C) 2025 The Qt Company Ltd.
  2. # SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
  3. import json
  4. from pathlib import Path
  5. from .pyproject_parse_result import PyProjectParseResult
  6. def write_pyproject_json(pyproject_file: Path, project_files: list[str]):
  7. """
  8. Create or update a *.pyproject file with the specified content.
  9. :param pyproject_file: The *.pyproject file path to create or update.
  10. :param project_files: The relative paths of the files to include in the project.
  11. """
  12. # The content of the file is fully replaced, so it is not necessary to read and merge any
  13. # existing content
  14. content = {
  15. "files": sorted(project_files),
  16. }
  17. pyproject_file.write_text(json.dumps(content), encoding="utf-8")
  18. def parse_pyproject_json(pyproject_json_file: Path) -> PyProjectParseResult:
  19. """
  20. Parse a pyproject.json file and return a PyProjectParseResult object.
  21. """
  22. result = PyProjectParseResult()
  23. try:
  24. with pyproject_json_file.open("r") as pyf:
  25. project_file_data = json.load(pyf)
  26. except json.JSONDecodeError as e:
  27. result.errors.append(str(e))
  28. return result
  29. except Exception as e:
  30. result.errors.append(str(e))
  31. return result
  32. if not isinstance(project_file_data, dict):
  33. result.errors.append("The root element of pyproject.json must be a JSON object")
  34. return result
  35. found_files = project_file_data.get("files")
  36. if found_files and not isinstance(found_files, list):
  37. result.errors.append("The files element must be a list")
  38. return result
  39. for file in project_file_data.get("files", []):
  40. if not isinstance(file, str):
  41. result.errors.append(f"Invalid file: {file}")
  42. return result
  43. file_path = Path(file)
  44. if not file_path.is_absolute():
  45. file_path = (pyproject_json_file.parent / file).resolve()
  46. result.files.append(file_path)
  47. return result