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.
Quickstart
Section titled “Quickstart”from githosted import Client
client = Client()repo = client.repo("my-project")
# List filesfiles = repo.ls("src/")
# Read a filefile = repo.read("src/main.py")print(file.content) # string contentprint(file.head_sha) # branch tip at read time
# Write a filerepo.write("src/main.py", "x = 1", "Update main.py")API Reference
Section titled “API Reference”repo.ls(path, *, ref)
Section titled “repo.ls(path, *, ref)”List files and directories at a path.
entries = repo.ls("src/")# [FileEntry(name='main.py', type='file'), FileEntry(name='lib', type='directory')]
# List rootroot = repo.ls()
# List at a specific branchentries = repo.ls("src/", ref="feature/new-api")repo.read(path, *, ref)
Section titled “repo.read(path, *, ref)”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 timefile.blob_sha # content-addressable blob hash
# Read from a specific branchfile = 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 writerepo.write("README.md", "# My Project", "Update readme")
# Write to a specific branchrepo.write("src/main.py", code, "Fix bug", ref="feature/fix")
# Write with optimistic concurrencyfile = 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")Optimistic Concurrency
Section titled “Optimistic Concurrency”Use expected_head to detect when another writer has modified the branch between your read and write:
import jsonfrom 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.