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

# Quick Start

> Install the SDK, initialize the client, create a repository, and make your first commit.

Use the Code Storage SDK to create your first repository. Choose the TypeScript, Python, or Go
example in each step. Later steps reuse the `storage` and `repo` values from the earlier steps.

First create an API key and store it. See
[Authentication & Security](/docs/getting-started/authentication). You need your organization identifier
and the `PIERRE_PRIVATE_KEY` value from that step.

## 1. Install the SDK

<CodeGroup>
  ```bash TypeScript theme={null} theme={"theme":{"light":"github-light","dark":"min-dark"}}
  pnpm add @pierre/storage
  ```

  ```bash Python theme={null} theme={"theme":{"light":"github-light","dark":"min-dark"}}
  pip install pierre-storage
  ```

  ```bash Go theme={null} theme={"theme":{"light":"github-light","dark":"min-dark"}}
  go get github.com/pierrecomputer/sdk/packages/code-storage-go@latest
  ```
</CodeGroup>

## 2. Initialize the client

Replace `your-org` with your organization identifier. The client reads the private key from
`PIERRE_PRIVATE_KEY`.

<CodeGroup>
  ```typescript TypeScript theme={null} theme={"theme":{"light":"github-light","dark":"min-dark"}}
  import { GitStorage } from '@pierre/storage';

  const storage = new GitStorage({
    name: 'your-org',
    key: process.env.PIERRE_PRIVATE_KEY!,
  });
  ```

  ```python Python theme={null} theme={"theme":{"light":"github-light","dark":"min-dark"}}
  import os

  from pierre_storage import GitStorage

  storage = GitStorage({
      "name": "your-org",
      "key": os.environ["PIERRE_PRIVATE_KEY"],
  })
  ```

  ```go Go theme={null} theme={"theme":{"light":"github-light","dark":"min-dark"}}
  client, err := storage.NewClient(storage.Options{
  	Name: "your-org",
  	Key:  os.Getenv("PIERRE_PRIVATE_KEY"),
  })
  if err != nil {
  	return fmt.Errorf("create client: %w", err)
  }
  ```
</CodeGroup>

## 3. Create a repository

Each repository belongs to your organization and has a unique ID. Code Storage can generate a UUID,
or you can supply an ID such as `team/project-alpha`. A new repository uses `main` as its default
branch.

<CodeGroup>
  ```typescript TypeScript theme={null} theme={"theme":{"light":"github-light","dark":"min-dark"}}
  // Create a repository with a server-generated ID.
  const generatedRepo = await storage.createRepo();
  console.log(generatedRepo.id); // e.g. '123e4567-e89b-12d3-a456-426614174000'

  // Or create a repository with your own ID.
  const repo = await storage.createRepo({ id: 'quickstart' });

  // Or create a repository that syncs with GitHub.
  const syncedRepo = await storage.createRepo({
    id: 'hello-world',
    baseRepo: { owner: 'octocat', name: 'Hello-World', defaultBranch: 'main' },
  });

  // Get an authenticated Git remote URL.
  const url = await repo.getRemoteURL();
  console.log(`git remote add origin ${url}`);
  // Output: git remote add origin https://t:JWT@[org].code.storage/quickstart.git
  ```

  ```python Python theme={null} theme={"theme":{"light":"github-light","dark":"min-dark"}}
  # Create a repository with a server-generated ID.
  generated_repo = await storage.create_repo()
  print(generated_repo.id)  # e.g. '123e4567-e89b-12d3-a456-426614174000'

  # Or create a repository with your own ID.
  repo = await storage.create_repo(id="quickstart")

  # Or create a repository that syncs with GitHub.
  synced_repo = await storage.create_repo(
      id="hello-world",
      base_repo={"owner": "octocat", "name": "Hello-World", "default_branch": "main"},
  )

  # Get an authenticated Git remote URL.
  url = await repo.get_remote_url()
  print(f"git remote add origin {url}")
  ```

  ```go Go theme={null} theme={"theme":{"light":"github-light","dark":"min-dark"}}
  ctx := context.Background()

  // Create a repository with a server-generated ID.
  generatedRepo, err := client.CreateRepo(ctx, storage.CreateRepoOptions{})
  if err != nil {
  	return fmt.Errorf("create repository: %w", err)
  }
  fmt.Println(generatedRepo.ID) // e.g. "123e4567-e89b-12d3-a456-426614174000"

  // Or create a repository with your own ID.
  repo, err := client.CreateRepo(ctx, storage.CreateRepoOptions{ID: "quickstart"})
  if err != nil {
  	return fmt.Errorf("create repository: %w", err)
  }

  // Or create a repository that syncs with GitHub.
  syncedRepo, err := client.CreateRepo(ctx, storage.CreateRepoOptions{
  	ID:       "hello-world",
  	BaseRepo: storage.GitHubBaseRepo{Owner: "octocat", Name: "Hello-World", DefaultBranch: "main"},
  })
  if err != nil {
  	return fmt.Errorf("create synced repository: %w", err)
  }

  // Get an authenticated Git remote URL.
  url, err := repo.RemoteURL(ctx, storage.RemoteURLOptions{})
  if err != nil {
  	return fmt.Errorf("create remote URL: %w", err)
  }
  fmt.Printf("git remote add origin %s\n", url)
  ```
</CodeGroup>

To sync with GitLab, Bitbucket, or another HTTPS host, pass a base repository. See
[GitHub Sync](/docs/guides/github-sync) and [Generic Sync](/docs/guides/generic-sync).

## 4. Create a commit

Write files and commit them to `repo` without a local clone.

