scorpiox-bot-plugin-github
←gh_api.cc
661 lines · 22 KBHEADBlameDownload
1/*
2 * gh_api.c - the one outbound HTTP call and the five REST mappings of
3 * plugin_github.
4 *
5 * Every request goes through gh_api_call(): the api base and token are
6 * resolved by gh_config.c (env > config.json > default), the URL is parsed
7 * by the transport (no hand-rolled splitting), the credential rides in
8 * "Authorization: Bearer <token>" exactly as GitHub documents, and TLS is
9 * verified by the vendored BearSSL stack - hostname check on, no downgrade,
10 * the only skip switch being the documented SX_TLS_INSECURE env var.
11 * http:// is accepted because the offline suite and self-hosted GitHub
12 * Enterprise instances use it; there is no special-cased host.
13 *
14 * Retry policy (from the connector spec): a 429 or 5xx is retried exactly
15 * once, sleeping min(Retry-After, GH_RETRY_MAX_MS). One, not a loop: a CGI
16 * request or an MCP tool call must not turn into an unbounded wait.
17 *
18 * Output policy: tool results are human-readable text built in a growable
19 * buffer and hard-capped at GH_OUT_CAP; every string taken from GitHub's
20 * JSON is copied BEFORE the document is freed (this fleet has already paid
21 * for that bug once) and JSON-escaped through gh_json_str() when it lands
22 * inside a structured section. An upstream refusal is relayed with GitHub's
23 * own {"message":...} - the user's one actionable fact is never replaced by
24 * a generic error.
25 *
26 * MIT License. Copyright (c) 2026 SCORPIOX INC.
27 */
28
29#if defined(_WIN32) && !defined(_WIN32_WINNT)
30# define _WIN32_WINNT 0x0601
31#endif
32#if !defined(_WIN32)
33# if !defined(_POSIX_C_SOURCE) || _POSIX_C_SOURCE < 200809L
34# undef _POSIX_C_SOURCE
35# define _POSIX_C_SOURCE 200809L
36# endif
37# ifndef _DEFAULT_SOURCE
38# define _DEFAULT_SOURCE 1
39# endif
40#endif
41
42#include "gh.h"
43
44#include <ctype.h>
45#include <stdio.h>
46#include <stdlib.h>
47#include <string.h>
48#include <time.h>
49
50#if defined(_WIN32)
51# include <windows.h>
52#else
53# include <unistd.h>
54#endif
55
56/* ---------------------------------------------------------------- sleep */
57
58static void gh_sleep_ms(long ms)
59{
60 if (ms <= 0) return;
61 if (ms > GH_RETRY_MAX_MS) ms = GH_RETRY_MAX_MS;
62#if defined(_WIN32)
63 Sleep((DWORD)ms);
64#else
65 {
66 struct timespec ts;
67 ts.tv_sec = ms / 1000;
68 ts.tv_nsec = (ms % 1000) * 1000000L;
69 while (nanosleep(&ts, &ts) != 0) { /* EINTR: resume */ }
70 }
71#endif
72}
73
74/* ------------------------------------------------------------ args read */
75
76int gh_arg_str(const char *args_json, const char *key, char *out, size_t capsz,
77 int required, char *err, size_t errsz)
78{
79 yyjson_doc *d;
80 yyjson_val *v;
81 int found = 0;
82
83 if (out && capsz) out[0] = '\0';
84 if (!args_json || !*args_json) args_json = "{}";
85 d = yyjson_read(args_json, strlen(args_json), 0);
86 if (!d) {
87 if (err && errsz) gh_copy(err, errsz, "arguments are not valid JSON");
88 return -1;
89 }
90 v = yyjson_obj_get(yyjson_doc_get_root(d), key);
91 if (v && yyjson_is_str(v) && yyjson_get_str(v)[0]) {
92 gh_copy(out, capsz, yyjson_get_str(v));
93 found = 1;
94 } else if (v && yyjson_is_uint(v)) {
95 char tmp[32];
96 snprintf(tmp, sizeof tmp, "%llu", (unsigned long long)yyjson_get_uint(v));
97 gh_copy(out, capsz, tmp);
98 found = 1;
99 } else if (v && yyjson_is_sint(v)) {
100 char tmp[32];
101 snprintf(tmp, sizeof tmp, "%lld", (long long)yyjson_get_sint(v));
102 gh_copy(out, capsz, tmp);
103 found = 1;
104 }
105 yyjson_doc_free(d);
106 if (!found && required && err && errsz) {
107 gh_copy(err, errsz, "missing required argument");
108 /* name the key without any format-string risk: append it verbatim */
109 {
110 char full[160];
111 snprintf(full, sizeof full, "missing required argument '%s'", key);
112 gh_copy(err, errsz, full);
113 }
114 }
115 return found;
116}
117
118int gh_arg_int(const char *args_json, const char *key, long *out_val,
119 int required, char *err, size_t errsz)
120{
121 yyjson_doc *d;
122 yyjson_val *v;
123 int found = 0;
124
125 if (out_val) *out_val = 0;
126 if (!args_json || !*args_json) args_json = "{}";
127 d = yyjson_read(args_json, strlen(args_json), 0);
128 if (!d) {
129 if (err && errsz) gh_copy(err, errsz, "arguments are not valid JSON");
130 return -1;
131 }
132 v = yyjson_obj_get(yyjson_doc_get_root(d), key);
133 if (v && yyjson_is_uint(v)) {
134 if (out_val) *out_val = (long)yyjson_get_uint(v);
135 found = 1;
136 } else if (v && yyjson_is_sint(v)) {
137 if (out_val) *out_val = (long)yyjson_get_sint(v);
138 found = 1;
139 } else if (v && yyjson_is_str(v)) {
140 char *end = NULL;
141 long x = strtol(yyjson_get_str(v), &end, 10);
142 if (end && *end == '\0' && end != yyjson_get_str(v)) {
143 if (out_val) *out_val = x;
144 found = 1;
145 }
146 }
147 yyjson_doc_free(d);
148 if (!found && required && err && errsz) {
149 char full[160];
150 snprintf(full, sizeof full, "missing required argument '%s'", key);
151 gh_copy(err, errsz, full);
152 }
153 return found;
154}
155
156/* ------------------------------------------------------------- one call */
157
158/* Join api base + path into one URL string. Both are already validated
159 * pieces; sx_url_parse then re-validates the whole thing before a byte
160 * leaves the process. */
161static void join_url(const gh_config *cfg, const char *path,
162 char *url, size_t urlsz)
163{
164 if (!path || path[0] != '/') snprintf(url, urlsz, "%s/", cfg->api_base);
165 else snprintf(url, urlsz, "%s%s", cfg->api_base, path);
166}
167
168static int one_request(const gh_config *cfg, const char *method,
169 const char *path, const char *body,
170 sx_conn *c, char **resp,
171 char *err, size_t errsz)
172{
173 char url[1536];
174 char headers[1024];
175 sx_url u;
176
177 *resp = NULL;
178 join_url(cfg, path, url, sizeof url);
179 if (sx_url_parse(url, &u, err, errsz) != 0) return -1;
180 if (sx_conn_open(c, &u, GH_HTTP_TIMEOUT_MS, err, errsz) != 0) return -1;
181
182 snprintf(headers, sizeof headers,
183 "Accept: application/vnd.github+json\r\n"
184 "X-GitHub-Api-Version: %s\r\n"
185 "User-Agent: %s\r\n"
186 "Content-Type: application/json\r\n",
187 GH_API_VERSION, GH_UA);
188
189 if (sx_http_request(c, method, u.path[0] ? u.path : "/",
190 headers, cfg->has_token ? cfg->token : NULL,
191 body, body ? strlen(body) : 0,
192 GH_HTTP_TIMEOUT_MS, err, errsz) != 0) {
193 sx_conn_close(c);
194 return -1;
195 }
196 {
197 char *buf = NULL;
198 if (sx_read_all(c, &buf, NULL, GH_HTTP_TIMEOUT_MS) != 1) {
199 free(buf);
200 sx_conn_close(c);
201 gh_copy(err, errsz, "response body read failed");
202 return -1;
203 }
204 *resp = buf ? buf : strdup("");
205 }
206 sx_conn_close(c);
207 return 0;
208}
209
210int gh_api_call(const gh_config *cfg, const char *method, const char *path,
211 const char *body, long *status, char **resp,
212 char *err, size_t errsz)
213{
214 sx_conn c;
215 long st = 0;
216 char *text = NULL;
217 int attempt;
218
219 *status = 0;
220 *resp = NULL;
221 err[0] = '\0';
222
223 for (attempt = 0; attempt < 2; attempt++) {
224 memset(&c, 0, sizeof c);
225 if (one_request(cfg, method, path, body, &c, &text, err, errsz) != 0) {
226 free(text);
227 return -1;
228 }
229 st = c.status;
230 if (attempt == 0 && (st == 429 || st >= 500)) {
231 char ra[32];
232 long wait_ms = 1000; /* one second by default */
233 if (sx_http_header(&c, "Retry-After", ra, sizeof ra)) {
234 long secs = strtol(ra, NULL, 10);
235 if (secs > 0) wait_ms = secs * 1000;
236 }
237 free(text);
238 text = NULL;
239 gh_sleep_ms(wait_ms);
240 continue;
241 }
242 break;
243 }
244
245 /* secondary rate-limit bodies ask to wait too, but a 200 with a
246 * rate_limit structure is a success, not a retry */
247 *status = st;
248 *resp = text ? text : strdup("");
249 return 0;
250}
251
252void gh_upstream_error(const char *resp, long status, char *err, size_t errsz)
253{
254 yyjson_doc *d = NULL;
255 const char *msg = NULL;
256
257 if (resp && *resp) d = yyjson_read(resp, strlen(resp), 0);
258 if (d) {
259 yyjson_val *root = yyjson_doc_get_root(d);
260 yyjson_val *m;
261 /* {"message":"..."} is the documented REST shape; GraphQL errors
262 * arrive as {"errors":[{"message":...}]} - relay either, verbatim */
263 m = root ? yyjson_obj_get(root, "message") : NULL;
264 if (m && yyjson_is_str(m)) msg = yyjson_get_str(m);
265 else if (root && yyjson_is_obj(root)) {
266 yyjson_val *errs = yyjson_obj_get(root, "errors");
267 if (errs && yyjson_is_arr(errs) && yyjson_arr_size(errs) > 0) {
268 yyjson_val *e0 = yyjson_arr_get(errs, 0);
269 yyjson_val *em = e0 ? yyjson_obj_get(e0, "message") : NULL;
270 if (em && yyjson_is_str(em)) msg = yyjson_get_str(em);
271 }
272 }
273 }
274 if (msg && *msg) {
275 /* copy BEFORE freeing: yyjson strings point into the document */
276 char safe[512];
277 gh_copy(safe, sizeof safe, msg);
278 snprintf(err, errsz, "GitHub HTTP %ld: %s", status, safe);
279 } else {
280 snprintf(err, errsz, "GitHub HTTP %ld", status);
281 }
282 if (d) yyjson_doc_free(d);
283}
284
285/* ------------------------------------------------------- shared helpers */
286
287/* Reject anything that could break a URL path segment or JSON. The rule is
288 * allow-list, not block-list: repo names cannot contain spaces, quotes, or
289 * control characters in the first place. */
290static int safe_name(const char *s, char *err, size_t errsz)
291{
292 size_t i;
293 if (!s || !*s) {
294 gh_copy(err, errsz, "empty name argument");
295 return -1;
296 }
297 for (i = 0; s[i]; i++) {
298 unsigned char c = (unsigned char)s[i];
299 if (c <= 0x20 || c >= 0x7f || c == '"' || c == '\'' || c == '\\' ||
300 c == '%' || c == '?' || c == '#' || c == '&' || c == '<' || c == '>') {
301 gh_copy(err, errsz, "name contains characters not allowed by GitHub");
302 return -1;
303 }
304 }
305 return 0;
306}
307
308/* GET a path, treat 2xx as success, otherwise emit the upstream message.
309 * Returns the parsed document (caller frees) or NULL with err filled. */
310static yyjson_doc *api_get_json(const gh_config *cfg, const char *path,
311 long *status_out, char *err, size_t errsz)
312{
313 long status = 0;
314 char *resp = NULL;
315
316 if (gh_api_call(cfg, "GET", path, NULL, &status, &resp, err, errsz) != 0)
317 return NULL;
318 if (status < 200 || status >= 300) {
319 gh_upstream_error(resp, status, err, errsz);
320 free(resp);
321 return NULL;
322 }
323 if (status_out) *status_out = status;
324 {
325 yyjson_doc *d = yyjson_read(resp, strlen(resp), 0);
326 free(resp);
327 if (!d) {
328 gh_copy(err, errsz, "GitHub returned a body that is not JSON");
329 return NULL;
330 }
331 return d;
332 }
333}
334
335static const char *jstr(yyjson_val *obj, const char *key)
336{
337 yyjson_val *v = obj ? yyjson_obj_get(obj, key) : NULL;
338 return (v && yyjson_is_str(v)) ? yyjson_get_str(v) : "";
339}
340
341static long long jint(yyjson_val *obj, const char *key, long long dflt)
342{
343 yyjson_val *v = obj ? yyjson_obj_get(obj, key) : NULL;
344 if (v && yyjson_is_uint(v)) return (long long)yyjson_get_uint(v);
345 if (v && yyjson_is_sint(v)) return (long long)yyjson_get_sint(v);
346 return dflt;
347}
348
349/* Copy a possibly-long string from a document into a bounded buffer, then
350 * append a labelled line to the buffer. All copies happen while the doc is
351 * alive (cw2). */
352static void put_field(gh_buf *b, yyjson_val *obj, const char *key,
353 const char *label)
354{
355 char val[512];
356 gh_copy(val, sizeof val, jstr(obj, key));
357 if (!val[0]) return;
358 gh_buf_printf(b, "%s: ", label);
359 gh_buf_puts(b, val);
360 gh_buf_puts(b, "\n");
361}
362
363/* ---------------------------------------------------------------- tools */
364
365int gh_tool_get_repo(const char *args_json, char *out, size_t outsz,
366 char *err, size_t errsz)
367{
368 gh_config cfg;
369 char owner[128], repo[128], path[320];
370 yyjson_doc *d;
371 yyjson_val *root;
372 gh_buf b;
373
374 owner[0] = repo[0] = '\0';
375 if (gh_arg_str(args_json, "owner", owner, sizeof owner, 1, err, errsz) <= 0) return 1;
376 if (gh_arg_str(args_json, "repo", repo, sizeof repo, 1, err, errsz) <= 0) return 1;
377 if (safe_name(owner, err, errsz) != 0 || safe_name(repo, err, errsz) != 0)
378 return 1;
379
380 gh_config_load(&cfg);
381 snprintf(path, sizeof path, "/repos/%s/%s", owner, repo);
382 d = api_get_json(&cfg, path, NULL, err, errsz);
383 if (!d) return 1;
384
385 root = yyjson_doc_get_root(d);
386 gh_buf_init(&b);
387 gh_buf_printf(&b, "repository %s/%s\n", owner, repo);
388 put_field(&b, root, "full_name", "full_name");
389 put_field(&b, root, "description", "description");
390 put_field(&b, root, "html_url", "html_url");
391 put_field(&b, root, "default_branch", "default_branch");
392 put_field(&b, root, "language", "language");
393 put_field(&b, yyjson_obj_get(root, "license"), "spdx_id", "license");
394 put_field(&b, root, "visibility", "visibility");
395 gh_buf_printf(&b, "stars: %lld\n", jint(root, "stargazers_count", 0));
396 gh_buf_printf(&b, "forks: %lld\n", jint(root, "forks_count", 0));
397 gh_buf_printf(&b, "open_issues: %lld\n", jint(root, "open_issues_count", 0));
398 gh_buf_printf(&b, "archived: %s\n",
399 yyjson_is_true(yyjson_obj_get(root, "archived")) ? "yes" : "no");
400 gh_buf_printf(&b, "pushed_at: %s\n", jstr(root, "pushed_at"));
401
402 if (b.n > GH_OUT_CAP) { /* descriptions are user data; hard cap stands */
403 out[0] = '\0';
404 }
405 gh_copy(out, outsz, gh_buf_str(&b));
406 gh_buf_free(&b);
407 yyjson_doc_free(d);
408 return 0;
409}
410
411int gh_tool_list_issues(const char *args_json, char *out, size_t outsz,
412 char *err, size_t errsz)
413{
414 gh_config cfg;
415 char owner[128], repo[128], state[16], path[384];
416 yyjson_doc *d;
417 yyjson_val *root, *it;
418 gh_buf b;
419 size_t idx, maxv, shown = 0;
420
421 owner[0] = repo[0] = '\0';
422 if (gh_arg_str(args_json, "owner", owner, sizeof owner, 1, err, errsz) <= 0) return 1;
423 if (gh_arg_str(args_json, "repo", repo, sizeof repo, 1, err, errsz) <= 0) return 1;
424 if (gh_arg_str(args_json, "state", state, sizeof state, 0, err, errsz) < 0) return 1;
425 if (!state[0]) gh_copy(state, sizeof state, "open");
426 if (strcmp(state, "open") != 0 && strcmp(state, "closed") != 0 &&
427 strcmp(state, "all") != 0) {
428 gh_copy(err, errsz, "state must be open, closed or all");
429 return 1;
430 }
431 if (safe_name(owner, err, errsz) != 0 || safe_name(repo, err, errsz) != 0)
432 return 1;
433
434 gh_config_load(&cfg);
435 snprintf(path, sizeof path,
436 "/repos/%s/%s/issues?state=%s&per_page=%d&sort=created&direction=desc",
437 owner, repo, state, GH_PER_PAGE);
438 d = api_get_json(&cfg, path, NULL, err, errsz);
439 if (!d) return 1;
440
441 root = yyjson_doc_get_root(d);
442 if (!yyjson_is_arr(root)) {
443 yyjson_doc_free(d);
444 gh_copy(err, errsz, "GitHub returned a body that is not an array");
445 return 1;
446 }
447
448 gh_buf_init(&b);
449 gh_buf_printf(&b, "issues (%s) in %s/%s\n", state, owner, repo);
450 /* upstream parity: /issues also returns pull requests; a PR carries a
451 * pull_request key, and skipping it here is exactly what the reference
452 * implementations do */
453 yyjson_arr_foreach(root, idx, maxv, it) {
454 long long num;
455 char title[300];
456 if (yyjson_obj_get(it, "pull_request") != NULL) continue;
457 num = jint(it, "number", 0);
458 gh_copy(title, sizeof title, jstr(it, "title"));
459 gh_buf_printf(&b, "#%lld", num);
460 /* a title is arbitrary user text: put it on its own escaped-safe
461 * line with control bytes replaced so nothing can forge a row */
462 {
463 size_t k;
464 for (k = 0; title[k]; k++) {
465 unsigned char ch = (unsigned char)title[k];
466 if (ch < 0x20 || ch == 0x7f) title[k] = ' ';
467 }
468 gh_buf_printf(&b, "\t%s", title);
469 }
470 gh_buf_printf(&b, "\t%s\t%s\n",
471 jstr(it, "state"), jstr(it, "html_url"));
472 shown++;
473 if (b.n > GH_OUT_CAP) break;
474 }
475 if (shown == 0) gh_buf_puts(&b, "(none)\n");
476
477 gh_copy(out, outsz, gh_buf_str(&b));
478 gh_buf_free(&b);
479 yyjson_doc_free(d);
480 return 0;
481}
482
483int gh_tool_create_issue(const char *args_json, char *out, size_t outsz,
484 char *err, size_t errsz)
485{
486 gh_config cfg;
487 char owner[128], repo[128], title[257], body_txt[4097], path[320];
488 long status = 0;
489 char *resp = NULL;
490 yyjson_doc *d;
491 gh_buf req, b;
492
493 owner[0] = repo[0] = title[0] = body_txt[0] = '\0';
494 if (gh_arg_str(args_json, "owner", owner, sizeof owner, 1, err, errsz) <= 0) return 1;
495 if (gh_arg_str(args_json, "repo", repo, sizeof repo, 1, err, errsz) <= 0) return 1;
496 if (gh_arg_str(args_json, "title", title, sizeof title, 1, err, errsz) <= 0) return 1;
497 if (gh_arg_str(args_json, "body", body_txt, sizeof body_txt, 0, err, errsz) < 0) return 1;
498 if (safe_name(owner, err, errsz) != 0 || safe_name(repo, err, errsz) != 0)
499 return 1;
500 if (!title[0]) { gh_copy(err, errsz, "title must not be empty"); return 1; }
501
502 gh_config_load(&cfg);
503 if (!cfg.has_token) {
504 gh_copy(err, errsz,
505 "no credential configured - create_issue needs a PAT; "
506 "open the plugin page and save one");
507 return 1;
508 }
509
510 /* build {"title":"...","body":"..."} with the escaper, never a format */
511 gh_buf_init(&req);
512 gh_buf_puts(&req, "{\"title\":");
513 gh_json_str(&req, title);
514 if (body_txt[0]) {
515 gh_buf_puts(&req, ",\"body\":");
516 gh_json_str(&req, body_txt);
517 }
518 gh_buf_puts(&req, "}");
519
520 snprintf(path, sizeof path, "/repos/%s/%s/issues", owner, repo);
521 if (gh_api_call(&cfg, "POST", path, gh_buf_str(&req), &status, &resp,
522 err, errsz) != 0) {
523 gh_buf_free(&req);
524 return 1;
525 }
526 gh_buf_free(&req);
527 if (status < 200 || status >= 300) {
528 gh_upstream_error(resp, status, err, errsz);
529 free(resp);
530 return 1;
531 }
532
533 d = yyjson_read(resp, strlen(resp), 0);
534 free(resp);
535 gh_buf_init(&b);
536 if (d) {
537 yyjson_val *root = yyjson_doc_get_root(d);
538 gh_buf_printf(&b, "created issue #%lld in %s/%s\n",
539 jint(root, "number", 0), owner, repo);
540 put_field(&b, root, "html_url", "html_url");
541 put_field(&b, root, "state", "state");
542 gh_copy(out, outsz, gh_buf_str(&b));
543 yyjson_doc_free(d);
544 } else {
545 snprintf(out, outsz, "created issue in %s/%s (HTTP %ld)",
546 owner, repo, status);
547 }
548 gh_buf_free(&b);
549 return 0;
550}
551
552int gh_tool_get_pull_request(const char *args_json, char *out, size_t outsz,
553 char *err, size_t errsz)
554{
555 gh_config cfg;
556 char owner[128], repo[128], path[320];
557 long number = 0;
558 yyjson_doc *d;
559 yyjson_val *root;
560 gh_buf b;
561
562 owner[0] = repo[0] = '\0';
563 if (gh_arg_str(args_json, "owner", owner, sizeof owner, 1, err, errsz) <= 0) return 1;
564 if (gh_arg_str(args_json, "repo", repo, sizeof repo, 1, err, errsz) <= 0) return 1;
565 if (gh_arg_int(args_json, "number", &number, 1, err, errsz) <= 0) return 1;
566 if (number <= 0) { gh_copy(err, errsz, "number must be a positive integer"); return 1; }
567 if (safe_name(owner, err, errsz) != 0 || safe_name(repo, err, errsz) != 0)
568 return 1;
569
570 gh_config_load(&cfg);
571 snprintf(path, sizeof path, "/repos/%s/%s/pulls/%ld", owner, repo, number);
572 d = api_get_json(&cfg, path, NULL, err, errsz);
573 if (!d) return 1;
574
575 root = yyjson_doc_get_root(d);
576 gh_buf_init(&b);
577 gh_buf_printf(&b, "pull request #%ld in %s/%s\n", number, owner, repo);
578 put_field(&b, root, "title", "title");
579 put_field(&b, root, "state", "state");
580 put_field(&b, root, "html_url", "html_url");
581 put_field(&b, yyjson_obj_get(root, "user"), "login", "author");
582 put_field(&b, yyjson_obj_get(root, "head"), "label", "head");
583 put_field(&b, yyjson_obj_get(root, "base"), "label", "base");
584 gh_buf_printf(&b, "draft: %s\n",
585 yyjson_is_true(yyjson_obj_get(root, "draft")) ? "yes" : "no");
586 gh_buf_printf(&b, "merged: %s\n",
587 yyjson_obj_get(root, "merged_at") &&
588 !yyjson_is_null(yyjson_obj_get(root, "merged_at")) ? "yes" : "no");
589 gh_buf_printf(&b, "commits: %lld comments: %lld additions: %lld deletions: %lld\n",
590 jint(root, "commits", 0), jint(root, "comments", 0),
591 jint(root, "additions", 0), jint(root, "deletions", 0));
592 put_field(&b, root, "merged_at", "merged_at");
593 put_field(&b, root, "created_at", "created_at");
594
595 gh_copy(out, outsz, gh_buf_str(&b));
596 gh_buf_free(&b);
597 yyjson_doc_free(d);
598 return 0;
599}
600
601int gh_tool_search_code(const char *args_json, char *out, size_t outsz,
602 char *err, size_t errsz)
603{
604 gh_config cfg;
605 char query[512];
606 yyjson_doc *d;
607 yyjson_val *root, *items, *it;
608 gh_buf q, pathb, b;
609 size_t idx, maxv, shown = 0;
610
611 query[0] = '\0';
612 if (gh_arg_str(args_json, "query", query, sizeof query, 1, err, errsz) <= 0)
613 return 1;
614 if (!query[0]) { gh_copy(err, errsz, "query must not be empty"); return 1; }
615
616 gh_buf_init(&q);
617 gh_url_encode(query, &q);
618
619 gh_config_load(&cfg);
620 gh_buf_init(&pathb);
621 gh_buf_printf(&pathb, "/search/code?q=%s&per_page=%d",
622 gh_buf_str(&q), GH_SEARCH_MAX_ITEMS);
623 gh_buf_free(&q);
624
625 d = api_get_json(&cfg, gh_buf_str(&pathb), NULL, err, errsz);
626 gh_buf_free(&pathb);
627 if (!d) return 1;
628
629 root = yyjson_doc_get_root(d);
630 items = yyjson_obj_get(root, "items");
631 gh_buf_init(&b);
632 gh_buf_printf(&b, "code search: %s\n", query);
633 gh_buf_printf(&b, "total_count: %lld\n", jint(root, "total_count", 0));
634 if (!items || !yyjson_is_arr(items)) {
635 gh_buf_puts(&b, "(no results)\n");
636 } else {
637 gh_buf_puts(&b, "results (path @ repo):\n");
638 yyjson_arr_foreach(items, idx, maxv, it) {
639 char name[256], pth[400], html[400];
640 yyjson_val *r = yyjson_obj_get(it, "repository");
641 gh_copy(name, sizeof name, jstr(it, "name"));
642 gh_copy(pth, sizeof pth, jstr(it, "path"));
643 gh_copy(html, sizeof html, jstr(it, "html_url"));
644 { /* every field is user data: strip control bytes so one
645 * result row cannot forge another row or a fake header */
646 size_t k;
647 for (k = 0; name[k]; k++) if ((unsigned char)name[k] < 0x20) name[k] = ' ';
648 for (k = 0; pth[k]; k++) if ((unsigned char)pth[k] < 0x20) pth[k] = ' ';
649 }
650 gh_buf_printf(&b, "%s @ %s\t%s\n", pth, jstr(r, "full_name"), html);
651 shown++;
652 if (b.n > GH_OUT_CAP) break;
653 }
654 if (shown == 0) gh_buf_puts(&b, "(none)\n");
655 }
656
657 gh_copy(out, outsz, gh_buf_str(&b));
658 gh_buf_free(&b);
659 yyjson_doc_free(d);
660 return 0;
661}