codeasier-gitcode-mcp 0.3.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.
- codeasier_gitcode_mcp-0.3.0.dist-info/METADATA +144 -0
- codeasier_gitcode_mcp-0.3.0.dist-info/RECORD +20 -0
- codeasier_gitcode_mcp-0.3.0.dist-info/WHEEL +4 -0
- codeasier_gitcode_mcp-0.3.0.dist-info/entry_points.txt +3 -0
- codeasier_gitcode_mcp-0.3.0.dist-info/licenses/LICENSE +21 -0
- gitcode_mcp/__init__.py +3 -0
- gitcode_mcp/__main__.py +83 -0
- gitcode_mcp/api.py +285 -0
- gitcode_mcp/askpass.py +40 -0
- gitcode_mcp/clone.py +208 -0
- gitcode_mcp/config.py +170 -0
- gitcode_mcp/file_writes.py +132 -0
- gitcode_mcp/oauth.py +636 -0
- gitcode_mcp/oauth_config.py +135 -0
- gitcode_mcp/oauth_http.py +163 -0
- gitcode_mcp/oauth_store.py +431 -0
- gitcode_mcp/oauth_upstream.py +320 -0
- gitcode_mcp/server.py +218 -0
- gitcode_mcp/smoke.py +64 -0
- gitcode_mcp/tools.py +689 -0
gitcode_mcp/clone.py
ADDED
|
@@ -0,0 +1,208 @@
|
|
|
1
|
+
"""Clone into the caller's coding environment, separate from remote MCP tools."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import argparse
|
|
6
|
+
import json
|
|
7
|
+
import os
|
|
8
|
+
import re
|
|
9
|
+
import shlex
|
|
10
|
+
import subprocess
|
|
11
|
+
import sys
|
|
12
|
+
import tempfile
|
|
13
|
+
from pathlib import Path
|
|
14
|
+
from typing import Any
|
|
15
|
+
|
|
16
|
+
from .config import ConfigurationError, Settings, repository_name
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
class CloneError(RuntimeError):
|
|
20
|
+
"""A safe, actionable error without captured Git output or credentials."""
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def _git(args: list[str], env: dict[str, str], timeout: int, *, allow_missing: bool = False) -> str:
|
|
24
|
+
try:
|
|
25
|
+
completed = subprocess.run(
|
|
26
|
+
["git", *args],
|
|
27
|
+
env=env,
|
|
28
|
+
capture_output=True,
|
|
29
|
+
text=True,
|
|
30
|
+
encoding="utf-8",
|
|
31
|
+
errors="replace",
|
|
32
|
+
timeout=timeout,
|
|
33
|
+
check=False,
|
|
34
|
+
)
|
|
35
|
+
except FileNotFoundError:
|
|
36
|
+
raise CloneError("Git is not installed in this execution environment.") from None
|
|
37
|
+
except subprocess.TimeoutExpired:
|
|
38
|
+
raise CloneError(
|
|
39
|
+
"Git timed out. Inspect the destination before retrying; no existing files were deleted."
|
|
40
|
+
) from None
|
|
41
|
+
if completed.returncode and not (allow_missing and completed.returncode == 1):
|
|
42
|
+
# Git can echo remote responses, credential-helper failures or expanded URLs.
|
|
43
|
+
raise CloneError(
|
|
44
|
+
"Git failed. Check the repository, ref, network and Git credentials in this environment. "
|
|
45
|
+
"Captured output is withheld because it may contain credentials. Inspect any partial destination before retrying."
|
|
46
|
+
)
|
|
47
|
+
return completed.stdout.strip()
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def clone_repository(
|
|
51
|
+
repository: str,
|
|
52
|
+
destination: str | Path,
|
|
53
|
+
*,
|
|
54
|
+
branch: str | None = None,
|
|
55
|
+
depth: int | None = None,
|
|
56
|
+
ssh: bool = False,
|
|
57
|
+
timeout: int = 300,
|
|
58
|
+
env: dict[str, str] | None = None,
|
|
59
|
+
) -> dict[str, Any]:
|
|
60
|
+
"""Clone with temporary credentials, then check out without the PAT in the environment."""
|
|
61
|
+
repository = repository_name(repository)
|
|
62
|
+
environment = dict(os.environ if env is None else env)
|
|
63
|
+
settings = Settings.from_env(environment)
|
|
64
|
+
if settings.allowed_repositories and repository not in settings.allowed_repositories:
|
|
65
|
+
raise ConfigurationError("Repository is not in GITCODE_MCP_ALLOWED_REPOS.")
|
|
66
|
+
if branch and (branch.startswith("-") or any(c in branch for c in "\r\n\x00")):
|
|
67
|
+
raise ConfigurationError("Invalid branch name.")
|
|
68
|
+
if depth is not None and not 1 <= depth <= 1_000_000:
|
|
69
|
+
raise ConfigurationError("Depth must be between 1 and 1000000.")
|
|
70
|
+
if not 1 <= timeout <= 3600:
|
|
71
|
+
raise ConfigurationError("Timeout must be between 1 and 3600 seconds.")
|
|
72
|
+
destination = Path(destination).expanduser()
|
|
73
|
+
if destination.exists() or destination.is_symlink():
|
|
74
|
+
raise CloneError(
|
|
75
|
+
"Destination already exists. Choose a new directory; existing files are never overwritten."
|
|
76
|
+
)
|
|
77
|
+
destination = destination.resolve()
|
|
78
|
+
if not destination.parent.is_dir():
|
|
79
|
+
raise CloneError("Destination parent directory must already exist.")
|
|
80
|
+
username = environment.get("GITCODE_USERNAME", "")
|
|
81
|
+
use_pat = bool(settings.token and not ssh)
|
|
82
|
+
if use_pat and not re.fullmatch(r"[A-Za-z0-9_.@-]+", username):
|
|
83
|
+
raise ConfigurationError(
|
|
84
|
+
"Set GITCODE_USERNAME to your GitCode login for temporary HTTPS PAT authentication, "
|
|
85
|
+
"or use --ssh / an existing Git credential helper without GITCODE_TOKEN and GC_TOKEN."
|
|
86
|
+
)
|
|
87
|
+
if use_pat and os.name != "posix":
|
|
88
|
+
raise ConfigurationError(
|
|
89
|
+
"Temporary PAT authentication requires a POSIX shell; use SSH or a Git credential helper on this platform."
|
|
90
|
+
)
|
|
91
|
+
|
|
92
|
+
# Keep credentials out of checkout filters/hooks and any diagnostic Git tracing.
|
|
93
|
+
for key in list(environment):
|
|
94
|
+
if key in {
|
|
95
|
+
"GITCODE_TOKEN",
|
|
96
|
+
"GC_TOKEN",
|
|
97
|
+
"GITCODE_MCP_HTTP_TOKEN",
|
|
98
|
+
"GITCODE_CLONE_TOKEN",
|
|
99
|
+
"GITCODE_CLONE_USERNAME",
|
|
100
|
+
"GIT_CURL_VERBOSE",
|
|
101
|
+
} or key.startswith("GIT_TRACE"):
|
|
102
|
+
environment.pop(key, None)
|
|
103
|
+
environment.update({"GIT_TERMINAL_PROMPT": "0", "LC_ALL": "C"})
|
|
104
|
+
if branch:
|
|
105
|
+
_git(["check-ref-format", "--branch", branch], environment, 10)
|
|
106
|
+
|
|
107
|
+
url = f"git@gitcode.com:{repository}.git" if ssh else f"https://gitcode.com/{repository}.git"
|
|
108
|
+
with tempfile.TemporaryDirectory(prefix="gitcode-clone-") as temporary:
|
|
109
|
+
temporary_path = Path(temporary)
|
|
110
|
+
hooks = temporary_path / "hooks"
|
|
111
|
+
hooks.mkdir()
|
|
112
|
+
template = temporary_path / "template"
|
|
113
|
+
template.mkdir()
|
|
114
|
+
options = [
|
|
115
|
+
"-c",
|
|
116
|
+
f"core.hooksPath={hooks}",
|
|
117
|
+
"-c",
|
|
118
|
+
f"init.templateDir={template}",
|
|
119
|
+
"-c",
|
|
120
|
+
"http.followRedirects=false",
|
|
121
|
+
]
|
|
122
|
+
network_env = environment.copy()
|
|
123
|
+
if use_pat:
|
|
124
|
+
askpass = temporary_path / "askpass"
|
|
125
|
+
askpass.write_text(
|
|
126
|
+
f'#!/bin/sh\nexec {shlex.quote(sys.executable)} -I -m gitcode_mcp.askpass "$@"\n',
|
|
127
|
+
encoding="utf-8",
|
|
128
|
+
)
|
|
129
|
+
askpass.chmod(0o700)
|
|
130
|
+
network_env.update(
|
|
131
|
+
{
|
|
132
|
+
"GIT_ASKPASS": str(askpass),
|
|
133
|
+
"GITCODE_CLONE_TOKEN": settings.token,
|
|
134
|
+
"GITCODE_CLONE_USERNAME": username,
|
|
135
|
+
}
|
|
136
|
+
)
|
|
137
|
+
# Reset helpers so Git cannot persist this transient PAT after a successful clone.
|
|
138
|
+
options.extend(["-c", "credential.helper="])
|
|
139
|
+
args = [*options, "clone", "--quiet", "--no-checkout"]
|
|
140
|
+
if branch:
|
|
141
|
+
args.extend(["--branch", branch])
|
|
142
|
+
if depth is not None:
|
|
143
|
+
args.extend(["--depth", str(depth)])
|
|
144
|
+
args.extend(["--", url, str(destination)])
|
|
145
|
+
try:
|
|
146
|
+
destination.mkdir(mode=0o700)
|
|
147
|
+
except FileExistsError:
|
|
148
|
+
raise CloneError(
|
|
149
|
+
"Destination was created by another process; choose a new directory."
|
|
150
|
+
) from None
|
|
151
|
+
_git(args, network_env, timeout)
|
|
152
|
+
# No network credential environment during checkout. Git filters may execute local programs.
|
|
153
|
+
head = _git(
|
|
154
|
+
["-C", str(destination), "rev-parse", "--verify", "--quiet", "HEAD"],
|
|
155
|
+
environment,
|
|
156
|
+
10,
|
|
157
|
+
allow_missing=True,
|
|
158
|
+
)
|
|
159
|
+
if head:
|
|
160
|
+
# A fresh clone owns this new directory. Populate it without detaching its branch.
|
|
161
|
+
_git(
|
|
162
|
+
[*options, "-C", str(destination), "reset", "--quiet", "--hard", "HEAD"],
|
|
163
|
+
environment,
|
|
164
|
+
timeout,
|
|
165
|
+
)
|
|
166
|
+
return {
|
|
167
|
+
"repository": repository,
|
|
168
|
+
"path": str(destination),
|
|
169
|
+
"head_sha": head or None,
|
|
170
|
+
"clone_url": url,
|
|
171
|
+
"execution_scope": "local_process",
|
|
172
|
+
"authentication": "temporary_pat" if use_pat else "existing_git_credentials",
|
|
173
|
+
"note": "This directory exists only in the environment that ran gitcode-clone. No push credentials were saved by this helper.",
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
|
|
177
|
+
def main(argv: list[str] | None = None) -> int:
|
|
178
|
+
parser = argparse.ArgumentParser(description="Clone GitCode into this execution environment")
|
|
179
|
+
parser.add_argument("repository", help="owner/repo (no token or URL)")
|
|
180
|
+
parser.add_argument("destination", help="new local directory")
|
|
181
|
+
parser.add_argument("--branch", help="branch or tag to clone")
|
|
182
|
+
parser.add_argument("--depth", type=int, help="shallow clone depth")
|
|
183
|
+
parser.add_argument("--ssh", action="store_true", help="use existing SSH authentication")
|
|
184
|
+
parser.add_argument("--timeout", type=int, default=300, help="Git operation timeout in seconds")
|
|
185
|
+
args = parser.parse_args(argv)
|
|
186
|
+
try:
|
|
187
|
+
payload = clone_repository(
|
|
188
|
+
args.repository,
|
|
189
|
+
args.destination,
|
|
190
|
+
branch=args.branch,
|
|
191
|
+
depth=args.depth,
|
|
192
|
+
ssh=args.ssh,
|
|
193
|
+
timeout=args.timeout,
|
|
194
|
+
)
|
|
195
|
+
except (ConfigurationError, CloneError, OSError) as exc:
|
|
196
|
+
message = (
|
|
197
|
+
str(exc)
|
|
198
|
+
if isinstance(exc, (ConfigurationError, CloneError))
|
|
199
|
+
else "Cannot create the destination or temporary helper files."
|
|
200
|
+
)
|
|
201
|
+
print(message, file=sys.stderr)
|
|
202
|
+
return 1
|
|
203
|
+
print(json.dumps(payload, ensure_ascii=False))
|
|
204
|
+
return 0
|
|
205
|
+
|
|
206
|
+
|
|
207
|
+
if __name__ == "__main__":
|
|
208
|
+
raise SystemExit(main())
|
gitcode_mcp/config.py
ADDED
|
@@ -0,0 +1,170 @@
|
|
|
1
|
+
"""Process configuration; credentials never enter tool schemas or reprs."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import os
|
|
6
|
+
import re
|
|
7
|
+
from collections.abc import Mapping
|
|
8
|
+
from dataclasses import dataclass, field
|
|
9
|
+
from typing import TYPE_CHECKING
|
|
10
|
+
from urllib.parse import urlsplit
|
|
11
|
+
|
|
12
|
+
if TYPE_CHECKING:
|
|
13
|
+
from .oauth_config import OAuthSettings
|
|
14
|
+
|
|
15
|
+
_COMPONENT = r"[A-Za-z0-9_][A-Za-z0-9_.-]*"
|
|
16
|
+
_REPOSITORY = re.compile(rf"{_COMPONENT}/{_COMPONENT}\Z")
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
class ConfigurationError(ValueError):
|
|
20
|
+
"""An actionable configuration error that contains no credential values."""
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def repository_name(value: str) -> str:
|
|
24
|
+
"""Accept a canonical owner/repo identifier, never a URL or filesystem path."""
|
|
25
|
+
if not _REPOSITORY.fullmatch(value) or any(x.endswith(".git") for x in value.split("/")):
|
|
26
|
+
raise ConfigurationError(
|
|
27
|
+
"Repository must be an owner/repo identifier without .git or a URL."
|
|
28
|
+
)
|
|
29
|
+
if any(".." in x for x in value.split("/")):
|
|
30
|
+
raise ConfigurationError("Repository identifiers must not contain '..'.")
|
|
31
|
+
return value
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def _boolean(env: Mapping[str, str], name: str, default: bool = False) -> bool:
|
|
35
|
+
value = env.get(name, str(default)).strip().lower()
|
|
36
|
+
if value in {"true", "1", "yes"}:
|
|
37
|
+
return True
|
|
38
|
+
if value in {"false", "0", "no"}:
|
|
39
|
+
return False
|
|
40
|
+
raise ConfigurationError(f"{name} must be true or false.")
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def _number(env: Mapping[str, str], name: str, default: str, low: float, high: float) -> float:
|
|
44
|
+
try:
|
|
45
|
+
value = float(env.get(name, default))
|
|
46
|
+
except ValueError:
|
|
47
|
+
raise ConfigurationError(f"{name} must be a number.") from None
|
|
48
|
+
if not low <= value <= high:
|
|
49
|
+
raise ConfigurationError(f"{name} must be between {low:g} and {high:g}.")
|
|
50
|
+
return value
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
@dataclass(frozen=True)
|
|
54
|
+
class Settings:
|
|
55
|
+
token: str = field(default="", repr=False)
|
|
56
|
+
http_token: str = field(default="", repr=False)
|
|
57
|
+
read_only: bool = False
|
|
58
|
+
allowed_repositories: tuple[str, ...] = ()
|
|
59
|
+
timeout: float = 30.0
|
|
60
|
+
max_response_bytes: int = 2_000_000
|
|
61
|
+
allowed_hosts: tuple[str, ...] = ("127.0.0.1:*", "localhost:*", "[::1]:*")
|
|
62
|
+
allowed_origins: tuple[str, ...] = (
|
|
63
|
+
"http://127.0.0.1:*",
|
|
64
|
+
"http://localhost:*",
|
|
65
|
+
"http://[::1]:*",
|
|
66
|
+
)
|
|
67
|
+
oauth: OAuthSettings | None = None
|
|
68
|
+
|
|
69
|
+
@classmethod
|
|
70
|
+
def from_env(cls, env: Mapping[str, str] | None = None) -> Settings:
|
|
71
|
+
env = os.environ if env is None else env
|
|
72
|
+
auth_mode = env.get("GITCODE_MCP_AUTH_MODE", "bearer")
|
|
73
|
+
if auth_mode not in {"bearer", "oauth"}:
|
|
74
|
+
raise ConfigurationError("GITCODE_MCP_AUTH_MODE must be bearer or oauth.")
|
|
75
|
+
oauth = None
|
|
76
|
+
if auth_mode == "oauth":
|
|
77
|
+
from .oauth_config import OAuthSettings
|
|
78
|
+
|
|
79
|
+
if any(
|
|
80
|
+
env.get(name) for name in ("GITCODE_TOKEN", "GC_TOKEN", "GITCODE_MCP_HTTP_TOKEN")
|
|
81
|
+
):
|
|
82
|
+
raise ConfigurationError(
|
|
83
|
+
"OAuth mode cannot use GITCODE_TOKEN, GC_TOKEN or GITCODE_MCP_HTTP_TOKEN. "
|
|
84
|
+
"Each connection uses its own GitCode OAuth authorization."
|
|
85
|
+
)
|
|
86
|
+
oauth = OAuthSettings.from_env(env)
|
|
87
|
+
token = env.get("GITCODE_TOKEN") or env.get("GC_TOKEN", "")
|
|
88
|
+
http_token = env.get("GITCODE_MCP_HTTP_TOKEN", "")
|
|
89
|
+
if any(c.isspace() or ord(c) < 32 for c in token + http_token):
|
|
90
|
+
raise ConfigurationError(
|
|
91
|
+
"Credentials must not contain whitespace or control characters."
|
|
92
|
+
)
|
|
93
|
+
if http_token and (len(http_token) < 32 or http_token == token):
|
|
94
|
+
raise ConfigurationError(
|
|
95
|
+
"GITCODE_MCP_HTTP_TOKEN must be at least 32 characters and different from the GitCode PAT."
|
|
96
|
+
)
|
|
97
|
+
repositories = tuple(
|
|
98
|
+
repository_name(x.strip())
|
|
99
|
+
for x in env.get("GITCODE_MCP_ALLOWED_REPOS", "").split(",")
|
|
100
|
+
if x.strip()
|
|
101
|
+
)
|
|
102
|
+
hosts = tuple(
|
|
103
|
+
x.strip()
|
|
104
|
+
for x in env.get("GITCODE_MCP_ALLOWED_HOSTS", "127.0.0.1:*,localhost:*,[::1]:*").split(
|
|
105
|
+
","
|
|
106
|
+
)
|
|
107
|
+
if x.strip()
|
|
108
|
+
)
|
|
109
|
+
if not hosts or any(
|
|
110
|
+
"/" in host or "@" in host or any(c.isspace() for c in host) or host == "*"
|
|
111
|
+
for host in hosts
|
|
112
|
+
):
|
|
113
|
+
raise ConfigurationError(
|
|
114
|
+
"GITCODE_MCP_ALLOWED_HOSTS must list explicit host names (optionally :*)."
|
|
115
|
+
)
|
|
116
|
+
origins = tuple(
|
|
117
|
+
value.strip()
|
|
118
|
+
for value in env.get(
|
|
119
|
+
"GITCODE_MCP_ALLOWED_ORIGINS",
|
|
120
|
+
"http://127.0.0.1:*,http://localhost:*,http://[::1]:*",
|
|
121
|
+
).split(",")
|
|
122
|
+
if value.strip()
|
|
123
|
+
)
|
|
124
|
+
for origin in origins:
|
|
125
|
+
# The port wildcard is retained only for the existing local development origins.
|
|
126
|
+
check = origin[:-2] if origin.endswith(":*") else origin
|
|
127
|
+
try:
|
|
128
|
+
parsed = urlsplit(check)
|
|
129
|
+
valid_origin = (
|
|
130
|
+
parsed.scheme in {"http", "https"}
|
|
131
|
+
and parsed.hostname
|
|
132
|
+
and not parsed.path
|
|
133
|
+
and not parsed.query
|
|
134
|
+
and not parsed.fragment
|
|
135
|
+
and parsed.username is None
|
|
136
|
+
and parsed.password is None
|
|
137
|
+
and parsed.port != 0
|
|
138
|
+
and "*" not in check
|
|
139
|
+
and "\\" not in check
|
|
140
|
+
and origin.isascii()
|
|
141
|
+
and not any(c.isspace() or ord(c) < 32 or ord(c) == 127 for c in origin)
|
|
142
|
+
)
|
|
143
|
+
if origin.endswith(":*") and parsed.hostname not in {
|
|
144
|
+
"localhost",
|
|
145
|
+
"127.0.0.1",
|
|
146
|
+
"::1",
|
|
147
|
+
}:
|
|
148
|
+
valid_origin = False
|
|
149
|
+
except ValueError:
|
|
150
|
+
valid_origin = False
|
|
151
|
+
if not valid_origin:
|
|
152
|
+
raise ConfigurationError("GITCODE_MCP_ALLOWED_ORIGINS must list explicit origins.")
|
|
153
|
+
if oauth:
|
|
154
|
+
if "GITCODE_MCP_ALLOWED_HOSTS" not in env:
|
|
155
|
+
hosts += (urlsplit(oauth.public_url).netloc,)
|
|
156
|
+
if "GITCODE_MCP_ALLOWED_ORIGINS" not in env:
|
|
157
|
+
origins += (oauth.public_url,)
|
|
158
|
+
return cls(
|
|
159
|
+
token=token,
|
|
160
|
+
http_token=http_token,
|
|
161
|
+
read_only=_boolean(env, "GITCODE_MCP_READ_ONLY"),
|
|
162
|
+
allowed_repositories=repositories,
|
|
163
|
+
timeout=_number(env, "GITCODE_MCP_TIMEOUT", "30", 1, 120),
|
|
164
|
+
max_response_bytes=int(
|
|
165
|
+
_number(env, "GITCODE_MCP_MAX_RESPONSE_BYTES", "2000000", 1024, 10_000_000)
|
|
166
|
+
),
|
|
167
|
+
allowed_hosts=hosts,
|
|
168
|
+
allowed_origins=origins,
|
|
169
|
+
oauth=oauth,
|
|
170
|
+
)
|
|
@@ -0,0 +1,132 @@
|
|
|
1
|
+
"""Validated, single-file publication through GitCode's Contents API.
|
|
2
|
+
|
|
3
|
+
Each call issues exactly one mutation. The public API does not document an
|
|
4
|
+
atomic multi-file commit or a branch-head compare-and-swap operation.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import base64
|
|
10
|
+
import binascii
|
|
11
|
+
import re
|
|
12
|
+
from typing import Any, Literal
|
|
13
|
+
|
|
14
|
+
from .api import GitCodeAPI, GitCodeError
|
|
15
|
+
|
|
16
|
+
MAX_FILE_BYTES = 256 * 1024
|
|
17
|
+
MAX_ENCODED_FILE_CHARS = 4 * ((MAX_FILE_BYTES + 2) // 3)
|
|
18
|
+
MAX_MESSAGE_BYTES = 4096
|
|
19
|
+
_SHA = re.compile(r"[0-9a-fA-F]{40}\Z")
|
|
20
|
+
FILE_WRITE_METHODS = {"create_file": "create", "update_file": "update", "delete_file": "delete"}
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def utf8_bytes(value: str, *, maximum: int) -> bytes:
|
|
24
|
+
"""Count encoded bytes without leaking content in validation errors."""
|
|
25
|
+
try:
|
|
26
|
+
encoded = value.encode("utf-8")
|
|
27
|
+
except UnicodeEncodeError:
|
|
28
|
+
raise ValueError("Use valid UTF-8 text without unpaired surrogates.") from None
|
|
29
|
+
if len(encoded) > maximum:
|
|
30
|
+
raise ValueError("The value exceeds the UTF-8 byte limit.")
|
|
31
|
+
return encoded
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def validate_write_branch(value: str) -> str:
|
|
35
|
+
"""Require an explicit short branch name, not a ref expression."""
|
|
36
|
+
utf8_bytes(value, maximum=1024)
|
|
37
|
+
if (
|
|
38
|
+
not value
|
|
39
|
+
or value in {"@", "HEAD"}
|
|
40
|
+
or value.startswith(("-", "/", "refs/"))
|
|
41
|
+
or value.endswith(("/", "."))
|
|
42
|
+
or ".." in value
|
|
43
|
+
or "@{" in value
|
|
44
|
+
or any(
|
|
45
|
+
character.isspace()
|
|
46
|
+
or ord(character) < 32
|
|
47
|
+
or ord(character) == 127
|
|
48
|
+
or character in "~^:?*[\\%#"
|
|
49
|
+
for character in value
|
|
50
|
+
)
|
|
51
|
+
or any(
|
|
52
|
+
not part or part.startswith(".") or part.endswith(".lock") for part in value.split("/")
|
|
53
|
+
)
|
|
54
|
+
):
|
|
55
|
+
raise ValueError("Use an explicit short Git branch name, not a tag or ref expression.")
|
|
56
|
+
return value
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def validate_commit_message(value: str) -> str:
|
|
60
|
+
utf8_bytes(value, maximum=MAX_MESSAGE_BYTES)
|
|
61
|
+
if not value.strip() or "\x00" in value:
|
|
62
|
+
raise ValueError("Provide a nonblank commit message without NUL characters.")
|
|
63
|
+
return value
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def encode_file_content(value: str, encoding: Literal["utf-8", "base64"]) -> str:
|
|
67
|
+
"""Produce the canonical Base64 required by the upstream Contents API."""
|
|
68
|
+
if encoding == "utf-8":
|
|
69
|
+
content = utf8_bytes(value, maximum=MAX_FILE_BYTES)
|
|
70
|
+
else:
|
|
71
|
+
if len(value) > MAX_ENCODED_FILE_CHARS:
|
|
72
|
+
raise ValueError("The file exceeds the decoded byte limit.")
|
|
73
|
+
try:
|
|
74
|
+
content = base64.b64decode(value.encode("ascii"), validate=True)
|
|
75
|
+
except (UnicodeEncodeError, binascii.Error, ValueError):
|
|
76
|
+
raise ValueError("Use canonical, padded Base64 without whitespace.") from None
|
|
77
|
+
if len(content) > MAX_FILE_BYTES:
|
|
78
|
+
raise ValueError("The file exceeds the decoded byte limit.")
|
|
79
|
+
if base64.b64encode(content).decode("ascii") != value:
|
|
80
|
+
raise ValueError("Use canonical, padded Base64 without whitespace.")
|
|
81
|
+
return base64.b64encode(content).decode("ascii")
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
def _response_sha(value: Any) -> str | None:
|
|
85
|
+
if isinstance(value, str) and _SHA.fullmatch(value):
|
|
86
|
+
return value.lower()
|
|
87
|
+
return None
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
def write_file(
|
|
91
|
+
api: GitCodeAPI, owner: str, repo: str, action: str, arguments: dict[str, Any]
|
|
92
|
+
) -> dict[str, Any]:
|
|
93
|
+
"""Publish one validated file operation and return bounded metadata.
|
|
94
|
+
|
|
95
|
+
The documented response examples disagree about whether a commit object is
|
|
96
|
+
present. A missing SHA is a verification requirement, never a reason to repeat
|
|
97
|
+
the mutation or attribute a later branch HEAD to this request.
|
|
98
|
+
"""
|
|
99
|
+
payload = dict(arguments)
|
|
100
|
+
path = payload.pop("path")
|
|
101
|
+
if "content" in payload:
|
|
102
|
+
payload["content"] = encode_file_content(payload["content"], payload.pop("encoding"))
|
|
103
|
+
# The service quotes the validated decoded path once and uses this API's
|
|
104
|
+
# bounded bearer transport. It never looks up a SHA or retries a mutation.
|
|
105
|
+
response = getattr(api.files, FILE_WRITE_METHODS[action])(owner, repo, path, **payload)
|
|
106
|
+
if response is not None and not isinstance(response, dict):
|
|
107
|
+
raise GitCodeError(
|
|
108
|
+
"invalid_response",
|
|
109
|
+
"GitCode returned an unexpected successful response.",
|
|
110
|
+
operation_may_have_completed=True,
|
|
111
|
+
)
|
|
112
|
+
response = response or {}
|
|
113
|
+
commit = response.get("commit")
|
|
114
|
+
content = response.get("content")
|
|
115
|
+
commit_sha = _response_sha(commit.get("sha")) if isinstance(commit, dict) else None
|
|
116
|
+
content_sha = _response_sha(content.get("sha")) if isinstance(content, dict) else None
|
|
117
|
+
result = {
|
|
118
|
+
"operation": action.removesuffix("_file"),
|
|
119
|
+
"status": "accepted",
|
|
120
|
+
"branch": arguments["branch"],
|
|
121
|
+
"path": path,
|
|
122
|
+
"commit_sha": commit_sha,
|
|
123
|
+
"content_sha": content_sha,
|
|
124
|
+
"verification_required": commit_sha is None,
|
|
125
|
+
}
|
|
126
|
+
if commit_sha is None:
|
|
127
|
+
result["note"] = (
|
|
128
|
+
"GitCode accepted the request but did not return a usable commit SHA. "
|
|
129
|
+
"Read the target file and branch before continuing; do not repeat the write "
|
|
130
|
+
"just to obtain a SHA. A later branch HEAD is not proof of this request's commit."
|
|
131
|
+
)
|
|
132
|
+
return {"data": result}
|