godotkit 0.8.1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
godotkit/__init__.py ADDED
@@ -0,0 +1,6 @@
1
+ from importlib.metadata import PackageNotFoundError, version
2
+
3
+ try:
4
+ __version__ = version("godotkit")
5
+ except PackageNotFoundError:
6
+ __version__ = "0.0.0"
@@ -0,0 +1,17 @@
1
+ from .core import (
2
+ launch_daemon_command,
3
+ open_directory,
4
+ remove_directory,
5
+ run_utility_command,
6
+ )
7
+ from .git import clone, git_installed, init_repo
8
+
9
+ __all__ = [
10
+ "clone",
11
+ "git_installed",
12
+ "init_repo",
13
+ "launch_daemon_command",
14
+ "open_directory",
15
+ "remove_directory",
16
+ "run_utility_command",
17
+ ]
@@ -0,0 +1,134 @@
1
+ import logging
2
+ import os
3
+ import platform
4
+ import shutil
5
+ import subprocess
6
+ import sys
7
+ from pathlib import Path
8
+
9
+ logger = logging.getLogger(__name__)
10
+
11
+
12
+ def open_directory(path: Path) -> None:
13
+ """
14
+ Opens the given directory in the native file manager.
15
+
16
+ Args:
17
+ path (Path): The path to the directory to open.
18
+
19
+ Raises:
20
+ ValueError: If the provided path is not a valid directory.
21
+ NotImplementedError: If the current platform is unsupported.
22
+ """
23
+ if not path.is_dir():
24
+ raise ValueError("Invalid directory path")
25
+
26
+ current_platform = platform.system().lower()
27
+
28
+ if current_platform == "windows" and hasattr(os, "startfile"):
29
+ os.startfile(str(path))
30
+ elif current_platform == "darwin":
31
+ run_utility_command(["open", str(path)])
32
+ elif current_platform == "linux":
33
+ run_utility_command(["xdg-open", str(path)])
34
+ else:
35
+ raise NotImplementedError(f"Unsupported platform: {current_platform}")
36
+
37
+
38
+ def remove_directory(dir_path: Path) -> None:
39
+ """Recursively deletes a directory and all its contents.
40
+
41
+ Args:
42
+ dir_path (Path): Path to the directory to delete.
43
+
44
+ Raises:
45
+ ValueError: If the path does not exist or is not a directory.
46
+ OSError: If an OS-related error occurs during deletion.
47
+ PermissionError: If the process lacks permission to delete files or subdirectories.
48
+ """
49
+ if not dir_path.is_dir():
50
+ msg = f"Invalid directory path: '{dir_path}'"
51
+ logger.error(msg)
52
+ raise ValueError(msg)
53
+ try:
54
+ shutil.rmtree(dir_path)
55
+ logger.info("Removed directory '%s'", dir_path)
56
+ except Exception:
57
+ logger.exception("Failed to remove directory '%s'", dir_path)
58
+ raise
59
+
60
+
61
+ def run_utility_command(
62
+ command: list[str],
63
+ working_dir: Path | None = None,
64
+ timeout: int | None = None,
65
+ ) -> subprocess.CompletedProcess:
66
+ """Runs a system command, waits for it to complete, and captures output.
67
+
68
+ Args:
69
+ command (List[str]): Command and arguments, e.g. ['ls', '-l'].
70
+ working_dir (Optional[Path]): Working directory for the command.
71
+ timeout (Optional[int]): Timeout in seconds.
72
+
73
+ Returns:
74
+ subprocess.CompletedProcess: Result object containing stdout, stderr, and return code.
75
+
76
+ Raises:
77
+ subprocess.CalledProcessError: If the command fails (non-zero return code).
78
+ subprocess.TimeoutExpired: If the command times out.
79
+ ValueError: If the working directory is invalid.
80
+ """
81
+ cmd_str = " ".join(command)
82
+ logger.debug("Executing utility command: %s", cmd_str)
83
+
84
+ if working_dir is not None and not working_dir.is_dir():
85
+ raise ValueError(f"Invalid working directory: {working_dir}")
86
+
87
+ return subprocess.run(
88
+ command,
89
+ cwd=None if working_dir is None else str(working_dir),
90
+ timeout=timeout,
91
+ check=True,
92
+ capture_output=True,
93
+ text=True,
94
+ )
95
+
96
+
97
+ def launch_daemon_command(
98
+ command: list[str],
99
+ working_dir: Path | None = None,
100
+ ) -> None:
101
+ """Launches a system command in a non-blocking, detached manner.
102
+
103
+ Args:
104
+ command (List[str]): Command and arguments, e.g. ['xdg-open', 'file.pdf'].
105
+ working_dir (Optional[Path]): Working directory for the command.
106
+
107
+ Raises:
108
+ ValueError: If the working directory is invalid.
109
+ """
110
+ cmd_str = " ".join(command)
111
+ logger.debug("Launching background command: %s", cmd_str)
112
+
113
+ if working_dir is not None and not working_dir.is_dir():
114
+ raise ValueError(f"Invalid working directory: {working_dir}")
115
+
116
+ if sys.platform == "win32":
117
+ creationflags = (
118
+ subprocess.CREATE_NEW_PROCESS_GROUP | subprocess.DETACHED_PROCESS
119
+ )
120
+ subprocess.Popen(
121
+ command,
122
+ cwd=None if working_dir is None else str(working_dir),
123
+ creationflags=creationflags,
124
+ stdout=subprocess.DEVNULL,
125
+ stderr=subprocess.DEVNULL,
126
+ )
127
+ else:
128
+ subprocess.Popen(
129
+ command,
130
+ cwd=None if working_dir is None else str(working_dir),
131
+ start_new_session=True,
132
+ stdout=subprocess.DEVNULL,
133
+ stderr=subprocess.DEVNULL,
134
+ )
godotkit/common/git.py ADDED
@@ -0,0 +1,228 @@
1
+ import logging
2
+ import re
3
+ import shutil
4
+ import subprocess
5
+ import tempfile
6
+ from pathlib import Path
7
+ from urllib.parse import urlparse
8
+
9
+ from godotkit.constants import GIT_CLONE_TIMEOUT
10
+
11
+ logger = logging.getLogger(__name__)
12
+
13
+ _GIT_INSTALLED: bool | None = None
14
+
15
+
16
+ def git_installed() -> bool:
17
+ """
18
+ Checks if Git is installed on the system.
19
+
20
+ Returns:
21
+ True if Git is installed, False otherwise.
22
+ """
23
+ global _GIT_INSTALLED
24
+
25
+ if _GIT_INSTALLED is not None:
26
+ return _GIT_INSTALLED
27
+ else:
28
+ git_path = shutil.which("git")
29
+ if git_path is None:
30
+ logger.warning("Git is not installed or not found in PATH.")
31
+ _GIT_INSTALLED = False
32
+ return False
33
+
34
+ logger.debug("Git found at: %s", git_path)
35
+ _GIT_INSTALLED = True
36
+ return True
37
+
38
+
39
+ def init_repo(
40
+ dir_path: Path,
41
+ gitignore: str | None = None,
42
+ gitattributes: str | None = None,
43
+ initial_branch: str = "main",
44
+ ) -> bool:
45
+ """
46
+ Initializes a Git repository in the given directory.
47
+
48
+ Args:
49
+ dir_path: The directory where the repository will be initialized.
50
+ gitignore: Optional content for the .gitignore file.
51
+ gitattributes: Optional content for the .gitattributes file.
52
+ initial_branch: The name to use for the initial branch.
53
+
54
+ Returns:
55
+ True if initialization was successful, False otherwise.
56
+ """
57
+ if not re.match(r"^[a-zA-Z0-9_\-\./]+$", initial_branch):
58
+ logger.error("Invalid branch name provided: '%s'.", initial_branch)
59
+ return False
60
+
61
+ if not git_installed():
62
+ logger.error("Git is not installed. Skipping initialization.")
63
+ return False
64
+
65
+ dir_path.mkdir(parents=True, exist_ok=True)
66
+ try:
67
+ subprocess.run(
68
+ ["git", "init", "-b", initial_branch],
69
+ cwd=dir_path,
70
+ check=True,
71
+ capture_output=True,
72
+ text=True,
73
+ )
74
+ logger.info("Successfully initialized Git repository in %s", dir_path)
75
+ if gitignore:
76
+ (dir_path / ".gitignore").write_text(
77
+ gitignore, encoding="utf-8", newline="\n"
78
+ )
79
+ if gitattributes:
80
+ (dir_path / ".gitattributes").write_text(
81
+ gitattributes, encoding="utf-8", newline="\n"
82
+ )
83
+ return True
84
+ except subprocess.CalledProcessError as e:
85
+ logger.error(
86
+ "Failed to initialize Git repository: %s. Command: %s",
87
+ e.stderr.strip(),
88
+ " ".join(e.cmd),
89
+ )
90
+ return False
91
+ except Exception:
92
+ logger.exception("An unexpected error occurred during Git initialization")
93
+ return False
94
+
95
+
96
+ def clone(
97
+ repo_url: str,
98
+ output_dir: str | Path,
99
+ repo_name: str | None = None,
100
+ overwrite: bool = False,
101
+ depth: int | None = None,
102
+ ) -> Path:
103
+ """
104
+ Clones a Git repository into a specified output directory.
105
+
106
+ Args:
107
+ repo_url: The URL of the Git repository to clone.
108
+ output_dir: The directory where the repository will be cloned into.
109
+ repo_name: Optional name for the cloned directory. Defaults to the repository's name from the URL.
110
+ overwrite: If True, replaces an existing directory once the new clone
111
+ has succeeded; a failed clone leaves it untouched. If False and the
112
+ directory exists, skips.
113
+ depth: Optional integer for a shallow clone ('--depth').
114
+
115
+ Raises:
116
+ RuntimeError: If Git is not installed or the Git command fails.
117
+ ValueError: If a repository name cannot be extracted from the URL.
118
+ OSError: If the existing directory cannot be swapped out (e.g. a file in it is open).
119
+
120
+ Returns:
121
+ The Path object to the newly cloned (or existing) repository directory.
122
+ """
123
+ if not git_installed():
124
+ logger.error("Clone aborted: Git is not installed.")
125
+ raise RuntimeError("Git is not installed")
126
+
127
+ output_dir = Path(output_dir)
128
+ output_dir.mkdir(parents=True, exist_ok=True)
129
+
130
+ final_repo_name = _get_repo_name(repo_url, repo_name)
131
+ repo_path = output_dir / final_repo_name
132
+ logger.debug("Target repository path: %s", repo_path)
133
+
134
+ if not repo_path.exists():
135
+ _execute_git_clone(repo_url, repo_path, depth)
136
+ elif overwrite:
137
+ _replace_with_clone(repo_url, repo_path, depth)
138
+ else:
139
+ logger.info("Clone skipped, returning existing path: %s", repo_path)
140
+ return repo_path
141
+
142
+ logger.info("Successfully cloned repository to: %s", repo_path)
143
+ return repo_path
144
+
145
+
146
+ def _get_repo_name(repo_url: str, repo_name: str | None) -> str:
147
+ if repo_name:
148
+ logger.debug("Using user-provided repository name: %s", repo_name)
149
+ return repo_name
150
+
151
+ parsed_url = urlparse(repo_url)
152
+ path_stem = Path(parsed_url.path).stem
153
+
154
+ if not path_stem:
155
+ logger.debug(
156
+ "Failed to extract name using Path.stem, trying manual split on path: %s",
157
+ parsed_url.path,
158
+ )
159
+ path_stem = parsed_url.path.rstrip("/").split("/")[-1]
160
+
161
+ if not path_stem:
162
+ logger.error("Could not extract a valid repository name from URL: %s", repo_url)
163
+ raise ValueError(
164
+ f"Could not extract a valid repository name from URL: {repo_url}"
165
+ )
166
+
167
+ return path_stem
168
+
169
+
170
+ def _replace_with_clone(repo_url: str, repo_path: Path, depth: int | None) -> None:
171
+ """Clones beside `repo_path`, then swaps it in; the old copy is only dropped on success."""
172
+ logger.warning("Directory %s exists. Replacing it with a fresh clone.", repo_path)
173
+
174
+ with tempfile.TemporaryDirectory(
175
+ dir=repo_path.parent, prefix=".godotkit-clone-", ignore_cleanup_errors=True
176
+ ) as tmp:
177
+ staged = Path(tmp) / "new"
178
+ backup = Path(tmp) / "old"
179
+
180
+ _execute_git_clone(repo_url, staged, depth)
181
+
182
+ repo_path.rename(backup)
183
+ try:
184
+ staged.rename(repo_path)
185
+ except OSError:
186
+ backup.rename(repo_path)
187
+ raise
188
+
189
+
190
+ def _execute_git_clone(repo_url: str, repo_path: Path, depth: int | None) -> None:
191
+ command = ["git", "clone"]
192
+ if depth is not None and depth > 0:
193
+ command.extend(["--depth", str(depth)])
194
+
195
+ command.extend([repo_url, str(repo_path)])
196
+
197
+ logger.debug("Executing git command: %s", " ".join(command))
198
+
199
+ try:
200
+ result = subprocess.run(
201
+ command,
202
+ check=True,
203
+ capture_output=True,
204
+ text=True,
205
+ timeout=GIT_CLONE_TIMEOUT,
206
+ )
207
+ logger.debug("Git clone finished. Stdout: %s", result.stdout.strip())
208
+ logger.debug("Git clone finished. Stderr: %s", result.stderr.strip())
209
+ except subprocess.CalledProcessError as e:
210
+ logger.error(
211
+ "Git clone failed with return code %d: %s", e.returncode, e.stderr.strip()
212
+ )
213
+ raise RuntimeError(
214
+ f"Git clone failed for '{repo_url}': {e.stderr.strip()}"
215
+ ) from e
216
+ except FileNotFoundError as e:
217
+ logger.critical("Git executable not found in PATH during execution.")
218
+ raise RuntimeError("Git command not found during execution") from e
219
+ except subprocess.TimeoutExpired as e:
220
+ logger.error(
221
+ "Git clone timed out after %d seconds for '%s'.",
222
+ GIT_CLONE_TIMEOUT,
223
+ repo_url,
224
+ )
225
+ raise RuntimeError(f"Git clone timed out for '{repo_url}'.") from e
226
+ except OSError as e:
227
+ logger.critical("Unexpected exception during git clone: %s", e)
228
+ raise RuntimeError(f"Unexpected error during cloning: {e}") from e
godotkit/constants.py ADDED
@@ -0,0 +1,11 @@
1
+ import platform
2
+
3
+ from godotkit import __version__
4
+
5
+ USER_AGENT = f"godotkit v{__version__} (Python: v{platform.python_version()}, Platform: {platform.system()})"
6
+
7
+ GIT_CLONE_TIMEOUT = 300
8
+ RELEASE_FETCHER_TIMEOUT = 10
9
+ RELEASE_CACHE_TTL = 3600
10
+ RELEASE_DOWNLOAD_TIMEOUT = 30
11
+ RSS_FETCHER_TIMEOUT = 10
@@ -0,0 +1,24 @@
1
+ from . import utils
2
+ from .engine import GodotEngine
3
+ from .exceptions import DownloadError, ExtractError
4
+ from .release_fetcher import (
5
+ GodotAsset,
6
+ GodotFetcher,
7
+ GodotRelease,
8
+ detect_architecture,
9
+ detect_platform,
10
+ )
11
+ from .version_parsing import GodotVersion
12
+
13
+ __all__ = [
14
+ "DownloadError",
15
+ "ExtractError",
16
+ "GodotAsset",
17
+ "GodotEngine",
18
+ "GodotFetcher",
19
+ "GodotRelease",
20
+ "GodotVersion",
21
+ "detect_architecture",
22
+ "detect_platform",
23
+ "utils",
24
+ ]
@@ -0,0 +1,60 @@
1
+ from pathlib import Path
2
+
3
+ from godotkit.project.utils import start as start_project
4
+
5
+ from .utils import find_binary, open_directory, remove, start
6
+ from .version_parsing import GodotVersion
7
+
8
+
9
+ class GodotEngine:
10
+ def __init__(self, version: GodotVersion, engine_dir: Path):
11
+ self.version = version
12
+ self.directory_path = engine_dir
13
+
14
+ bin_file = find_binary(engine_dir)
15
+ if bin_file:
16
+ self.binary_path = bin_file
17
+ else:
18
+ raise ValueError("Cannot find Godot binary")
19
+
20
+ def start(self) -> None:
21
+ """
22
+ Launches the Godot Engine executable.
23
+
24
+ Raises:
25
+ ValueError: If the provided path is not a valid file.
26
+ """
27
+ start(self.binary_path)
28
+
29
+ def start_project(self, project_path: Path) -> None:
30
+ """
31
+ Launches the provided project file with this version of the Godot Engine.
32
+
33
+ Args:
34
+ project_path (Path): The '.godot' project file path.
35
+
36
+ Raises:
37
+ ValueError: If the provided path is not a valid file.
38
+ """
39
+ start_project(self.binary_path, project_path)
40
+
41
+ def open_directory(self) -> None:
42
+ """
43
+ Opens the engine directory in the native file manager.
44
+
45
+ Raises:
46
+ ValueError: If the path is not a valid directory.
47
+ NotImplementedError: If the current platform is unsupported.
48
+ """
49
+ open_directory(self.directory_path)
50
+
51
+ def remove(self) -> None:
52
+ """
53
+ Recursively removes the Godot Engine installation directory.
54
+
55
+ Raises:
56
+ ValueError: If the path does not exist or is not a directory.
57
+ OSError: If an OS-related error occurs during deletion.
58
+ PermissionError: If the process lacks permission to delete files or subdirectories.
59
+ """
60
+ remove(self.directory_path)
@@ -0,0 +1,6 @@
1
+ class DownloadError(Exception):
2
+ pass
3
+
4
+
5
+ class ExtractError(Exception):
6
+ pass