<CodeGroup>
  ```typescript TypeScript theme={null} theme={"theme":{"light":"github-light","dark":"min-dark"}}
  const result = await repo
    .createCommit({
      targetBranch: 'main',
      commitMessage: 'Initial commit',
      author: { name: 'Your Name', email: 'you@example.com' },
    })
    .addFileFromString('README.md', '# Quickstart\n')
    .send();

  console.log(result.commitSha);
  ```

  ```python Python theme={null} theme={"theme":{"light":"github-light","dark":"min-dark"}}
  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", "# Quickstart\n")
      .send()
  )

  print(result["commit_sha"])
  ```

  ```go Go theme={null} theme={"theme":{"light":"github-light","dark":"min-dark"}}
  builder, err := repo.CreateCommit(storage.CommitOptions{
  	TargetBranch:  "main",
  	CommitMessage: "Initial commit",
  	Author:        storage.CommitSignature{Name: "Your Name", Email: "you@example.com"},
  })
  if err != nil {
  	return fmt.Errorf("create commit builder: %w", err)
  }

  result, err := builder.
  	AddFileFromString("README.md", "# Quickstart\n", nil).
  	Send(ctx)
  if err != nil {
  	return fmt.Errorf("create commit: %w", err)
  }

  fmt.Println(result.CommitSHA)
  ```
</CodeGroup>

## 5. Read repository data

Read files, list commits, and stream file content from `repo`.

<CodeGroup>
  ```typescript TypeScript theme={null} theme={"theme":{"light":"github-light","dark":"min-dark"}}
  // List files.
  const files = await repo.listFiles();
  console.log(files.paths);

  // List recent commits.
  const commits = await repo.listCommits({ limit: 10 });
  for (const commit of commits.commits) {
    console.log(`${commit.sha.slice(0, 7)} ${commit.message}`);
  }

  // Read file content.
  const response = await repo.getFileStream({ path: 'README.md' });
  console.log(await response.text());
  ```

  ```python Python theme={null} theme={"theme":{"light":"github-light","dark":"min-dark"}}
  # List files.
  files = await repo.list_files()
  print(files["paths"])

  # List recent commits.
  commits = await repo.list_commits({"limit": 10})
  for commit in commits["commits"]:
      print(f"{commit['sha'][:7]} {commit['message']}")

  # Read file content.
  response = await repo.get_file_stream({"path": "README.md"})
  content = await response.aread()
  print(content.decode())
  ```

  ```go Go theme={null} theme={"theme":{"light":"github-light","dark":"min-dark"}}
  // List files.
  files, err := repo.ListFiles(ctx, storage.ListFilesOptions{})
  if err != nil {
  	return fmt.Errorf("list files: %w", err)
  }
  fmt.Println(files.Paths)

  // List recent commits.
  commits, err := repo.ListCommits(ctx, storage.ListCommitsOptions{Limit: 10})
  if err != nil {
  	return fmt.Errorf("list commits: %w", err)
  }
  for _, commit := range commits.Commits {
  	fmt.Printf("%s %s\n", commit.SHA[:7], commit.Message)
  }

  // Read file content.
  resp, err := repo.FileStream(ctx, storage.GetFileOptions{Path: "README.md"})
  if err != nil {
  	return fmt.Errorf("get file stream: %w", err)
  }
  defer resp.Body.Close()
  body, err := io.ReadAll(resp.Body)
  if err != nil {
  	return fmt.Errorf("read file content: %w", err)
  }
  fmt.Println(string(body))
  ```
</CodeGroup>

## 6. Apply a diff

Commit a unified diff to `repo` without a local clone.

<CodeGroup>
  ```typescript TypeScript theme={null} theme={"theme":{"light":"github-light","dark":"min-dark"}}
  const diff = `--- a/README.md
  +++ b/README.md
  @@
  -# Quickstart
  +# Quickstart project
  `;

  const patched = await repo.createCommitFromDiff({
    targetBranch: 'main',
    commitMessage: 'Apply upstream changes',
    diff,
    author: { name: 'Automation', email: 'bot@example.com' },
  });

  console.log(patched.commitSha);
  ```

  ```python Python theme={null} theme={"theme":{"light":"github-light","dark":"min-dark"}}
  diff = """\
  --- a/README.md
  +++ b/README.md
  @@
  -# Quickstart
  +# Quickstart project
  """

  patched = await repo.create_commit_from_diff(
      target_branch="main",
      commit_message="Apply upstream changes",
      diff=diff,
      author={"name": "Automation", "email": "bot@example.com"},
  )

  print(patched["commit_sha"])
  ```

  ```go Go theme={null} theme={"theme":{"light":"github-light","dark":"min-dark"}}
  diff := `--- a/README.md
  +++ b/README.md
  @@
  -# Quickstart
  +# Quickstart project
  `

  patched, err := repo.CreateCommitFromDiff(ctx, storage.CommitFromDiffOptions{
  	TargetBranch:  "main",
  	CommitMessage: "Apply upstream changes",
  	Diff:          strings.NewReader(diff),
  	Author:        storage.CommitSignature{Name: "Automation", Email: "bot@example.com"},
  })
  if err != nil {
  	return fmt.Errorf("apply diff: %w", err)
  }

  fmt.Println(patched.CommitSHA)
  ```
</CodeGroup>

## Next steps

* [Git Operations](/docs/guides/git-operations): Use clone, fetch, push, and pull.
* [Ref Policies](/docs/guides/ref-policies): Limit the refs that a token can update.
* [SDK Reference](/docs/reference/sdk): Find methods for repositories, branches, commits, files, tags,
  and notes.
* [HTTP API](/docs/reference/api/overview): Use Code Storage without an SDK.
