### Install Code Storage SDK (TypeScript, Python, Go)
Source: https://code.storage/docs/getting-started/quickstart
Installs the Code Storage SDK using package managers for TypeScript (pnpm), Python (pip), and Go (go get). Ensure you have the respective package managers installed.
```bash
pnpm i @pierre/storage
```
```bash
pip install pierre-storage
```
```bash
go get github.com/pierrecomputer/sdk/packages/code-storage-go@latest
```
--------------------------------
### Create Repository and Get Remote URL (TypeScript, Python, Go)
Source: https://code.storage/docs/getting-started/quickstart
Creates a new repository, optionally with a custom ID or GitHub sync. It then retrieves a secure Git remote URL for cloning or adding as a remote. Supports custom repository IDs and synchronization with existing GitHub repositories.
```typescript
// Create a new repository
const repo = await store.createRepo();
// Get a secure Git URL with authentication
const url = await repo.getRemoteURL();
// Configure Git to use the repository
console.log(`git remote add origin ${url}`);
// Output: git remote add origin https://t:JWT@[org].code.storage/repo-id.git
```
```python
# Create a new repository with auto-generated ID
repo = await storage.create_repo()
print(repo.id) # e.g., '123e4567-e89b-12d3-a456-426614174000'
# Create a repository with a custom ID
custom_repo = await storage.create_repo(id="my-custom-repo")
print(custom_repo.id) # 'my-custom-repo'
# Create a repository with GitHub sync
github_repo = await storage.create_repo(
id="my-synced-repo",
base_repo={
"owner": "octocat",
"name": "Hello-World",
"default_branch": "main", # optional
},
)
# This repository will sync with github.com/octocat/Hello-World
# Get a secure Git URL and configure Git
secure_url = await repo.get_remote_url()
print(f"git remote add origin {secure_url}")
```
```go
// Create a new repository
repo, err := client.CreateRepo(context.Background(), storage.CreateRepoOptions{})
fmt.Println(repo.ID)
// Create a repository with a custom ID
customRepo, err := client.CreateRepo(context.Background(), storage.CreateRepoOptions{
ID: "my-custom-repo",
})
// Create a repository with GitHub sync
githubRepo, err := client.CreateRepo(context.Background(), storage.CreateRepoOptions{
ID: "my-synced-repo",
BaseRepo: storage.GitHubBaseRepo{
Owner: "octocat",
Name: "Hello-World",
DefaultBranch: "main",
},
})
// Get a secure Git URL and configure Git
url, err := repo.RemoteURL(context.Background(), storage.RemoteURLOptions{})
fmt.Printf("git remote add origin %s\n", url)
```
--------------------------------
### SDK Integration Example
Source: https://code.storage/docs/reference/http-api/overview
A JavaScript example demonstrating how to use the HTTP API with a JWT and the `fetch` API to retrieve repository branches.
```APIDOC
## SDK Integration Example
### Description
This example shows how to integrate with the HTTP API using any JWT signer and the standard `fetch` API in JavaScript. It demonstrates fetching repository branch data.
### Request Example (JavaScript)
```js
// Ensure you have a valid token with the necessary claims (e.g., repo claim and git:read scope)
const token = "YOUR_JWT_TOKEN";
const baseUrl = "https://api.your-org.code.storage/api/v1";
// Fetch repository data
async function fetchBranches(baseUrl, token) {
const response = await fetch(`${baseUrl}/repos/branches?limit=20`, {
headers: {
Authorization: `Bearer ${token}`,
"Content-Type": "application/json"
},
});
if (!response.ok) {
const errorData = await response.json();
throw new Error(`API Error: ${response.status} - ${errorData.error}`);
}
const { branches } = await response.json();
console.log(`Found ${branches.length} branches`);
return branches;
}
fetchBranches(baseUrl, token).catch(console.error);
```
### Response Example (Success)
Assuming the request is successful, the response body will contain a JSON object, potentially with a `branches` field:
```json
{
"branches": [
{
"name": "main",
"commit": {
"sha": "a1b2c3d4e5f678901234567890abcdef12345678",
"message": "Initial commit"
}
},
{
"name": "develop",
"commit": {
"sha": "fedcba0987654321fedcba0987654321",
"message": "Add feature X"
}
}
],
"next_cursor": "some_cursor_value",
"has_more": true
}
```
```
--------------------------------
### Fetch Repositories using cURL (Bash)
Source: https://code.storage/docs/reference/http-api/overview
Demonstrates how to make a GET request to the '/repos' endpoint using cURL, including necessary Authorization and Content-Type headers. This is a basic example of interacting with the API.
```bash
curl "$CODE_STORAGE_BASE_URL/repos" \
-H "Authorization: Bearer $CODE_STORAGE_TOKEN" \
-H "Content-Type: application/json"
```
--------------------------------
### Install Code Storage SDK
Source: https://code.storage/docs/reference/sdk/index
Instructions for installing the Code Storage SDK using package managers for TypeScript, Python, and Go. For Python, uv is recommended over pip.
```bash
pnpm i @pierre/storage
```
```bash
# Using uv (recommended)
uv add pierre-storage
# Or using pip
pip install pierre-storage
```
```bash
go get github.com/pierrecomputer/sdk/packages/code-storage-go@latest
```
--------------------------------
### Create Repository and Initial Commit (Go)
Source: https://code.storage/docs/getting-started/quickstart
Initializes the GitStorage client using environment variables for the key, creates a repository, and makes the first commit with a README file.
```go
import (
"context"
"fmt"
"os"
"storage"
)
func createCommit() {
// Initialize the client
client, err := storage.NewClient(storage.Options{
Name: "your-name",
Key: os.Getenv("PIERRE_PRIVATE_KEY"),
})
// Create a repository
repo, err := client.CreateRepo(context.Background(), storage.CreateRepoOptions{})
fmt.Printf("Created repository: %s\n", repo.ID)
// Get the Git remote URL
url, err := repo.RemoteURL(context.Background(), storage.RemoteURLOptions{})
fmt.Printf("Git URL: %s\n", url)
// Create your first commit
builder, err := repo.CreateCommit(storage.CommitOptions{
TargetBranch: "main",
CommitMessage: "Initial commit",
Author: storage.CommitSignature{Name: "Your Name", Email: "you@example.com"},
})
result, err := builder.AddFileFromString("README.md", "# My Project\n\nWelcome!", nil).
Send(context.Background())
fmt.Printf("Commit SHA: %s\n", result.CommitSHA)
}
```
--------------------------------
### Create Git Repository and Get Secure URL (TypeScript, Python, Go)
Source: https://code.storage/docs/reference/sdk/index
Demonstrates how to create a new Git repository and generate a secure, time-limited URL for cloning or pushing. This functionality is crucial for managing code versions and enabling secure access. The examples cover TypeScript, Python, and Go, utilizing the '@pierre/storage' or equivalent libraries.
```typescript
import { GitStorage } from "@pierre/storage";
const storage = new GitStorage({
name: "your-org",
key: "your-private-key",
});
async function setupRepository() {
// Create repository
const repo = await storage.createRepo({
id: "backend/api-service",
});
// Generate secure URL
const url = await repo.getRemoteURL({
permissions: ["git:read", "git:write"],
ttl: 31536000, // 1 year
});
// Use with Git
console.log(`git clone ${url}`);
return repo;
}
```
```python
from pierre_storage import GitStorage
storage = GitStorage({
"name": "your-org",
"key": "your-private-key",
})
async def setup_repository():
repo = await storage.create_repo(id="backend/api-service")
url = await repo.get_remote_url(
permissions=["git:read", "git:write"],
ttl=31536000,
)
print(f"git clone {url}")
return repo
```
```go
// Initialize Pierre client for code storage
client, err := storage.NewClient(storage.Options{
Name: "your-org",
Key: "your-private-key",
})
// Create repository
repo, err := client.CreateRepo(context.Background(), storage.CreateRepoOptions{
ID: "backend/api-service",
})
// Generate secure URL
url, err := repo.RemoteURL(context.Background(), storage.RemoteURLOptions{
Permissions: []storage.Permission{storage.PermissionGitRead, storage.PermissionGitWrite},
TTL: 365 * 24 * time.Hour,
})
// Use with Git
fmt.Printf("git clone %s\n", url)
```
--------------------------------
### Create Repository and Initial Commit (Python)
Source: https://code.storage/docs/getting-started/quickstart
Initializes the GitStorage client, creates a new repository, and makes the first commit with a README file. Uses asyncio for asynchronous operations.
```python
import asyncio
from pierre_storage import GitStorage
async def main():
# Initialize the client
storage = GitStorage({
"name": "your-name",
"key": "-----BEGIN PRIVATE KEY-----\nYour private key here\n-----END PRIVATE KEY-----",
})
# Create a repository
repo = await storage.create_repo()
print(f"Created repository: {repo.id}")
# Get the Git remote URL
url = await repo.get_remote_url()
print(f"Git URL: {url}")
# Create your first commit
result = await (
repo.create_commit({
"target_branch": "main",
"commit_message": "Initial commit",
"author": {
"name": "Your Name",
"email": "you@example.com"
},
})
.add_file_from_string("README.md", "# My Project\n\nWelcome!")
.send()
)
print(f"Commit SHA: {result['commit_sha']}")
# Run the example
asyncio.run(main())
```
--------------------------------
### Create Repository and Initial Commit (TypeScript)
Source: https://code.storage/docs/getting-started/quickstart
Initializes the GitStorage client, creates a new repository, and makes the first commit with a README file. Requires environment variables for authentication.
```typescript
import { GitStorage } from 'pierre-storage';
import env from './env';
async function createCommit() {
const storage = new GitStorage({
name: 'your-name',
key: env.privateKey,
});
// Create a repository
const repo = await storage.createRepo();
console.log(`Created repository: ${repo.id}`);
// Get the Git remote URL
const url = await repo.getRemoteUrl();
console.log(`Git URL: ${url}`);
// Create your first commit
const result = await storage
.createCommit({
target_branch: 'main',
commit_message: 'Initial commit',
author: {
name: 'Your Name',
email: 'you@example.com',
},
})
.addFileFromString('README.md', '# My Project\n\nWelcome!')
.send();
console.log(`Commit SHA: ${result.commitSha}`);
}
```
--------------------------------
### Initialize GitStorage Client
Source: https://code.storage/docs/reference/sdk/index
Examples for initializing the GitStorage client in TypeScript, Python, and Go. This involves providing your organization identifier and private key.
```typescript
import { GitStorage } from "@pierre/storage";
const storage = new GitStorage({
name: "your-org", // Your organization identifier
key: env.privateKey,
});
```
```python
from pierre_storage import GitStorage
storage = GitStorage({
"name": "your-org", # Your organization identifier
"key": "your-private-key", # Your API key in PEM format
})
```
```go
// Initialize the client
client, err := storage.NewClient(storage.Options{
Name: "your-org",
Key: "your-private-key",
})
```
--------------------------------
### Read Repository Data (Go)
Source: https://code.storage/docs/getting-started/quickstart
Retrieves repository data by ID, lists files and commits, and reads the content of a specific file from the GitStorage service.
```go
import (
"context"
"fmt"
"io"
"storage"
)
func readData() {
repo, err := client.FindOne(context.Background(), storage.FindOneOptions{ID: "repo-id"})
if repo == nil {
return
}
// List files
files, err := repo.ListFiles(context.Background(), storage.ListFilesOptions{})
fmt.Println("Files:", files.Paths)
// List commits
commits, err := repo.ListCommits(context.Background(), storage.ListCommitsOptions{Limit: 10})
for _, commit := range commits.Commits {
fmt.Printf("%s - %s\n", commit.SHA[:7], commit.Message)
}
// Get file content
resp, err := repo.FileStream(context.Background(), storage.GetFileOptions{Path: "README.md"})
defer resp.Body.Close()
body, err := io.ReadAll(resp.Body)
fmt.Println(string(body))
}
readData()
```
--------------------------------
### List Commits Request Example (Bash)
Source: https://code.storage/docs/reference/http-api/list-commits
Example of how to make a GET request to the /api/v1/repos/commits endpoint to retrieve commit history. It includes parameters for branch, cursor, and limit, along with the necessary Authorization header.
```bash
GET /api/v1/repos/commits?branch=main&cursor=CURSOR&limit=20
Authorization: Bearer YOUR_JWT_TOKEN
```
--------------------------------
### Read Repository Data (TypeScript)
Source: https://code.storage/docs/getting-started/quickstart
Connects to the GitStorage service, retrieves repository information, lists files and commits, and reads the content of a specific file.
```typescript
import { GitStorage } from 'pierre-storage';
import env from './env';
async function readData() {
const store = new GitStorage({ name: 'your-name', key: env.privateKey });
const repo = await store.findOne({ id: 'repo-id' });
if (!repo) return;
// List files
const files = await repo.listFiles();
console.log('Files:', files.paths);
// List commits
const commits = await repo.listCommits({ limit: 10 });
commits.commits.forEach((commit) => {
console.log(`${commit.sha.slice(0, 7)} - ${commit.message}`);
});
// Get file content
const response = await repo.getFileStream({ path: 'README.md' });
const content = await response.text();
console.log(content);
}
```
--------------------------------
### Read Repository Data (Python)
Source: https://code.storage/docs/getting-started/quickstart
Connects to the GitStorage service, retrieves repository information, lists files and commits, and reads the content of a specific file using asyncio.
```python
import asyncio
from pierre_storage import GitStorage
async def read_data():
storage = GitStorage({"name": "your-name", "key": "your-key"})
repo = await storage.find_one({"id": "repo-id"})
# List files
files = await repo.list_files()
print("Files:", files["paths"])
# List commits
commits = await repo.list_commits({"limit": 10})
for commit in commits["commits"]:
print(f"{commit['sha'][:7]} - {commit['message']}")
# Get file content
response = await repo.get_file_stream({"path": "README.md"})
content = await response.aread()
print(content.decode())
asyncio.run(read_data())
```
--------------------------------
### Make First Commit (TypeScript)
Source: https://code.storage/docs/getting-started/quickstart
Demonstrates how to create an initial commit in a newly created repository using the Code Storage SDK for TypeScript. This includes setting the target branch, commit message, and author details.
```typescript
import { GitStorage } from '@pierre/storage';
async function main() {
const store = new GitStorage({
name: 'your-name',
key: env.privateKey,
});
const repo = await store.createRepo();
console.log(`Created repository: ${repo.id}`);
const url = await repo.getRemoteURL();
console.log(`Git URL: ${url}`);
const result = await repo
.createCommit({
targetBranch: 'main',
commitMessage: 'Initial commit',
author: { name: 'Your Name', email: 'you@example.com' },
})
}
```
--------------------------------
### createCommit() - Go Example
Source: https://code.storage/docs/reference/sdk/create-commit
Build and push a commit to a branch using the fluent commit builder in Go.
```APIDOC
## POST /websites/code_storage/commits
### Description
Build and push a commit to a branch using the fluent commit builder.
### Method
POST
### Endpoint
/websites/code_storage/commits
### Parameters
#### Query Parameters
- **TargetBranch** (string) - Required - Branch name that will receive the commit (for example `main`).
- **CommitMessage** (string) - Required - The commit message.
- **ExpectedHeadSha** (string) - Optional - Commit SHA that must match the remote tip; omit to fast-forward unconditionally.
- **Author** (storage.CommitSignature) - Required - Provide `Name` and `Email` for the commit author.
- **Name** (string) - Required - Author's name.
- **Email** (string) - Required - Author's email.
- **BaseBranch** (string) - Optional - Mirrors the `base_branch` metadata field. Point to an existing branch whose tip should seed `targetBranch` if it does not exist.
- **Ephemeral** (bool) - Optional - Store the branch under the `refs/namespaces/ephemeral/...` namespace.
- **EphemeralBase** (string) - Optional - Use alongside `BaseBranch` when the seed branch also lives in the ephemeral namespace.
- **Committer** (storage.CommitSignature) - Optional - Provide `Name` and `Email`. If omitted, the author identity is reused.
- **Name** (string) - Required - Committer's name.
- **Email** (string) - Required - Committer's email.
- **Signal** (context.Context) - Optional - Abort an in-flight upload with `AbortController`.
- **TargetRef** (string) - Optional - Deprecated. Fully qualified ref (for example `refs/heads/main`). Prefer `TargetBranch`.
#### Request Body
This endpoint uses a builder pattern. Files are added using methods like `AddFileFromString`, `AddFile`, and `DeletePath` before calling `Send()`.
### Request Example
```go
// Build a commit and add files
builder, err := repo.CreateCommit(storage.CommitOptions{
TargetBranch: "main",
CommitMessage: "Update dashboard docs",
Author: storage.CommitSignature{Name: "Docs Bot", Email: "docs@example.com"},
})
// Add and delete files, then send the commit
result, err := builder.
AddFileFromString("docs/changelog.md", "# v2.1.0\n- refresh docs\n", nil).
AddFile("public/logo.svg", bytes.NewReader([]byte("")), nil).
DeletePath("docs/legacy.txt").
Send(context.Background())
// Inspect the result
fmt.Println(result.CommitSHA)
fmt.Println(result.RefUpdate.NewSHA)
fmt.Println(result.RefUpdate.OldSHA)
```
### Response
#### Success Response (200)
- **CommitSHA** (string) - The SHA of the newly created commit.
- **RefUpdate** (storage.RefUpdate) - Information about the ref update.
- **NewSHA** (string) - The new SHA of the updated ref.
- **OldSHA** (string) - The old SHA of the updated ref.
#### Response Example
```json
{
"CommitSHA": "a1b2c3d4e5f678901234567890abcdef12345678",
"RefUpdate": {
"NewSHA": "a1b2c3d4e5f678901234567890abcdef12345678",
"OldSHA": "0987654321fedcba0987654321fedcba09876543"
}
}
```
#### Error Response
- **RefUpdateError** - Thrown if the backend rejects the update (e.g., branch moved past `ExpectedHeadSha`). Contains status, reason, and ref details.
```
--------------------------------
### Access Repository Properties in Go
Source: https://code.storage/docs/reference/sdk/index
Provides an example of how to retrieve and access the 'ID' and 'DefaultBranch' properties of a repository object in Go using the storage SDK.
```Go
// Read repository properties
repo, err := client.FindOne(context.Background(), storage.FindOneOptions{ID: "my-repo"})
if repo != nil {
// Access repo metadata
fmt.Println(repo.ID)
fmt.Println(repo.DefaultBranch)
}
```
--------------------------------
### createCommit() - Python Example
Source: https://code.storage/docs/reference/sdk/create-commit
Build and push a commit to a branch using the fluent commit builder in Python.
```APIDOC
## POST /websites/code_storage/commits
### Description
Build and push a commit to a branch using the fluent commit builder.
### Method
POST
### Endpoint
/websites/code_storage/commits
### Parameters
#### Query Parameters
- **target_branch** (string) - Required - Branch name that will receive the commit (for example `main`).
- **commit_message** (string) - Required - The commit message.
- **expected_head_sha** (string) - Optional - Commit SHA that must match the remote tip; omit to fast-forward unconditionally.
- **author** (object) - Required - Provide `name` and `email` for the commit author.
- **name** (string) - Required - Author's name.
- **email** (string) - Required - Author's email.
- **base_branch** (string) - Optional - Mirrors the `base_branch` metadata field. Point to an existing branch whose tip should seed `target_branch` if it does not exist.
- **ephemeral** (boolean) - Optional - Store the branch under the `refs/namespaces/ephemeral/...` namespace.
- **ephemeral_base** (string) - Optional - Use alongside `base_branch` when the seed branch also lives in the ephemeral namespace.
- **committer** (object) - Optional - Provide `name` and `email`. If omitted, the author identity is reused.
- **name** (string) - Required - Committer's name.
- **email** (string) - Required - Committer's email.
- **signal** (AbortSignal) - Optional - Abort an in-flight upload with `AbortController`.
- **target_ref** (string) - Optional - Deprecated. Fully qualified ref (for example `refs/heads/main`). Prefer `target_branch`.
#### Request Body
This endpoint uses a builder pattern. Files are added using methods like `add_file_from_string`, `add_file`, and `delete_path` before calling `send()`.
### Request Example
```python
result = await (
repo.create_commit(
target_branch="main",
commit_message="Update dashboard docs",
author={"name": "Docs Bot", "email": "docs@example.com"},
)
.add_file_from_string("docs/changelog.md", "# v2.1.0\n- refresh docs\n")
.add_file("public/logo.svg", b"")
.delete_path("docs/legacy.txt")
.send()
)
print(result["commit_sha"])
print(result["ref_update"]["new_sha"])
print(result["ref_update"]["old_sha"])
```
### Response
#### Success Response (200)
- **commit_sha** (string) - The SHA of the newly created commit.
- **ref_update** (object) - Information about the ref update.
- **new_sha** (string) - The new SHA of the updated ref.
- **old_sha** (string) - The old SHA of the updated ref.
#### Response Example
```json
{
"commit_sha": "a1b2c3d4e5f678901234567890abcdef12345678",
"ref_update": {
"new_sha": "a1b2c3d4e5f678901234567890abcdef12345678",
"old_sha": "0987654321fedcba0987654321fedcba09876543"
}
}
```
#### Error Response
- **RefUpdateError** - Thrown if the backend rejects the update (e.g., branch moved past `expected_head_sha`). Contains status, reason, and ref details.
```
--------------------------------
### List Repositories Request (Bash)
Source: https://code.storage/docs/reference/http-api/list-repos
This snippet demonstrates how to make a GET request to the /api/v1/repos endpoint using bash. It includes the necessary Authorization header with a JWT token and optional query parameters for pagination (cursor and limit).
```bash
GET /api/v1/repos?cursor=CURSOR&limit=20
Authorization: Bearer YOUR_JWT_TOKEN
```
--------------------------------
### Fetch Repository Metadata (Bash)
Source: https://code.storage/docs/reference/http-api/get-repo
Demonstrates how to fetch repository metadata using a GET request to the /api/v1/repo endpoint. Requires a JWT with a 'repo' claim in the Authorization header. Returns repository details upon success.
```bash
GET /api/v1/repo
Authorization: Bearer YOUR_JWT_TOKEN
```
--------------------------------
### Get Commit Diff API Request Example (Bash)
Source: https://code.storage/docs/reference/http-api/get-commit-diff
Example of how to make a GET request to the commit diff API. It includes parameters for commit SHA, base commit SHA, and specific file paths to filter the diff. An Authorization header with a JWT token is required.
```bash
GET /api/v1/repos/diff?sha=COMMIT_SHA&baseSha=BASE_COMMIT_SHA&path=src/main.go&path=README.md
Authorization: Bearer YOUR_JWT_TOKEN
```
--------------------------------
### Initialize Code Storage Client (TypeScript, Python, Go)
Source: https://code.storage/docs/getting-started/quickstart
Initializes the GitStorage client with organization name and private key. Requires environment variables or direct key provision. Ensure your private key is securely handled.
```typescript
import { GitStorage } from '@pierre/storage';
const store = new GitStorage({
name: 'your-org', // Your organization identifier
key: env.privateKey, // Your API key
});
```
```python
from pierre_storage import GitStorage
storage = GitStorage({
"name": "your-name", # e.g., 'v0'
"key": "your-key", # Your API key in PEM format
})
```
```go
// Initialize the client
client, err := storage.NewClient(storage.Options{
Name: "your-org",
Key: os.Getenv("PIERRE_PRIVATE_KEY"),
})
```
--------------------------------
### GET /api/v1/repos/branches/diff
Source: https://code.storage/docs/reference/http-api/get-branch-diff
Compares a feature branch to its base branch to review all changes before merging. Supports filtering by specific file paths.
```APIDOC
## GET /api/v1/repos/branches/diff
### Description
Compares a feature branch to its base so you can review every change before merging.
### Method
GET
### Endpoint
/api/v1/repos/branches/diff
### Parameters
#### Query Parameters
- **branch** (string) - Required - The branch name to get the diff for.
- **base** (string) - Optional - Base branch to compare against (defaults to repository's default branch).
- **ephemeral** (boolean) - Optional - When `true`, resolves the branch ref under `refs/namespaces/ephemeral/refs/heads/`.
- **ephemeral_base** (boolean) - Optional - When `true`, resolves the base ref under `refs/namespaces/ephemeral/refs/heads/`.
- **path** (string) - Optional - File path(s) to filter the diff. Can be specified multiple times to include multiple files. When provided, only returns diffs for the specified files and bypasses size/type filtering.
#### Headers
- **Authorization** (string) - Required - Bearer YOUR_JWT_TOKEN
### Request Example
```bash
GET /api/v1/repos/branches/diff?branch=BRANCH_NAME&base=BASE_BRANCH&ephemeral=true&ephemeral_base=false&path=src/main.go&path=README.md
Authorization: Bearer YOUR_JWT_TOKEN
```
### Response
#### Success Response (200)
- **branch** (string) - The name of the compared branch.
- **base** (string) - The name of the base branch.
- **stats** (object) - Statistics about the diff.
- **files** (integer) - Number of files changed.
- **additions** (integer) - Total number of additions.
- **deletions** (integer) - Total number of deletions.
- **changes** (integer) - Total number of changes.
- **files** (array) - List of changed files with diff content.
- **path** (string) - Path of the file.
- **state** (string) - Git status code (e.g., 'A', 'M', 'D').
- **old_path** (string) - Original path for renamed files.
- **bytes** (integer) - Size of the file in bytes.
- **is_eof** (boolean) - Indicates if it's the end of the file.
- **raw** (string) - Raw diff content.
- **filtered_files** (array) - List of files included in filtering (e.g., large or binary files) without diff content.
- **path** (string) - Path of the file.
- **state** (string) - Git status code.
- **old_path** (string) - Original path for renamed files.
- **bytes** (integer) - Size of the file in bytes.
- **is_eof** (boolean) - Indicates if it's the end of the file.
#### Response Example
```json
{
"branch": "feature/new-feature",
"base": "main",
"stats": {
"files": 5,
"additions": 120,
"deletions": 30,
"changes": 150
},
"files": [
{
"path": "src/feature.go",
"state": "A",
"old_path": "",
"bytes": 2048,
"is_eof": true,
"raw": "diff --git a/src/feature.go b/src/feature.go\nnew file mode 100644\nindex 0000000..abc123\n--- /dev/null\n+++ b/src/feature.go\n@@ -0,0 +1,50 @@\n+package main\n+\n+func NewFeature() {\n+ // Implementation\n+}\n"
},
{
"path": "src/main.go",
"state": "M",
"old_path": "",
"bytes": 1024,
"is_eof": true,
"raw": "diff --git a/src/main.go b/src/main.go\nindex abc123..def456 100644\n--- a/src/main.go\n+++ b/src/main.go\n@@ -10,6 +10,8 @@\n+ feature := NewFeature()\n+ feature.Run()\n"
}
],
"filtered_files": [
{
"path": "go.sum",
"state": "M",
"old_path": "",
"bytes": 50000,
"is_eof": true
}
]
}
```
### JWT Requirements
- The JWT must include the repository in the `repo` claim.
- Requires `git:read` scope.
### Error Responses
- **404 Not Found**: Branch or base branch doesn't exist.
- **401 Unauthorized**: Invalid JWT or missing `git:read` scope.
- **400 Bad Request**: Missing branch parameter or invalid `ephemeral`/`ephemeral_base` value.
```
--------------------------------
### Apply Git Diff and Create Commit (Go)
Source: https://code.storage/docs/getting-started/quickstart
Applies a given diff to a repository and creates a new commit. It requires a GitStorage client initialized with credentials and repository details. The function takes a diff string and commit information as input, and outputs the SHA of the newly created commit.
```go
func applyDiff() {
// Prepare a diff payload
diffText := `--- a/README.md
+++ b/README.md
@@
-Old line
+New line
`
repo, err := client.FindOne(context.Background(), storage.FindOneOptions{ID: "repo-id"})
if repo == nil {
return
}
// Apply the diff as a commit
result, err := repo.CreateCommitFromDiff(context.Background(), storage.CommitFromDiffOptions{
TargetBranch: "main",
CommitMessage: "Apply upstream changes",
Diff: strings.NewReader(diffText),
Author: storage.CommitSignature{Name: "Automation", Email: "bot@example.com"},
BaseBranch: "main",
})
fmt.Printf("Updated commit: %s\n", result.CommitSHA)
}
applyDiff()
```
--------------------------------
### GET /api/v1/repos/diff
Source: https://code.storage/docs/reference/http-api/get-commit-diff
Streams the full diff for a commit, allowing for detailed review of file-level changes. It supports filtering by specific file paths and comparing against a base commit.
```APIDOC
## GET /api/v1/repos/diff
### Description
Streams the full diff for a commit to help you review file-level changes. Supports filtering by specific file paths and comparing against a base commit.
### Method
GET
### Endpoint
/api/v1/repos/diff
### Parameters
#### Query Parameters
- **sha** (string) - Required - The full commit SHA to get the diff for.
- **baseSha** (string) - Optional - Base commit SHA to compare against. If not specified, compares against the commit's parent(s).
- **path** (string) - Optional - File path(s) to filter the diff. Can be specified multiple times to include multiple files. When provided, only returns diffs for the specified files and bypasses size/type filtering.
#### Headers
- **Authorization** (string) - Required - Bearer YOUR_JWT_TOKEN
### Request Example
```bash
GET /api/v1/repos/diff?sha=COMMIT_SHA&baseSha=BASE_COMMIT_SHA&path=src/main.go&path=README.md
Authorization: Bearer YOUR_JWT_TOKEN
```
### Response
#### Success Response (200)
- **sha** (string) - The commit SHA.
- **stats** (object) - Statistics about the diff (files, additions, deletions, changes).
- **files** (integer) - Number of files changed.
- **additions** (integer) - Number of lines added.
- **deletions** (integer) - Number of lines deleted.
- **changes** (integer) - Total number of changes.
- **files** (array) - Array of file diff objects.
- **path** (string) - The path of the file.
- **state** (string) - Git status code (e.g., 'M', 'A', 'D').
- **old_path** (string) - The old path for renamed files.
- **bytes** (integer) - Size of the file in bytes.
- **is_eof** (boolean) - Indicates if the file ends with a newline.
- **raw** (string) - The raw diff content for the file.
- **filtered_files** (array) - Array of files that were filtered due to size or type, without diff content.
- **path** (string) - The path of the filtered file.
- **state** (string) - Git status code.
- **old_path** (string) - The old path for renamed files.
- **bytes** (integer) - Size of the file in bytes.
- **is_eof** (boolean) - Indicates if the file ends with a newline.
#### Response Example
```json
{
"sha": "b003fc78805954584e1ee364a4ad39d7c79e819a",
"stats": {
"files": 3,
"additions": 50,
"deletions": 10,
"changes": 60
},
"files": [
{
"path": "src/main.go",
"state": "M",
"old_path": "",
"bytes": 2048,
"is_eof": true,
"raw": "diff --git a/src/main.go b/src/main.go\nindex abc123..def456 100644\n--- a/src/main.go\n+++ b/src/main.go\n@@ -10,6 +10,8 @@\n+func newFunction() {\n+ // New implementation\n+}\n"
},
{
"path": "README.md",
"state": "A",
"old_path": "",
"bytes": 512,
"is_eof": true,
"raw": "diff --git a/README.md b/README.md\nnew file mode 100644\nindex 0000000..abc123\n--- /dev/null\n+++ b/README.md\n@@ -0,0 +1,5 @@\n+# Project Title\n+\n+Description of the project\n"
}
],
"filtered_files": [
{
"path": "package-lock.json",
"state": "M",
"old_path": "",
"bytes": 50000,
"is_eof": true
}
]
}
```
### JWT Requirements
- The JWT must include the repository in the `repo` claim.
- Requires `git:read` scope.
### Error Responses
- **404 Not Found**: Commit doesn't exist.
- **401 Unauthorized**: Invalid JWT or missing `git:read` scope.
- **400 Bad Request**: Missing or invalid SHA parameter.
```
--------------------------------
### List Commits Response Example (JSON)
Source: https://code.storage/docs/reference/http-api/list-commits
Example JSON response structure for the /api/v1/repos/commits endpoint. It shows the 'commits' array containing commit details, and pagination information like 'next_cursor' and 'has_more'.
```json
{
"commits": [
{
"sha": "b003fc78805954584e1ee364a4ad39d7c79e819a",
"message": "fix: resolve scrolling issue in dashboard",
"author_name": "Jane Doe",
"author_email": "jane@example.com",
"committer_name": "Jane Doe",
"committer_email": "jane@example.com",
"date": "2024-01-15T14:32:18Z"
},
{
"sha": "a4d39d7c79e819ab003fc78805954584e1ee36",
"message": "feat: add user authentication",
"author_name": "John Smith",
"author_email": "john@example.com",
"committer_name": "John Smith",
"committer_email": "john@example.com",
"date": "2024-01-14T10:15:00Z"
}
],
"next_cursor": "20",
"has_more": true
}
```
--------------------------------
### Compare Branches API Request (Bash)
Source: https://code.storage/docs/reference/http-api/get-branch-diff
This Bash snippet demonstrates how to make a GET request to the /api/v1/repos/branches/diff endpoint. It includes parameters for specifying branches, ephemeral settings, and file paths, along with the necessary Authorization header.
```bash
GET /api/v1/repos/branches/diff?branch=BRANCH_NAME&base=BASE_BRANCH&ephemeral=true&ephemeral_base=false&path=src/main.go&path=README.md
Authorization: Bearer YOUR_JWT_TOKEN
```
--------------------------------
### Apply Git Diff and Create Commit (Python)
Source: https://code.storage/docs/getting-started/quickstart
Applies a given diff to a repository and creates a new commit. It requires a GitStorage client initialized with credentials and repository details. The function takes a diff string and commit information as input, and outputs the SHA of the newly created commit.
```python
async def apply_diff():
storage = GitStorage({"name": "your-name", "key": "your-key"})
repo = await storage.find_one({"id": "repo-id"})
diff_text = """
--- a/README.md
+++ b/README.md
@@
-Old line
+New line
"""
result = await repo.create_commit_from_diff(
target_branch="main",
commit_message="Apply upstream changes",
diff=diff_text,
author={"name": "Automation", "email": "bot@example.com"},
base_branch="main", # optional, matches create_commit options
)
print(f"Updated commit: {result['commit_sha']}")
asyncio.run(apply_diff())
```
--------------------------------
### createCommit() - TypeScript Example
Source: https://code.storage/docs/reference/sdk/create-commit
Build and push a commit to a branch using the fluent commit builder in TypeScript.
```APIDOC
## POST /websites/code_storage/commits
### Description
Build and push a commit to a branch using the fluent commit builder.
### Method
POST
### Endpoint
/websites/code_storage/commits
### Parameters
#### Query Parameters
- **targetBranch** (string) - Required - Branch name that will receive the commit (for example `main`).
- **commitMessage** (string) - Required - The commit message.
- **expectedHeadSha** (string) - Optional - Commit SHA that must match the remote tip; omit to fast-forward unconditionally.
- **author** (object) - Required - Provide `name` and `email` for the commit author.
- **name** (string) - Required - Author's name.
- **email** (string) - Required - Author's email.
- **baseBranch** (string) - Optional - Mirrors the `base_branch` metadata field. Point to an existing branch whose tip should seed `targetBranch` if it does not exist.
- **ephemeral** (boolean) - Optional - Store the branch under the `refs/namespaces/ephemeral/...` namespace.
- **ephemeralBase** (string) - Optional - Use alongside `baseBranch` when the seed branch also lives in the ephemeral namespace.
- **committer** (object) - Optional - Provide `name` and `email`. If omitted, the author identity is reused.
- **name** (string) - Required - Committer's name.
- **email** (string) - Required - Committer's email.
- **signal** (AbortSignal) - Optional - Abort an in-flight upload with `AbortController`.
- **targetRef** (string) - Optional - Deprecated. Fully qualified ref (for example `refs/heads/main`). Prefer `targetBranch`.
#### Request Body
This endpoint uses a builder pattern. Files are added using methods like `addFileFromString`, `addFile`, and `deletePath` before calling `send()`.
### Request Example
```typescript
const fs = await import("node:fs/promises");
const result = await repo
.createCommit({
targetBranch: "main",
commitMessage: "Update dashboard docs",
expectedHeadSha: currentHeadSha, // optional safety check
author: { name: "Docs Bot", email: "docs@example.com" },
})
.addFileFromString("docs/changelog.md", "# v2.1.0\n- refresh docs\n")
.addFile("public/logo.svg", await fs.readFile("assets/logo.svg"))
.deletePath("docs/legacy.txt")
.send();
console.log(result.commitSha);
console.log(result.refUpdate.newSha);
console.log(result.refUpdate.oldSha);
```
### Response
#### Success Response (200)
- **commitSha** (string) - The SHA of the newly created commit.
- **refUpdate** (object) - Information about the ref update.
- **newSha** (string) - The new SHA of the updated ref.
- **oldSha** (string) - The old SHA of the updated ref.
#### Response Example
```json
{
"commitSha": "a1b2c3d4e5f678901234567890abcdef12345678",
"refUpdate": {
"newSha": "a1b2c3d4e5f678901234567890abcdef12345678",
"oldSha": "0987654321fedcba0987654321fedcba09876543"
}
}
```
#### Error Response
- **RefUpdateError** - Thrown if the backend rejects the update (e.g., branch moved past `expectedHeadSha`). Contains status, reason, and ref details.
```
--------------------------------
### GET /api/v1/repo
Source: https://code.storage/docs/reference/http-api/get-repo
Fetches repository metadata for the repository identified by the JWT 'repo' claim. Requires a valid JWT with the repository claim.
```APIDOC
## GET /api/v1/repo
### Description
Fetch repository metadata for the repository identified by the JWT `repo` claim.
### Method
GET
### Endpoint
/api/v1/repo
### Parameters
#### Query Parameters
None
#### Headers
- **Authorization** (string) - Required - Bearer YOUR_JWT_TOKEN
### Request Example
```bash
GET /api/v1/repo
Authorization: Bearer YOUR_JWT_TOKEN
```
### Response
#### Success Response (200)
- **repo_id** (string) - The unique identifier for the repository.
- **url** (string) - The URL path for the repository within the project.
- **default_branch** (string) - The default branch of the repository.
- **created_at** (string) - The timestamp when the repository was created.
- **base_repo** (object) - Information about the base repository.
- **provider** (string) - The provider of the base repository (e.g., 'github').
- **owner** (string) - The owner of the base repository.
- **name** (string) - The name of the base repository.
#### Response Example
```json
{
"repo_id": "V1StGXR8_Z5jdHi6B-myT",
"url": "team/project-alpha",
"default_branch": "main",
"created_at": "2024-01-15T10:30:00Z",
"base_repo": {
"provider": "github",
"owner": "octocat",
"name": "Hello-World"
}
}
```
#### Error Responses
- **401 Unauthorized** (string) - Invalid JWT or missing authorization header.
- **404 Not Found** (string) - Repository not found.
```