Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .claude-plugin/plugin.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
{
"name": "sourcegraph",
"description": "Search and read code in a Sourcegraph service at pinned commits, and register or maintain its repositories, through MCP or the sourcegraph CLI.",
"version": "0.8.1",
"version": "0.8.2",
"author": {
"name": "context4ai"
},
Expand Down
2 changes: 1 addition & 1 deletion cli/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ A token acts as its owner: it reads what you can read, manages repositories you
| MCP | `mcp` prints a client configuration |
| Connection | `doctor` checks DNS, each IPv4/IPv6 address, HTTPS and the sign-in, and says what to do |

`sourcegraph admin logs [--hours N] [--level warn|error|info] [--msg TEXT] [--limit N]` shows service logs of all instances (default: warnings and errors, last 24 hours).
`sourcegraph admin logs [--hours N] [--level warn|error|info] [--msg TEXT] [--contains TEXT] [--limit N] [--access]` shows service logs of all instances (default: warnings and errors, last 24 hours); `--access` reads the request log instead (one line per request with route, method, status and duration), and `--contains` keeps lines containing a text such as a request id.

`sourcegraph read <repo> <path>` prints lines 1–200 by default; `--start N` alone reads 200 lines from line N, and `--start/--end` reads a range of up to 2000 lines per call. `--all` reads the whole file page by page at the commit of the first page, with continuous line numbers. It stops after 20000 lines and still exits 0: the command that continues is printed on stderr, and `--json` output keeps `HasMore: true` and `NextStartLine`.

Expand Down
2 changes: 1 addition & 1 deletion cli/package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@c4a/sourcegraph",
"version": "0.8.1",
"version": "0.8.2",
"description": "Command-line client for Sourcegraph: search and read code at pinned commits, register and manage repositories, personal and site settings.",
"license": "MIT",
"type": "module",
Expand Down
17 changes: 14 additions & 3 deletions cli/src/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,13 @@ function unindexedNote(r: any) {
if (m.MissingObjects > 0) console.error(`note: ${m.MissingObjects} file(s) could not be read (objects missing locally) and were not searched`);
if (m.UncoveredGroups?.length) console.error(`note: not searched (contents not local at this commit): ${m.UncoveredGroups.join(', ')}`);
}
// partialNote tells a human reader why an indexed search is incomplete and
// what to do, so a short or empty answer is not read as "not in the code".
function partialNote(r: any) {
const m = r?.Meta;
if (!m?.Partial || m.Unindexed || jsonOutput) return;
console.error(`note: partial result${m.PartialReasons?.length ? ' (' + m.PartialReasons.join(', ') + ')' : ''}${m.Hint ? ': ' + m.Hint : ''}`);
}
// hybridNote tells a human reader that a commit without its own index was
// answered exactly from a nearby index plus the files changed since.
function hybridNote(r: any) {
Expand Down Expand Up @@ -372,6 +379,7 @@ const C: Record<string, Command> = {
servedNote(r);
unindexedNote(r);
hybridNote(r);
partialNote(r);
if (jsonOutput) return r;
const files = r.Result?.Files || [];
if (o.l) return files.map((f: any) => f.FileName).join('\n') || '(no matches)';
Expand Down Expand Up @@ -482,7 +490,10 @@ const C: Record<string, Command> = {
admin credentials [get] | admin credentials set <kind> [--token T|--stdin] | admin credentials clear <kind>
admin query-errors [ID] [--repo R] [--limit N] [--after CURSOR] | admin clear-jobs [--success] [--failed]
admin cluster | admin instances | admin statistics [--window MIN]
admin logs [--hours N] [--level warn|error|info] [--msg TEXT] [--limit N] service logs of all instances (default: warnings and errors, last 24 hours)`, summary: 'Site administration (administrators)', options: { query: { type: 'string' }, token: { type: 'string' }, stdin: { type: 'boolean' }, after: { type: 'string' }, success: { type: 'boolean' }, failed: { type: 'boolean' }, window: { type: 'string' }, repo: { type: 'string' }, limit: { type: 'string' }, hours: { type: 'string' }, level: { type: 'string' }, msg: { type: 'string' } }, run: async (ctx, a, o) => {
admin logs [--hours N] [--level warn|error|info] [--msg TEXT] [--contains TEXT] [--limit N] [--access]
service logs of all instances (default: warnings and errors, last 24 hours);
--access: the request log (one line per request: route, method, status, duration);
--contains: lines containing TEXT, e.g. a request id`, summary: 'Site administration (administrators)', options: { query: { type: 'string' }, token: { type: 'string' }, stdin: { type: 'boolean' }, after: { type: 'string' }, success: { type: 'boolean' }, failed: { type: 'boolean' }, window: { type: 'string' }, repo: { type: 'string' }, limit: { type: 'string' }, hours: { type: 'string' }, level: { type: 'string' }, msg: { type: 'string' }, contains: { type: 'string' }, access: { type: 'boolean' } }, run: async (ctx, a, o) => {
const [sub, ...rest] = a;
switch (sub) {
case 'settings': return siteSettings(ctx, rest);
Expand All @@ -501,9 +512,9 @@ const C: Record<string, Command> = {
case 'instances': return ctx.client.call('/api/admin/v1/instances');
case 'statistics': return ctx.client.call('/api/admin/v1/statistics', { query: { window: o.window } });
case 'logs': {
const r = await ctx.client.call('/api/admin/v1/logs', { query: { hours: o.hours, level: o.level, msg: o.msg, limit: o.limit } });
const r = await ctx.client.call('/api/admin/v1/logs', { query: { hours: o.hours, level: o.level, msg: o.msg, limit: o.limit, contains: o.contains, category: o.access ? 'access' : undefined } });
if (jsonOutput) return r;
const head = `${r.from} .. ${r.to} · ${r.level} and above · ${r.scanned_lines} lines scanned`;
const head = `${r.category === 'access' ? 'request log · ' : ''}${r.from} .. ${r.to} · ${r.level} and above · ${r.scanned_lines} lines scanned`;
const sum = table((r.summary || []).map((x: any) => ({ count: x.count, level: x.level, msg: x.msg, code: x.code || '', last: x.last })), ['count', 'level', 'msg', 'code', 'last']);
const lines = (r.lines || []).map((l: any) => { const { time, level, msg, instance, ...rest } = l; return `${time} ${level} ${instance} ${msg} ${JSON.stringify(rest)}`; }).join('\n');
return [head, '', sum, '', lines, r.truncated ? '\n(newest lines only; raise --limit or narrow with --msg)' : ''].join('\n');
Expand Down
42 changes: 42 additions & 0 deletions cli/src/search-partial.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
import { test } from 'node:test';
import assert from 'node:assert/strict';
import { createServer } from 'node:http';
import { spawn } from 'node:child_process';
import { mkdtempSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { fileURLToPath } from 'node:url';

// A search API answering one partial result with its reason and hint.
async function partialServer(meta: Record<string, unknown>) {
const server = createServer((_req, res) => {
res.setHeader('Content-Type', 'application/json');
res.end(JSON.stringify({ Meta: { Status: 'partial', Partial: true, Commit: 'a'.repeat(40), ...meta }, Result: { Files: [], FileCount: 0 } }));
});
await new Promise<void>(r => server.listen(0, '127.0.0.1', r));
return { url: `http://127.0.0.1:${(server.address() as any).port}`, close: () => server.close() };
}

function cli(url: string, ...args: string[]) {
const env = { ...process.env, XDG_CONFIG_HOME: mkdtempSync(join(tmpdir(), 'sg-cli-')) } as Record<string, string | undefined>;
delete env.SOURCEGRAPH_API_TOKEN;
delete env.SOURCEGRAPH_URL;
return new Promise<{ status: number | null; stdout: string; stderr: string }>(resolve => {
const child = spawn(process.execPath, [fileURLToPath(new URL('main.ts', import.meta.url)), '--url', url, ...args], { env });
let stdout = '', stderr = '';
child.stdout.on('data', (d: Buffer) => { stdout += d; });
child.stderr.on('data', (d: Buffer) => { stderr += d; });
child.on('close', (status: number | null) => resolve({ status, stdout, stderr }));
});
}

test('search says why a result is partial and what to do', async () => {
const s = await partialServer({ PartialReasons: ['deadline'], Hint: 'The search reached its time limit with 9465 candidate files unchecked.' });
try {
const r = await cli(s.url, 'search', '-r', 'org/repo', '-i', 'location.?auth');
assert.equal(r.status, 0);
assert.match(r.stderr, /note: partial result \(deadline\): The search reached its time limit with 9465 candidate files unchecked\./);
const json = await cli(s.url, 'search', '-r', 'org/repo', '--json', 'x');
assert.doesNotMatch(json.stderr, /partial result/);
} finally { s.close(); }
});
2 changes: 1 addition & 1 deletion cli/src/version.ts
Original file line number Diff line number Diff line change
@@ -1 +1 @@
export const VERSION = '0.8.1';
export const VERSION = '0.8.2';
7 changes: 4 additions & 3 deletions docs/interfaces.md
Original file line number Diff line number Diff line change
Expand Up @@ -72,18 +72,19 @@ Repository routes take `?repo=owner/repository`.
| `GET /sourcegraph/healthz`, `GET /sourcegraph/readyz` | Liveness and readiness |
| `GET /sourcegraph/v1/capabilities` | Supported operations |
| `GET /sourcegraph/v1/repos` | Repository catalog; signed-in callers also get each repository's `managers` |
| `GET /sourcegraph/v1/repo/catalog`, `GET /sourcegraph/v1/tag/list` | The repository catalog (`{items, next_after}`, 100 per page, `after` for the next page) and the tag counts (`{items}`) as objects, for clients that cannot take a top-level array |
| `GET /sourcegraph/v1/code-sources` | Configured code sources in display order: `id/name/host/username/anonymous/editable/locked` |
| `GET /sourcegraph/v1/repo/availability` | Indexed commits and readiness; `/v1/repo/commits` is an alias |
| `GET /sourcegraph/v1/repo/plugins` | Read plugins available for a revision |
| `POST /sourcegraph/v1/repo/resolve` | Resolve a branch, tag or SHA to a fixed commit; see [Branches, tags and resolve](#branches-tags-and-resolve) |
| `GET /sourcegraph/v1/repo/refs` | List and search branches and tags (`kind/query/author/title/since/until/sort/first/after`) |
| `POST /sourcegraph/v1/repo/read` | Read a line range |
| `POST /sourcegraph/v1/repo/read` | Read a line range; optional `PluginMode`/`Plugins` run read plugins (see [read plugins](ref/repository-plugins.md)) |
| `POST /sourcegraph/v1/repo/list` | List a directory |
| `POST /sourcegraph/v1/repo/diff` | Changed paths between two commits; `NamesOnly` returns metadata only (see [remote reads](#remote-reads)) |
| `POST /sourcegraph/v1/repo/diff` | Changed paths between two commits with patches (64 KiB per file, 256 KiB per page; one page runs two Git processes); `NamesOnly` returns metadata only (see [remote reads](#remote-reads)) |
| `POST /sourcegraph/v1/repo/blob`, `POST /sourcegraph/v1/repo/blobs` | Raw file bytes, one or a batch (see [remote reads](#remote-reads)) |
| `POST /sourcegraph/v1/repo/scope-availability` | Whether a commit and paths can be read here |
| `POST /sourcegraph/v1/repo/directories` | Every directory below a path, recursively |
| `POST /sourcegraph/api/search` | Search, with the same options as the CLI |
| `POST /sourcegraph/api/search` | Search, with the same options as the CLI. A partial answer carries `Meta.PartialReasons` (`deadline`, `match_limit`, `engine_error`, `filter_candidates`, `files_skipped`, `scan_stopped`) and `Meta.Hint` |
| `POST /sourcegraph/api/admin/v1/repo/prepare` | Queue indexing or synchronization |

Repository registration, maintenance, statistics and site settings live under `/sourcegraph/api/admin/` and are used by the website's administration pages. Use the Connect page for current request examples.
Expand Down
55 changes: 26 additions & 29 deletions internal/gitstore/diff.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@ import (
"encoding/json"
"sort"
"strings"
"unicode/utf8"

"github.com/context4ai/sourcegraph/internal/contract"
)
Expand Down Expand Up @@ -154,41 +153,39 @@ func (s *Store) PatchChanges(ctx context.Context, repo, base, head string, selec
if err != nil {
return nil, remaining, err
}
// One numstat and one patch process serve the whole page: on network
// storage each git diff re-reads both root trees, and per-file processes
// made a 100-file page take tens of seconds.
paths := make([]string, 0, len(selected))
for _, c := range selected {
paths = append(paths, c.Path)
}
binary, err := s.binaryPaths(ctx, p, base, head, paths)
if err != nil {
return nil, remaining, err
}
text := []string{}
for _, path := range paths {
if !binary[path] {
text = append(text, path)
}
}
patches, err := s.pagePatches(ctx, p, base, head, text, remaining)
if err != nil {
return nil, remaining, err
}
out := make([]Change, 0, len(selected))
for _, c := range selected {
c.Patch = ""
c.Binary = false
c.Binary = binary[c.Path]
c.PatchTruncated = false
c.OldMode, c.NewMode = "", "" // patch diffs keep their original fields
// Neither operation can execute repository-provided diff drivers or fetch.
stat, e := s.run(ctx, p, 16384, "diff", "--no-ext-diff", "--no-textconv", "--no-renames", "--numstat", "-z", base, head, "--", c.Path)
if e != nil {
return nil, remaining, e
}
c.Binary = bytes.HasPrefix(stat, []byte("-\t-\t"))
if !c.Binary && remaining > 0 {
limit := 64 << 10
if remaining < limit {
limit = remaining
}
patch, truncated, e := s.runPrefix(ctx, p, limit, "diff", "--no-ext-diff", "--no-textconv", "--no-renames", "--no-color", "--submodule=short", "--unified=3", base, head, "--", c.Path)
if e != nil {
return nil, remaining, e
}
if truncated {
// A patch over its share returns its first whole lines; only
// what is returned is taken from the page budget.
c.PatchTruncated = true
if i := bytes.LastIndexByte(patch, '\n'); i >= 0 {
patch = patch[:i+1]
} else {
patch = nil
}
}
if !utf8.Valid(patch) {
c.Binary, c.PatchTruncated = true, false
patch, truncated, ok := cutPatch(patches[c.Path], remaining)
if !ok {
c.Binary = true
} else {
c.Patch = string(patch)
c.Patch, c.PatchTruncated = string(patch), truncated
remaining -= len(patch)
}
} else if !c.Binary {
Expand Down
Loading