devbox-sdk 0.1.0__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.
devbox/git.py ADDED
@@ -0,0 +1,257 @@
1
+ """Git operations executed inside a sandbox through the process API.
2
+
3
+ Exposed as :attr:`Sandbox.git` / :attr:`AsyncSandbox.git`.
4
+ """
5
+
6
+ from __future__ import annotations
7
+
8
+ import shlex
9
+ from collections.abc import Mapping, Sequence
10
+ from dataclasses import dataclass, field
11
+
12
+ from .commands import AsyncCommands, Commands
13
+ from .models import CommandResult
14
+
15
+
16
+ @dataclass(frozen=True, slots=True)
17
+ class GitCredentials:
18
+ """Credentials passed to git via a sandbox-side credential helper."""
19
+
20
+ username: str
21
+ password: str = field(repr=False)
22
+
23
+ def __post_init__(self) -> None:
24
+ if not self.username or not self.password:
25
+ raise ValueError("git username and password must not be blank")
26
+
27
+
28
+ class Git:
29
+ """Common Git operations executed inside a sandbox."""
30
+
31
+ def __init__(self, commands: Commands) -> None:
32
+ self._commands = commands
33
+
34
+ def clone(
35
+ self,
36
+ url: str,
37
+ path: str,
38
+ *,
39
+ branch: str | None = None,
40
+ depth: int | None = None,
41
+ credentials: GitCredentials | None = None,
42
+ timeout: float | None = 300,
43
+ ) -> CommandResult:
44
+ """Clone a repository into the sandbox."""
45
+ command = ["git", "clone"]
46
+ if branch:
47
+ command.extend(["--branch", branch])
48
+ if depth is not None:
49
+ if depth < 1:
50
+ raise ValueError("git clone depth must be positive")
51
+ command.extend(["--depth", str(depth)])
52
+ command.extend([url, path])
53
+ return self._run(command, credentials=credentials, timeout=timeout)
54
+
55
+ def status(self, repository: str) -> CommandResult:
56
+ """Return the short status of a sandbox repository."""
57
+ return self._run(_in(repository, "status", "--short", "--branch"))
58
+
59
+ def checkout(self, repository: str, reference: str, *, create: bool = False) -> CommandResult:
60
+ """Check out a branch or reference, optionally creating it."""
61
+ arguments = ["checkout"]
62
+ if create:
63
+ arguments.append("-b")
64
+ arguments.append(reference)
65
+ return self._run(_in(repository, *arguments))
66
+
67
+ def add(self, repository: str, paths: str | Sequence[str] = ".") -> CommandResult:
68
+ """Stage one or more paths."""
69
+ values = [paths] if isinstance(paths, str) else list(paths)
70
+ if not values:
71
+ raise ValueError("at least one git path is required")
72
+ return self._run(_in(repository, "add", "--", *values))
73
+
74
+ def commit(self, repository: str, message: str) -> CommandResult:
75
+ """Commit staged changes."""
76
+ if not message.strip():
77
+ raise ValueError("commit message must not be blank")
78
+ return self._run(_in(repository, "commit", "-m", message))
79
+
80
+ def pull(
81
+ self,
82
+ repository: str,
83
+ *,
84
+ remote: str = "origin",
85
+ branch: str | None = None,
86
+ credentials: GitCredentials | None = None,
87
+ timeout: float | None = 300,
88
+ ) -> CommandResult:
89
+ """Pull changes from a remote repository."""
90
+ command = _in(repository, "pull", remote)
91
+ if branch:
92
+ command.append(branch)
93
+ return self._run(command, credentials=credentials, timeout=timeout)
94
+
95
+ def push(
96
+ self,
97
+ repository: str,
98
+ *,
99
+ remote: str = "origin",
100
+ branch: str | None = None,
101
+ credentials: GitCredentials | None = None,
102
+ timeout: float | None = 300,
103
+ ) -> CommandResult:
104
+ """Push changes to a remote repository."""
105
+ command = _in(repository, "push", remote)
106
+ if branch:
107
+ command.append(branch)
108
+ return self._run(command, credentials=credentials, timeout=timeout)
109
+
110
+ def set_config(self, repository: str, key: str, value: str) -> CommandResult:
111
+ """Set one repository-local Git configuration value."""
112
+ return self._run(_in(repository, "config", key, value))
113
+
114
+ def _run(
115
+ self,
116
+ command: Sequence[str],
117
+ *,
118
+ credentials: GitCredentials | None = None,
119
+ timeout: float | None = 60,
120
+ ) -> CommandResult:
121
+ return self._commands.run(
122
+ _shell_command(command, credentials),
123
+ envs=_credential_env(credentials),
124
+ timeout=timeout,
125
+ )
126
+
127
+
128
+ class AsyncGit:
129
+ """Asynchronous counterpart of :class:`Git`."""
130
+
131
+ def __init__(self, commands: AsyncCommands) -> None:
132
+ self._commands = commands
133
+
134
+ async def clone(
135
+ self,
136
+ url: str,
137
+ path: str,
138
+ *,
139
+ branch: str | None = None,
140
+ depth: int | None = None,
141
+ credentials: GitCredentials | None = None,
142
+ timeout: float | None = 300,
143
+ ) -> CommandResult:
144
+ """Clone a repository into the sandbox."""
145
+ command = ["git", "clone"]
146
+ if branch:
147
+ command.extend(["--branch", branch])
148
+ if depth is not None:
149
+ if depth < 1:
150
+ raise ValueError("git clone depth must be positive")
151
+ command.extend(["--depth", str(depth)])
152
+ command.extend([url, path])
153
+ return await self._run(command, credentials=credentials, timeout=timeout)
154
+
155
+ async def status(self, repository: str) -> CommandResult:
156
+ """Return the short status of a sandbox repository."""
157
+ return await self._run(_in(repository, "status", "--short", "--branch"))
158
+
159
+ async def checkout(
160
+ self, repository: str, reference: str, *, create: bool = False
161
+ ) -> CommandResult:
162
+ """Check out a branch or reference, optionally creating it."""
163
+ arguments = ["checkout"]
164
+ if create:
165
+ arguments.append("-b")
166
+ arguments.append(reference)
167
+ return await self._run(_in(repository, *arguments))
168
+
169
+ async def add(self, repository: str, paths: str | Sequence[str] = ".") -> CommandResult:
170
+ """Stage one or more paths."""
171
+ values = [paths] if isinstance(paths, str) else list(paths)
172
+ if not values:
173
+ raise ValueError("at least one git path is required")
174
+ return await self._run(_in(repository, "add", "--", *values))
175
+
176
+ async def commit(self, repository: str, message: str) -> CommandResult:
177
+ """Commit staged changes."""
178
+ if not message.strip():
179
+ raise ValueError("commit message must not be blank")
180
+ return await self._run(_in(repository, "commit", "-m", message))
181
+
182
+ async def pull(
183
+ self,
184
+ repository: str,
185
+ *,
186
+ remote: str = "origin",
187
+ branch: str | None = None,
188
+ credentials: GitCredentials | None = None,
189
+ timeout: float | None = 300,
190
+ ) -> CommandResult:
191
+ """Pull changes from a remote repository."""
192
+ command = _in(repository, "pull", remote)
193
+ if branch:
194
+ command.append(branch)
195
+ return await self._run(command, credentials=credentials, timeout=timeout)
196
+
197
+ async def push(
198
+ self,
199
+ repository: str,
200
+ *,
201
+ remote: str = "origin",
202
+ branch: str | None = None,
203
+ credentials: GitCredentials | None = None,
204
+ timeout: float | None = 300,
205
+ ) -> CommandResult:
206
+ """Push changes to a remote repository."""
207
+ command = _in(repository, "push", remote)
208
+ if branch:
209
+ command.append(branch)
210
+ return await self._run(command, credentials=credentials, timeout=timeout)
211
+
212
+ async def set_config(self, repository: str, key: str, value: str) -> CommandResult:
213
+ """Set one repository-local Git configuration value."""
214
+ return await self._run(_in(repository, "config", key, value))
215
+
216
+ async def _run(
217
+ self,
218
+ command: Sequence[str],
219
+ *,
220
+ credentials: GitCredentials | None = None,
221
+ timeout: float | None = 60,
222
+ ) -> CommandResult:
223
+ return await self._commands.run(
224
+ _shell_command(command, credentials),
225
+ envs=_credential_env(credentials),
226
+ timeout=timeout,
227
+ )
228
+
229
+
230
+ def _in(repository: str, *arguments: str) -> list[str]:
231
+ if not repository:
232
+ raise ValueError("repository path must not be blank")
233
+ return ["git", "-C", repository, *arguments]
234
+
235
+
236
+ def _shell_command(command: Sequence[str], credentials: GitCredentials | None) -> str:
237
+ arguments = list(command)
238
+ if credentials:
239
+ arguments[1:1] = [
240
+ "-c",
241
+ "credential.helper=!f() { printf '%s\\n' "
242
+ '"username=$DEVBOX_GIT_USERNAME" '
243
+ '"password=$DEVBOX_GIT_PASSWORD"; }; f',
244
+ "-c",
245
+ "credential.useHttpPath=true",
246
+ ]
247
+ return " ".join(shlex.quote(argument) for argument in arguments)
248
+
249
+
250
+ def _credential_env(credentials: GitCredentials | None) -> Mapping[str, str] | None:
251
+ if credentials is None:
252
+ return None
253
+ return {
254
+ "DEVBOX_GIT_USERNAME": credentials.username,
255
+ "DEVBOX_GIT_PASSWORD": credentials.password,
256
+ "GIT_TERMINAL_PROMPT": "0",
257
+ }