Skip to content

Reading and Writing Files

The filesystem API (Level 3) is the primary interface for agents and apps. Read, write, and delete files with simple method calls.

from githosted import Client
client = Client()
repo = client.repo("my-project")
# List files
files = repo.ls("src/")
# Read a file
file = repo.read("src/main.py")
print(file.content) # string content
print(file.head_sha) # branch tip at read time
# Write a file
repo.write("src/main.py", "x = 1", "Update main.py")

List files and directories at a path.

entries = repo.ls("src/")
# [FileEntry(name='main.py', type='file'), FileEntry(name='lib', type='directory')]
# List root
root = repo.ls()
# List at a specific branch
entries = repo.ls("src/", ref="feature/new-api")

Read a file’s content and metadata.

file = repo.read("src/main.py")
file.content # str (UTF-8 decoded)
file.raw_content # bytes (raw)
file.head_sha # branch tip SHA at read time
file.blob_sha # content-addressable blob hash
# Read from a specific branch
file = repo.read("src/main.py", ref="develop")

head_sha is the key to optimistic concurrency — pass it as expected_head on a subsequent write to detect conflicts.

repo.write(path, content, message, *, ref, expected_head)

Section titled “repo.write(path, content, message, *, ref, expected_head)”

Write a file, creating a commit on the target branch.

# Simple write
repo.write("README.md", "# My Project", "Update readme")
# Write to a specific branch
repo.write("src/main.py", code, "Fix bug", ref="feature/fix")
# Write with optimistic concurrency
file = repo.read("src/main.py")
repo.write(
"src/main.py",
modified_code,
"Fix bug",
expected_head=file.head_sha,
)

Content can be a str or bytes (for binary files).

repo.delete(path, message, *, ref, expected_head)

Section titled “repo.delete(path, message, *, ref, expected_head)”

Delete a file, creating a commit on the target branch.

repo.delete("src/old_module.py", "Remove deprecated module")

Use expected_head to detect when another writer has modified the branch between your read and write:

import json
from githosted import Client, StaleHeadError
client = Client()
repo = client.repo("my-project")
file = repo.read("config.json")
config = json.loads(file.content)
config["version"] = "2.0"
try:
repo.write(
"config.json",
json.dumps(config, indent=2),
"Bump version",
expected_head=file.head_sha,
)
except StaleHeadError as err:
print(f"Branch moved to {err.actual_head}, re-read and retry")

See Error Handling for more on StaleHeadError.