> ## Documentation Index
> Fetch the complete documentation index at: https://docs.archil.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Git hosting SDK reference

> archil.git in TypeScript and Python: repos, tokens, the read API, commits, forks, webhooks, shards, and errors.

Git hosting is `archil.git` on the `Archil` client, in both [SDKs](https://docs.archil.com/sdks/overview.md): the
[`disk`](https://www.npmjs.com/package/disk) package for TypeScript and the [`archil`](https://pypi.org/project/archil/)
package for Python. There is no separate package to install. To set up Git hosting first, see the
[quickstart](https://docs.archil.com/git/introduction.md#quickstart).

> [!NOTE]
>
> Git hosting is in preview, and the API may change before 1.0.

## Configure

`archil.git` uses the client's API key and your git endpoint, which the console shows on its **Git hosting** page.

```typescript TypeScript theme={null}
import { Archil } from "disk";

const archil = new Archil({
  apiKey: process.env.ARCHIL_API_KEY,
  region: "aws-us-west-2",
  git: { endpoint: process.env.ARCHIL_GIT_URL },
});
```

```python Python theme={null}
from archil import Archil

# api_key falls back to ARCHIL_API_KEY, git_endpoint to ARCHIL_GIT_URL
archil = Archil(region="aws-us-west-2", git_endpoint="https://...")
```

| Option | TypeScript | Python | Falls back to |
| - | - | - | - |
| Git endpoint | `git: { endpoint }` | `git_endpoint` | `ARCHIL_GIT_URL` |
| API key | `apiKey` | `api_key` | `ARCHIL_API_KEY` |

Use an API key from the workspace where Git hosting is enabled. Without an endpoint, every `archil.git` call fails with
code `not_configured` before sending a request.

In Python every method also has an async form, `.aio`, like the rest of the SDK:

```python theme={null}
repo = await archil.git.repos.get.aio(repo_id)
readme = await repo.blob.aio("main", "README.md")
async for r in archil.git.repos.list.aio():
    print(r.name)
```

### Edge runtimes

In TypeScript, `archil.git` runs in edge runtimes such as Cloudflare Workers and Vercel Edge Functions as well as in
Node.js. It makes only HTTPS requests to your git endpoint with `fetch`, and verifies webhooks with Web Crypto.

```typescript theme={null}
// In a Worker, with your secrets and the endpoint in env
const archil = new Archil({
  apiKey: env.ARCHIL_API_KEY,
  region: "aws-us-west-2",
  git: { endpoint: env.ARCHIL_GIT_URL },
});
```

## Repos

```typescript TypeScript theme={null}
const repo = await archil.git.repos.create({ name: "my-app", defaultBranch: "main" });
const same = await archil.git.repos.get(repo.id);

for await (const r of archil.git.repos.list()) {
  console.log(r.name, r.diskId);
}
const { repos, nextCursor } = await archil.git.repos.listPage({ limit: 50 });

await repo.delete();
```

```python Python theme={null}
repo = archil.git.repos.create(name="my-app", default_branch="main")
same = archil.git.repos.get(repo.id)

for r in archil.git.repos.list():  # follows pages
    print(r.name, r.disk_id)
page = archil.git.repos.list_page(limit=50)  # page.repos, page.next_cursor

repo.delete()
```

| Method | Does |
| - | - |
| `repos.create({ name, defaultBranch? })` | Creates a repo on a new disk. `defaultBranch` defaults to `main` |
| `repos.get(id)` | Returns one repo |
| `repos.list({ limit? })` | Iterates over every repo, following pages |
| `repos.listPage({ limit?, cursor? })` | Returns one page: `{ repos, nextCursor }` |
| `repos.delete(id, { cascade? })` or `repo.delete({ cascade? })` | Deletes the repo and its disk, LFS objects included. A repo with live forks needs `cascade`. See [Forks](https://docs.archil.com/git/forks.md#delete-a-fork) |

Python uses snake\_case: `default_branch`, `list_page`, `next_cursor`, and `cascade=True`.

A repo has these fields:

| TypeScript | Python | |
| - | - | - |
| `id` | `id` | The repo's ID. Tokens and the read API name repos by ID |
| `name` | `name` | The name you gave it |
| `remoteUrl` | `remote_url` | The HTTPS git remote, on your git endpoint |
| `defaultBranch` | `default_branch` | The branch `HEAD` points at |
| `diskId` | `disk_id` | The Archil disk that holds the repo. For a fork, the disk the fork's family shares. See [Forks](https://docs.archil.com/git/forks.md#notes) |
| `createdAt` | `created_at` | When it was created |
| `forkOf` | `fork_of` | The source repo's ID for a fork, otherwise null |

## Tokens

`git` and Git LFS accept only tokens you mint, never your API key. A token names the repos it opens, a scope, and a
lifetime of up to 24 hours. A `read` token can clone, fetch, and download LFS objects. A `write` token can also push and
upload LFS objects.

```typescript TypeScript theme={null}
const { token, expiresAt } = await archil.git.tokens.mint({
  repos: [repo, "repo_..."], // Repo objects or IDs
  scope: "write",
  ttlSeconds: 3600,
});

const creds = await archil.git.tokens.credentials(repo, { scope: "read", ttlSeconds: 600 });
creds.env;                    // environment variables for git
creds.remoteUrl;              // the plain remote
creds.authenticatedRemoteUrl; // the remote with the token embedded
```

```python Python theme={null}
minted = archil.git.tokens.mint(repos=[repo, "repo_..."], scope="write", ttl_seconds=3600)
minted.token, minted.expires_at

creds = archil.git.tokens.credentials(repo, scope="read", ttl_seconds=600)
creds.env                       # environment variables for git
creds.remote_url                # the plain remote
creds.authenticated_remote_url  # the remote with the token embedded
```

There are three ways to give `git` a token. All three helpers are exported from `disk` and from `archil.git`:

| Helper | How it works | Where the token ends up |
| - | - | - |
| `gitEnv(token, remoteUrl)` (`git_env`), also `creds.env` | Environment variables that make `git` send the token to your git endpoint as an HTTP header | Only in the process environment. Recommended |
| `authenticatedRemoteUrl(remoteUrl, token)` (`authenticated_remote_url`) | `https://t:<token>@.../my-app.git`, for a quick `git clone <url>` | In `.git/config`, and visible in process lists |
| `credentialHelper(remoteUrl)` (`credential_helper`) | Git config for a credential helper that reads the token from `$ARCHIL_GIT_TOKEN`. Apply each entry with `git config --global <key> <value>` | In the environment variable, which you refresh when the token expires |

`gitEnv` sets `GIT_CONFIG_COUNT` and replaces any `GIT_CONFIG_*` variables already in that environment.

Any HTTPS git client works with a token as the password of HTTP basic auth: the username is ignored. A request with an
API key, or with an expired token or one for another repo, is refused.

## Read API

Read refs, trees, files, history, and diffs over HTTPS, without cloning. Each method is on a `Repo`, and also on
`archil.git.repos` with the repo ID first, such as `archil.git.repos.blob(id, "main", "README.md")`.

```typescript TypeScript theme={null}
const { refs, head } = await repo.refs();
const { entries } = await repo.tree("main", "src");
const readme = await repo.blob("main", "README.md");            // Uint8Array
const stream = await repo.blobStream("main", "assets/big.bin"); // ReadableStream
const model = await repo.blob("main", "model.bin", { lfs: "resolve" });
const { commits, nextCursor } = await repo.log({ ref: "main", path: "src", limit: 20 });
const diff = await repo.compare("main", "feature/x", { patch: true });
```

```python Python theme={null}
refs = repo.refs()                                # refs.refs, refs.head
tree = repo.tree("main", "src")                   # tree.entries
readme = repo.blob("main", "README.md")           # bytes
for chunk in repo.iter_blob("main", "assets/big.bin"):
    ...
model = repo.blob("main", "model.bin", lfs="resolve")
log = repo.log(ref="main", path="src", limit=20)  # log.commits, log.next_cursor
diff = repo.compare("main", "feature/x", patch=True)
```

| Method | Returns |
| - | - |
| `refs()` | Every ref (`name`, `target`, and `peeled` for annotated tags) and `head`, the ref `HEAD` points at |
| `tree(ref, path?)` | The entries of a directory at `ref`: `name`, `path`, `type` (`blob`, `tree`, or `commit`), `mode`, `oid`, and `size` for files |
| `blob(ref, path, { lfs? })` | A file's content. With `lfs: "resolve"`, an LFS file's content instead of its pointer |
| `blobStream(ref, path, { lfs? })` (Python: `iter_blob`) | The same, streamed, for large files |
| `log({ ref?, path?, limit?, cursor? })` | A page of commits, newest first, with `nextCursor` for the next page. `path` keeps only commits that touch it |
| `compare(base, head, { patch? })` | The merge base, commits ahead and behind, changed files with line counts, and with `patch`, a unified diff |

A `ref` can be a branch, tag, or commit, and may contain slashes.

## Commits, forks, and webhooks

| Method | Guide |
| - | - |
| `repo.commit({ branch, message, author, committer?, files, baseRef?, expectedHead? })` | [Commit without git](https://docs.archil.com/git/commits.md) |
| `repo.fork({ name, ref? })` | [Forks](https://docs.archil.com/git/forks.md) |
| `archil.git.webhook.set({ url })`, and `verifyWebhook` and `verifySignature` from `disk/webhooks` | [Push webhooks](https://docs.archil.com/git/webhooks.md) |

## Shards

The git service spreads repos over shards, 4 by default. Each shard is a sandbox in your account that serves the repos
placed on it, and starts when the first repo is placed there. More shards spread pushes from many concurrent clients
over more sandboxes.

```typescript TypeScript theme={null}
await archil.git.setShardCount(8); // { count: 8 }
```

```python Python theme={null}
archil.git.set_shard_count(8)  # 8
```

The count is between 1 and 64, and applies to repos created afterward. Existing repos stay where they are. Lowering the
count only stops new repos from being placed on the highest shards.

## Errors

Failed calls throw `ArchilGitError`, exported from `disk` and from `archil.git`. In TypeScript it's an `ArchilError`
like every other SDK error. It carries:

| TypeScript | Python | |
| - | - | - |
| `status` | `status` | The HTTP status. `0` when no response arrived |
| `code` | `code` | A machine-readable code, below |
| `requestId` | `request_id` | The request's ID, for support |
| `currentHead` | `current_head` | With `head_mismatch`: the branch's head, or null if it doesn't exist |
| `forks` | `forks` | With `has_forks`: the repo's live forks, each with `id` and `name` |

| Code | When |
| - | - |
| `not_configured` | The client has no git endpoint. Raised before any request |
| `network_error` | No response arrived (`status` is `0`) |
| `head_mismatch` | A commit's `expectedHead` is stale (HTTP 409). See [Commit without git](https://docs.archil.com/git/commits.md#check-the-branch-head) |
| `path_conflict`, `path_not_found`, `branch_not_found`, `base_ref_not_found` | A commit's files or refs don't fit the repo (HTTP 422). See [Commit without git](https://docs.archil.com/git/commits.md#errors) |
| `has_forks` | Deleting a repo that has live forks, without `cascade` (HTTP 409). See [Forks](https://docs.archil.com/git/forks.md#delete-a-fork) |

Other failures carry the code the service sends. When it sends none, the code follows the HTTP status:
`bad_request` (400), `unauthorized` (401), `forbidden` (403), `not_found` (404), `conflict` (409),
`payload_too_large` (413), `rate_limited` (429), and `server_error` (5xx). Branch on `status` for these. A 502 or 503
means the git service is starting or waking up: retry the call.

```typescript TypeScript theme={null}
import { ArchilGitError } from "disk";

try {
  await archil.git.repos.get("repo_missing");
} catch (err) {
  if (err instanceof ArchilGitError && err.status === 404) {
    // handle a missing repo
  } else {
    throw err;
  }
}
```

```python Python theme={null}
from archil.git import ArchilGitError

try:
    archil.git.repos.get("repo_missing")
except ArchilGitError as e:
    if e.status != 404:
        raise
```

Webhook verification throws its own `WebhookVerificationError`. See [Push webhooks](https://docs.archil.com/git/webhooks.md#verify-deliveries).


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.