### View Commit History with SwiftGitX Source: https://context7.com/ibrahimcetin/swiftgitx/llms.txt Retrieve commit history starting from HEAD using `repository.log()`. This returns a lazy `CommitSequence` that can be sorted by time. You can also start the log from a specific branch or commit. The sequence can be collected into an array for random access. ```swift // Walk commits from HEAD for commit in try repository.log() { print("\(commit.id) — \(commit.summary)") } // With time-sorted order let sorted = try repository.log(sorting: .time) // Start from a specific branch let branch = try repository.branch.get(named: "feature/auth") for commit in try repository.log(from: branch) { print("\(commit.author.name): \(commit.summary)") } // Start from a specific commit let pivot = try repository.log().first! let history = repository.log(from: pivot) // Collect into an array for random access let commits = Array(try repository.log()).prefix(10) let latest = commits.first! print("Latest: \(latest.summary), by \(latest.author.name) on \(latest.date)") ``` -------------------------------- ### Get Working Tree and Index Status Source: https://context7.com/ibrahimcetin/swiftgitx/llms.txt Retrieve the status of the entire repository, a specific file by path, or a file by URL. Options can be provided to include untracked files. ```swift let entries = try repository.status() for entry in entries { print("\(entry.status) — \(entry.headToIndex?.newFile?.path ?? entry.indexToWorkdir?.newFile?.path ?? "?")") } ``` ```swift let fileStatuses = try repository.status(path: "README.md") ``` ```swift let fileURL = URL(fileURLWithPath: "/tmp/my-repo/README.md") let statuses = try repository.status(file: fileURL) ``` ```swift let untrackedOnly = try repository.status(options: .includeUntracked) ``` -------------------------------- ### Clone Repository and Get Latest Commit in Swift Source: https://github.com/ibrahimcetin/swiftgitx/blob/main/README.md Demonstrates cloning a Git repository and accessing its latest commit using Swift concurrency. Ensure the repository URL and local path are valid. ```swift let url = URL(string: "https://github.com/ibrahimcetin/SwiftGitX.git")! let repository = try await Repository.clone(from: url, to: URL(string: "/path/to/clone")!) let latestCommit = try repository.HEAD.target as? Commit let main = try repository.branch.get(named: "main") let feature = try repository.branch.create(named: "feature", from: main) try repository.switch(to: feature) ``` -------------------------------- ### Branch Management with SwiftGitX Source: https://context7.com/ibrahimcetin/swiftgitx/llms.txt Manage Git branches using `repository.branch`. This includes getting the current branch, looking up branches by name (local or remote), creating new branches from existing ones or specific commits, renaming branches, setting upstream tracking, and deleting branches. Iteration over all branches is also supported. ```swift // Get the current branch let currentBranch = try repository.branch.current print("Current: \(currentBranch.name)") // "main" // Look up a branch by name let main = try repository.branch.get(named: "main") let originMain = try repository.branch.get(named: "origin/main", type: .remote) // Subscript (returns nil instead of throwing) let featureBranch = repository.branch["feature/login"] // List all branches let allBranches = try repository.branch.list() let localOnly = try repository.branch.list(.local) let remoteOnly = try repository.branch.list(.remote) // Create branch from another branch let feature = try repository.branch.create(named: "feature/new-ui", from: main) // Create branch from a specific commit let commit = try repository.log().first(where: { $0.summary.contains("stable") })! let hotfix = try repository.branch.create(named: "hotfix/crash", target: commit) // Rename a branch let renamed = try repository.branch.rename(feature, to: "feature/redesign") // Set upstream tracking try repository.branch.setUpstream(from: renamed, to: originMain) // Delete a branch try repository.branch.delete(hotfix) // Iterate over all branches for branch in repository.branch { print("\(branch.type == .local ? "local" : "remote"): \(branch.name)") } ``` -------------------------------- ### repository.branch — Branch Management Source: https://context7.com/ibrahimcetin/swiftgitx/llms.txt Manage Git branches using the `BranchCollection` provided by `repository.branch`. Supports getting, listing, creating, deleting, renaming, and setting upstream tracking for branches. ```APIDOC ## repository.branch — Branch Management `repository.branch` is a `BranchCollection` with full CRUD for branches: get, list, create, delete, rename, and set upstream tracking. ```swift // Get the current branch let currentBranch = try repository.branch.current print("Current: \(currentBranch.name)") // "main" // Look up a branch by name let main = try repository.branch.get(named: "main") let originMain = try repository.branch.get(named: "origin/main", type: .remote) // Subscript (returns nil instead of throwing) let featureBranch = repository.branch["feature/login"] // List all branches let allBranches = try repository.branch.list() let localOnly = try repository.branch.list(.local) let remoteOnly = try repository.branch.list(.remote) // Create branch from another branch let feature = try repository.branch.create(named: "feature/new-ui", from: main) // Create branch from a specific commit let commit = try repository.log().first(where: { $0.summary.contains("stable") })! let hotfix = try repository.branch.create(named: "hotfix/crash", target: commit) // Rename a branch let renamed = try repository.branch.rename(feature, to: "feature/redesign") // Set upstream tracking try repository.branch.setUpstream(from: renamed, to: originMain) // Delete a branch try repository.branch.delete(hotfix) // Iterate over all branches for branch in repository.branch { print("\(branch.type == .local ? "local" : "remote"): \(branch.name)") } ``` ``` -------------------------------- ### Open, Create, and Inspect a Git Repository with SwiftGitX Source: https://context7.com/ibrahimcetin/swiftgitx/llms.txt Use Repository.init, Repository.open, or Repository.create to manage repositories. Inspect properties like isEmpty, isBare, and workingDirectory. ```swift import SwiftGitX // Open existing or create new let repoURL = URL(fileURLWithPath: "/tmp/my-repo") let repository = try Repository(at: repoURL) // → creates /tmp/my-repo/.git if it doesn't exist // Open only (throws SwiftGitXError if not found) let existing = try Repository.open(at: repoURL) // Create a bare repository let bareRepo = try Repository.create(at: URL(fileURLWithPath: "/tmp/bare.git"), isBare: true) // Inspect properties print(repository.isEmpty) // true (no commits yet) print(repository.isBare) // false print(repository.isHEADDetached) // false print(try repository.workingDirectory) // file:///tmp/my-repo/ print(repository.path) // file:///tmp/my-repo/.git/ ``` -------------------------------- ### Repository Initialization and Inspection Source: https://context7.com/ibrahimcetin/swiftgitx/llms.txt Demonstrates how to open, create, and inspect Git repositories using the Repository class. ```APIDOC ## Repository Initialization and Inspection ### Description Opens an existing repository or creates a new one. Also shows how to inspect repository metadata. ### Methods - `init(at:createIfNotExists:)` - `open(at:)` - `create(at:isBare:)` ### Properties - `isEmpty` (Bool) - `isBare` (Bool) - `isHEADDetached` (Bool) - `workingDirectory` (URL) - `path` (URL) ### Usage Example ```swift import SwiftGitX // Open existing or create new let repoURL = URL(fileURLWithPath: "/tmp/my-repo") let repository = try Repository(at: repoURL) // → creates /tmp/my-repo/.git if it doesn't exist // Open only (throws SwiftGitXError if not found) let existing = try Repository.open(at: repoURL) // Create a bare repository let bareRepo = try Repository.create(at: URL(fileURLWithPath: "/tmp/bare.git"), isBare: true) // Inspect properties print(repository.isEmpty) // true (no commits yet) print(repository.isBare) // false print(repository.isHEADDetached) // false print(try repository.workingDirectory) // file:///tmp/my-repo/ print(repository.path) // file:///tmp/my-repo/.git/ ``` ``` -------------------------------- ### Initialization Source: https://github.com/ibrahimcetin/swiftgitx/blob/main/Sources/SwiftGitX/SwiftGitX.docc/Extensions/SwiftGitX-Extension.md Initializes the SwiftGitX library. This should be called before any other SwiftGitX operations. ```APIDOC ## initialize() ### Description Initializes the SwiftGitX library. ### Method - ``initialize()`` ``` -------------------------------- ### Repository Creation Source: https://github.com/ibrahimcetin/swiftgitx/blob/main/Sources/SwiftGitX/SwiftGitX.docc/Extensions/Repository.md Methods for initializing, opening, creating, and cloning Git repositories. ```APIDOC ## Initializers ### ``init(at:createIfNotExists:)`` Initializes a new repository instance at the specified path. If `createIfNotExists` is true, a new repository will be created if one does not already exist at the path. ### ``open(at:)`` Opens an existing Git repository at the specified path. ### ``create(at:isBare:)`` Creates a new Git repository at the specified path. If `isBare` is true, a bare repository will be created. ### ``clone(from:to:options:)`` Clones a remote repository to a local path with specified options. ### ``clone(from:to:options:transferProgressHandler:)`` Clones a remote repository to a local path with specified options and a handler for transfer progress. ``` -------------------------------- ### Create, Lookup, and List Git Tags Source: https://context7.com/ibrahimcetin/swiftgitx/llms.txt Demonstrates creating annotated and lightweight tags, looking up tags by name, and listing all tags in a repository. Requires a valid Commit object. ```swift let headCommit = try repository.HEAD.target as! Commit let v1 = try repository.tag.create( named: "v1.0.0", target: headCommit, type: .annotated, message: "First stable release" ) print("Created tag: \(v1.name), target: \(v1.target.id)") // Create a lightweight tag try repository.tag.create(named: "build-42", target: headCommit, type: .lightweight) // Look up a tag let tag = try repository.tag.get(named: "v1.0.0") let tagOpt = repository.tag["v1.0.0"] // nil-safe subscript // List all tags let tags = try repository.tag.list() tags.forEach { print($0.name) } // Iterate for tag in repository.tag { print("\(tag.name) → \(tag.target.id)") } ``` -------------------------------- ### Test SwiftGitX Project Source: https://github.com/ibrahimcetin/swiftgitx/blob/main/README.md Run the test suite for SwiftGitX using the Swift Package Manager. This command executes all defined tests to ensure code quality. ```bash swift test ``` -------------------------------- ### Build SwiftGitX Project Source: https://github.com/ibrahimcetin/swiftgitx/blob/main/README.md Build the SwiftGitX project using the Swift Package Manager. This command compiles the library and its dependencies. ```bash swift build ``` -------------------------------- ### Read and Write Git Configuration Source: https://context7.com/ibrahimcetin/swiftgitx/llms.txt Manages repository-level configuration settings in `.git/config` and global configuration in `~/.gitconfig`. Use static methods for global config. ```swift // Set repository-level config try repository.config.set("user.name", to: "Jane Doe") try repository.config.set("user.email", to: "jane@example.com") // Read a config value let name = try repository.config.string(forKey: "user.name") // "Jane Doe" let email = try repository.config.string(forKey: "user.email") // "jane@example.com" // Read the default branch name let defaultBranch = try repository.config.defaultBranchName // "main" // Set / read global configuration (static) try Repository.config.set("user.name", to: "Jane Doe") try Repository.config.set("core.editor", to: "vim") let globalName = try Repository.config.string(forKey: "user.name") ``` -------------------------------- ### repository.config — Configuration Source: https://context7.com/ibrahimcetin/swiftgitx/llms.txt Read and write repository-level and global Git configuration settings. ```APIDOC ## repository.config — Configuration `repository.config` reads and writes repository-level `.git/config`. `Repository.config` (static) accesses the global `~/.gitconfig`. ```swift // Set repository-level config try repository.config.set("user.name", to: "Jane Doe") try repository.config.set("user.email", to: "jane@example.com") // Read a config value let name = try repository.config.string(forKey: "user.name") // "Jane Doe" let email = try repository.config.string(forKey: "user.email") // "jane@example.com" // Read the default branch name let defaultBranch = try repository.config.defaultBranchName // "main" // Set / read global configuration (static) try Repository.config.set("user.name", to: "Jane Doe") try Repository.config.set("core.editor", to: "vim") let globalName = try Repository.config.string(forKey: "user.name") ``` ``` -------------------------------- ### Clone a Remote Repository with SwiftGitX Source: https://context7.com/ibrahimcetin/swiftgitx/llms.txt Use the async static method Repository.clone to clone a remote repository. Supports progress reporting and Swift Task cancellation. ```swift let remoteURL = URL(string: "https://github.com/ibrahimcetin/SwiftGitX.git")! let localURL = URL(fileURLWithPath: "/tmp/SwiftGitX-clone") // Basic clone let repository = try await Repository.clone(from: remoteURL, to: localURL) // Clone with transfer progress let repository = try await Repository.clone( from: remoteURL, to: localURL ) { progress in let pct = Int(Double(progress.receivedObjects) / Double(progress.totalObjects) * 100) print("Clone progress: \(pct)% (\(progress.receivedObjects)/\(progress.totalObjects) objects)") } // Clone supports Swift Task cancellation — cancel the enclosing Task to abort mid-clone let task = Task { let repo = try await Repository.clone(from: remoteURL, to: localURL) return repo } task.cancel() // safely aborts the clone ``` -------------------------------- ### Add SwiftGitX to Package.swift Source: https://github.com/ibrahimcetin/swiftgitx/blob/main/README.md Integrate SwiftGitX into your project by adding it as a dependency in your Package.swift file. Ensure you use the correct version. ```swift dependencies: [ .package(url: "https://github.com/ibrahimcetin/SwiftGitX.git", from: "0.1.0"), ] ``` -------------------------------- ### Stage and Commit Files in SwiftGitX Source: https://context7.com/ibrahimcetin/swiftgitx/llms.txt Stage individual files or multiple files at once using `repository.add()`. Commit staged changes with `repository.commit()`, which returns commit details like ID, summary, author, and date. Access the commit's tree and parents for further inspection. ```swift // Stage individual files try repository.add(path: "README.md") try repository.add(file: URL(fileURLWithPath: "/tmp/my-repo/Sources/main.swift")) // Stage multiple files at once try repository.add(paths: ["README.md", "Package.swift", "Sources/main.swift"]) // Commit staged changes let commit = try repository.commit(message: "Add initial implementation") print("Created commit: \(commit.id)") print("Summary: \(commit.summary)") print("Author: \(commit.author.name)") print("Date: \(commit.date)") // Access commit tree and parents let tree = try commit.tree let parents = try commit.parents print("Parent count: \(parents.count)") ``` -------------------------------- ### Show Operations Source: https://github.com/ibrahimcetin/swiftgitx/blob/main/Sources/SwiftGitX/SwiftGitX.docc/Extensions/Repository.md Methods for showing information about a commit. ```APIDOC ## Show ### ``show(id:)`` Shows information about a commit with the specified ID. ``` -------------------------------- ### Manage Git Remotes Source: https://context7.com/ibrahimcetin/swiftgitx/llms.txt Covers listing, adding, removing, and looking up remotes in a Git repository. Ensure the URL is valid when adding a new remote. ```swift let remotes = try repository.remote.list() remotes.forEach { print("\($0.name): \($0.url)") } // Look up a specific remote let origin = try repository.remote.get(named: "origin") let originOpt = repository.remote["origin"] // nil-safe subscript // Add a remote let upstream = try repository.remote.add( named: "upstream", at: URL(string: "https://github.com/ibrahimcetin/SwiftGitX.git")! ) print("Added: \(upstream.name) → \(upstream.url)") // Remove a remote try repository.remote.remove(upstream) // Iterate for remote in repository.remote { print(remote.name) } ``` -------------------------------- ### Restore Working Tree Files Source: https://context7.com/ibrahimcetin/swiftgitx/llms.txt Discard working tree changes, unstage files, or perform both actions for specific files or the entire repository. Files can be specified by path or URL. ```swift // Discard all unstaged changes (git restore .) try repository.restore() ``` ```swift // Discard changes to specific files try repository.restore(paths: ["README.md"]) ``` ```swift try repository.restore(files: [URL(fileURLWithPath: "/tmp/my-repo/README.md")]) ``` ```swift // Unstage specific files (git restore --staged README.md) try repository.restore(.staged, paths: ["README.md"]) ``` ```swift // Unstage and discard working tree changes try repository.restore([.workingTree, .staged], paths: ["README.md"]) ``` -------------------------------- ### Commit Operations Source: https://github.com/ibrahimcetin/swiftgitx/blob/main/Sources/SwiftGitX/SwiftGitX.docc/Extensions/Repository.md Methods for staging files and creating commits. ```APIDOC ## Create a Commit ### ``add(file:)`` Stages a single file for the next commit. ### ``add(files:)`` Stages multiple files for the next commit. ### ``add(path:)`` Stages a file at the specified path for the next commit. ### ``add(paths:)`` Stages files at the specified paths for the next commit. ### ``commit(message:)`` Creates a new commit with the staged changes and the provided message. ``` -------------------------------- ### Switch Operations Source: https://github.com/ibrahimcetin/swiftgitx/blob/main/Sources/SwiftGitX/SwiftGitX.docc/Extensions/Repository.md Methods for switching branches. ```APIDOC ## Switch ### ``switch(to:)-8oxzx`` Switches the current branch to the specified branch. ### ``switch(to:)-16nyq`` Switches the current branch to the specified branch. ### ``switch(to:)-2ysnq`` Switches the current branch to the specified branch. ``` -------------------------------- ### repository.restore Source: https://context7.com/ibrahimcetin/swiftgitx/llms.txt Restores working tree files to a previous state. Can discard working tree changes, unstage files, or both. ```APIDOC ## repository.restore — Restore Working Tree Files `repository.restore(_:paths:)` discards working tree changes (`.workingTree`), unstages files (`.staged`), or both (`[.workingTree, .staged]`). ```swift // Discard all unstaged changes (git restore .) try repository.restore() // Discard changes to specific files try repository.restore(paths: ["README.md"]) try repository.restore(files: [URL(fileURLWithPath: "/tmp/my-repo/README.md")]) // Unstage specific files (git restore --staged README.md) try repository.restore(.staged, paths: ["README.md"]) // Unstage and discard working tree changes try repository.restore([.workingTree, .staged], paths: ["README.md"]) ``` ``` -------------------------------- ### Libgit2 Version Source: https://github.com/ibrahimcetin/swiftgitx/blob/main/Sources/SwiftGitX/SwiftGitX.docc/Extensions/SwiftGitX-Extension.md Retrieves the version of the underlying libgit2 library used by SwiftGitX. ```APIDOC ## libgit2Version ### Description Provides the version string of the libgit2 library that SwiftGitX is built upon. ### Property - ``libgit2Version`` (String) ``` -------------------------------- ### Manage Git Stashes Source: https://context7.com/ibrahimcetin/swiftgitx/llms.txt Provides functionality for saving, listing, applying, popping, and dropping stashes. Supports saving with options like including untracked files. ```swift // Save current changes to stash try repository.stash.save(message: "WIP: refactoring auth module") // Save with options (include untracked files) try repository.stash.save(message: "With untracked", options: .includeUntracked) // List stashes let stashes = try repository.stash.list() stashes.forEach { print("stash@{\$0.index}: \($0.message)") } // Apply the most recent stash (does not remove it) try repository.stash.apply() // Apply a specific stash entry let entry = stashes[1] try repository.stash.apply(entry) // Pop the most recent stash (applies and removes) try repository.stash.pop() // Pop a specific entry try repository.stash.pop(stashes[0]) // Drop (remove without applying) try repository.stash.drop(stashes[0]) ``` -------------------------------- ### repository.add / repository.commit Source: https://context7.com/ibrahimcetin/swiftgitx/llms.txt Stage files for commit using `repository.add` and then commit the staged changes with `repository.commit`. The commit uses the repository's configured author and committer identity. ```APIDOC ## repository.add / repository.commit — Stage and Commit Files are staged with `repository.add(path:)` or `repository.add(file:)`, then committed with `repository.commit(message:options:)`. The commit uses the repository's configured author/committer identity. ```swift // Stage individual files try repository.add(path: "README.md") try repository.add(file: URL(fileURLWithPath: "/tmp/my-repo/Sources/main.swift")) // Stage multiple files at once try repository.add(paths: ["README.md", "Package.swift", "Sources/main.swift"]) // Commit staged changes let commit = try repository.commit(message: "Add initial implementation") print("Created commit: \(commit.id)") print("Summary: \(commit.summary)") print("Author: \(commit.author.name)") print("Date: \(commit.date)") // Access commit tree and parents let tree = try commit.tree let parents = try commit.parents print("Parent count: \(parents.count)") ``` ``` -------------------------------- ### Switch Branches, Tags, and Commits in SwiftGitX Source: https://context7.com/ibrahimcetin/swiftgitx/llms.txt Update the working tree and HEAD using `repository.switch(to:)`. This method accepts a `Branch`, `Tag`, or `Commit`. Switching to a remote branch automatically creates a local tracking branch. Switching to a tag or commit enters a detached HEAD state. ```swift // Switch to a local branch let develop = try repository.branch.get(named: "develop") try repository.switch(to: develop) print(try repository.branch.current.name) // "develop" // Switch to a remote branch (auto-creates local tracking branch) let remoteBranch = try repository.branch.get(named: "origin/feature/payment", type: .remote) try repository.switch(to: remoteBranch) // Now on local "feature/payment" tracking "origin/feature/payment" // Switch to a tag (enters detached HEAD) let tag = try repository.tag.get(named: "v1.0.0") try repository.switch(to: tag) print(repository.isHEADDetached) // true // Switch to a specific commit (detached HEAD) let oldCommit = try repository.log().dropFirst(5).first! try repository.switch(to: oldCommit) ``` -------------------------------- ### Repository.clone Source: https://context7.com/ibrahimcetin/swiftgitx/llms.txt Clones a remote Git repository to a local path with optional progress reporting and cancellation support. ```APIDOC ## Repository.clone ### Description Clones a remote repository to a local directory. Supports asynchronous operations, progress handlers, and Swift Concurrency task cancellation. ### Method `static func clone(from: URL, to: URL, options: CloneOptions? = nil, transferProgressHandler: ((TransferProgress) -> Void)? = nil) async throws -> Repository` ### Parameters - `from` (URL): The URL of the remote repository. - `to` (URL): The local path where the repository will be cloned. - `options` (CloneOptions?, optional): Options for the clone operation. - `transferProgressHandler` ((TransferProgress) -> Void, optional): A closure to receive progress updates during the clone. ### Response - `Repository`: The newly cloned repository object. ### Usage Example ```swift let remoteURL = URL(string: "https://github.com/ibrahimcetin/SwiftGitX.git")! let localURL = URL(fileURLWithPath: "/tmp/SwiftGitX-clone") // Basic clone let repository = try await Repository.clone(from: remoteURL, to: localURL) // Clone with transfer progress let repository = try await Repository.clone( from: remoteURL, to: localURL ) { progress in let pct = Int(Double(progress.receivedObjects) / Double(progress.totalObjects) * 100) print("Clone progress: \(pct)% (\(progress.receivedObjects)/\(progress.totalObjects) objects)") } // Clone supports Swift Task cancellation — cancel the enclosing Task to abort mid-clone let task = Task { let repo = try await Repository.clone(from: remoteURL, to: localURL) return repo } task.cancel() // safely aborts the clone ``` ``` -------------------------------- ### Compute Differences Source: https://context7.com/ibrahimcetin/swiftgitx/llms.txt Calculate differences between various states of the repository, such as the working tree against the index, the index against HEAD, or between two specific commits. ```swift let workingTreeDiff = try repository.diff() ``` ```swift let stagedDiff = try repository.diff(to: .index) ``` ```swift let fullDiff = try repository.diff(to: [.workingTree, .index]) ``` ```swift let commit = try repository.log().first! let commitDiff = try repository.diff(commit: commit) ``` ```swift let commits = Array(try repository.log()).prefix(3) let betweenDiff = try repository.diff(from: commits[2], to: commits[0]) ``` ```swift print("Files changed: \(commitDiff.deltas.count)") for delta in commitDiff.deltas { print("\(delta.status): \(delta.newFile.path)") } ``` -------------------------------- ### Fetch and Push Git Commits Source: https://context7.com/ibrahimcetin/swiftgitx/llms.txt Asynchronous operations for fetching from and pushing to remote repositories. Defaults to the upstream of the current branch, falling back to 'origin'. ```swift // Fetch from origin (auto-detected) try await repository.fetch() // Fetch from a specific remote let origin = try repository.remote.get(named: "origin") try await repository.fetch(remote: origin) // Push current branch to origin (auto-detected) try await repository.push() // Push to a specific remote try await repository.push(remote: origin) // Push without auto-creating refspec (throws if no refspec configured) try await repository.push(remote: origin, createsRefspec: false) ``` -------------------------------- ### repository.reset Source: https://context7.com/ibrahimcetin/swiftgitx/llms.txt Resets the HEAD and index to a specified state. Supports soft, mixed, and hard resets, as well as resetting specific index entries without moving HEAD. ```APIDOC ## repository.reset — Reset HEAD and Index `repository.reset(to:mode:)` moves HEAD to a commit with `.soft`, `.mixed`, or `.hard` semantics. `repository.reset(from:paths:)` resets specific index entries without moving HEAD (equivalent to `git restore --staged`). ```swift let commits = Array(try repository.log()) // Soft reset — move HEAD, keep index and working tree try repository.reset(to: commits[1], mode: .soft) // Mixed reset (default) — move HEAD and reset index, keep working tree try repository.reset(to: commits[1]) // Hard reset — move HEAD, reset index and working tree try repository.reset(to: commits[1], mode: .hard) // Reset specific files in the index from HEAD (unstage files) try repository.reset(from: commits[0], paths: ["README.md", "Package.swift"]) // Reset specific files using URLs let files = [URL(fileURLWithPath: "/tmp/my-repo/README.md")] try repository.reset(from: commits[0], files: files) ``` ``` -------------------------------- ### repository.switch Source: https://context7.com/ibrahimcetin/swiftgitx/llms.txt Update the working tree and HEAD by switching to a different branch, tag, or commit using `repository.switch(to:)`. Switching to a remote branch automatically creates a local tracking branch. ```APIDOC ## repository.switch — Switch Branches, Tags, and Commits `repository.switch(to:)` updates both the working tree and HEAD. It accepts a `Branch`, `Tag`, or `Commit`. Switching to a remote branch automatically creates a local tracking branch. ```swift // Switch to a local branch let develop = try repository.branch.get(named: "develop") try repository.switch(to: develop) print(try repository.branch.current.name) // "develop" // Switch to a remote branch (auto-creates local tracking branch) let remoteBranch = try repository.branch.get(named: "origin/feature/payment", type: .remote) try repository.switch(to: remoteBranch) // Now on local "feature/payment" tracking "origin/feature/payment" // Switch to a tag (enters detached HEAD) let tag = try repository.tag.get(named: "v1.0.0") try repository.switch(to: tag) print(repository.isHEADDetached) // true // Switch to a specific commit (detached HEAD) let oldCommit = try repository.log().dropFirst(5).first! try repository.switch(to: oldCommit) ``` ``` -------------------------------- ### Restore Operations Source: https://github.com/ibrahimcetin/swiftgitx/blob/main/Sources/SwiftGitX/SwiftGitX.docc/Extensions/Repository.md Methods for restoring files to a previous state. ```APIDOC ## Restore ### ``restore(_:files:)`` Restores specified files to their state in the index or a specified commit. ### ``restore(_:paths:)`` Restores files at specified paths to their state in the index or a specified commit. ### ``RestoreOption`` An enumeration defining options for restoring files. ``` -------------------------------- ### Remote Repository Operations Source: https://github.com/ibrahimcetin/swiftgitx/blob/main/Sources/SwiftGitX/SwiftGitX.docc/Extensions/Repository.md Methods for interacting with remote repositories. ```APIDOC ## Remote Repository Operations ### ``push(remote:)`` Pushes local changes to a specified remote repository. ### ``fetch(remote:)`` Fetches changes from a specified remote repository. ``` -------------------------------- ### repository.show — Look Up Objects by OID Source: https://context7.com/ibrahimcetin/swiftgitx/llms.txt Look up Git objects (Commit, Tree, Blob, Tag) by their Object ID (OID). ```APIDOC ## repository.show — Look Up Objects by OID `repository.show(id:)` performs a generic type-safe lookup of any `Object` (Commit, Tree, Blob, Tag) by its `OID`. ```swift // Look up a commit by OID let commitID = OID(string: "a1b2c3d4...")! let commit: Commit = try repository.show(id: commitID) print("Found: \(commit.summary)") // Look up a tag by OID let tagID = someTag.id let tag: Tag = try repository.show(id: tagID) ``` ``` -------------------------------- ### repository.status Source: https://context7.com/ibrahimcetin/swiftgitx/llms.txt Retrieves the status of the working tree and index. Can be used for the full repository, a single file by path or URL, or with custom options. ```APIDOC ## repository.status — Working Tree and Index Status `repository.status(options:)` returns an array of `StatusEntry` values. `repository.status(path:)` and `repository.status(file:)` return `[StatusEntry.Status]` for a single file. ```swift // Full repository status let entries = try repository.status() for entry in entries { print("\(entry.status) — \(entry.headToIndex?.newFile?.path ?? entry.indexToWorkdir?.newFile?.path ?? "?")") } // Check a single file by relative path let fileStatuses = try repository.status(path: "README.md") // e.g., [.workingTreeModified] or [.indexNew, .workingTreeModified] // Check by URL let fileURL = URL(fileURLWithPath: "/tmp/my-repo/README.md") let statuses = try repository.status(file: fileURL) // Common status values: // .indexNew – new file staged // .indexModified – modified file staged // .indexDeleted – deleted file staged // .workingTreeNew – untracked file // .workingTreeModified – modified but not staged // .ignored – ignored file // Custom options let untrackedOnly = try repository.status(options: .includeUntracked) ``` ``` -------------------------------- ### Status Operations Source: https://github.com/ibrahimcetin/swiftgitx/blob/main/Sources/SwiftGitX/SwiftGitX.docc/Extensions/Repository.md Methods for checking the status of the repository and specific files. ```APIDOC ## Status ### ``status(options:)`` Retrieves the status of the repository with specified options. #### Status of a specific file ### ``status(file:)`` Retrieves the status of a specific file. ### ``status(path:)`` Retrieves the status of a file at a specific path. ``` -------------------------------- ### Revert a Commit Source: https://context7.com/ibrahimcetin/swiftgitx/llms.txt Create inverse changes for a specified commit in the index and working tree, preparing them to be staged and committed as a revert. ```swift // Revert the most recent commit let commits = Array(try repository.log()) try repository.revert(commits[0]) ``` ```swift // Stage and commit the revert try repository.add(paths: ["README.md"]) let revertCommit = try repository.commit(message: "Revert: \(commits[0].summary)") print("Revert commit: \(revertCommit.id)") ``` -------------------------------- ### repository.tag — Tag Management Source: https://context7.com/ibrahimcetin/swiftgitx/llms.txt Manage annotated and lightweight tags within a Git repository. Supports creating, looking up, listing, and iterating through tags. ```APIDOC ## repository.tag — Tag Management `repository.tag` is a `TagCollection` supporting annotated and lightweight tags. ```swift // Create an annotated tag on the current HEAD commit let headCommit = try repository.HEAD.target as! Commit let v1 = try repository.tag.create( named: "v1.0.0", target: headCommit, type: .annotated, message: "First stable release" ) print("Created tag: \(v1.name), target: \(v1.target.id)") // Create a lightweight tag try repository.tag.create(named: "build-42", target: headCommit, type: .lightweight) // Look up a tag let tag = try repository.tag.get(named: "v1.0.0") let tagOpt = repository.tag["v1.0.0"] // nil-safe subscript // List all tags let tags = try repository.tag.list() tags.forEach { print($0.name) } // Iterate for tag in repository.tag { print("\(tag.name) → \(tag.target.id)") } ``` ``` -------------------------------- ### Reset HEAD and Index Source: https://context7.com/ibrahimcetin/swiftgitx/llms.txt Perform soft, mixed, or hard resets to move HEAD and modify the index and working tree. Specific index entries can also be reset without moving HEAD. ```swift let commits = Array(try repository.log()) // Soft reset — move HEAD, keep index and working tree try repository.reset(to: commits[1], mode: .soft) ``` ```swift // Mixed reset (default) — move HEAD and reset index, keep working tree try repository.reset(to: commits[1]) ``` ```swift // Hard reset — move HEAD, reset index and working tree try repository.reset(to: commits[1], mode: .hard) ``` ```swift // Reset specific files in the index from HEAD (unstage files) try repository.reset(from: commits[0], paths: ["README.md", "Package.swift"]) ``` ```swift // Reset specific files using URLs let files = [URL(fileURLWithPath: "/tmp/my-repo/README.md")] try repository.reset(from: commits[0], files: files) ``` -------------------------------- ### Repository Properties Source: https://github.com/ibrahimcetin/swiftgitx/blob/main/Sources/SwiftGitX/SwiftGitX.docc/Extensions/Repository.md Accessors for key properties of a Git repository. ```APIDOC ## Properties - ``HEAD``: Access the current HEAD reference. - ``workingDirectory``: Get the path to the working directory. - ``isHEADDetached``: Check if the HEAD is in a detached state. - ``isHEADUnborn``: Check if the repository has an unborn HEAD. - ``isEmpty``: Check if the repository is empty. - ``isBare``: Check if the repository is a bare repository. - ``isShallow``: Check if the repository is a shallow clone. ``` -------------------------------- ### Log Operations Source: https://github.com/ibrahimcetin/swiftgitx/blob/main/Sources/SwiftGitX/SwiftGitX.docc/Extensions/Repository.md Methods for retrieving commit history. ```APIDOC ## Log ### ``log(sorting:)`` Retrieves the commit history with specified sorting options. ### ``log(from:sorting:)-2c8fu`` Retrieves the commit history from a specific commit with specified sorting options. ### ``log(from:sorting:)-3rteq`` Retrieves the commit history from a specific commit with specified sorting options. ### ``LogSortingOption`` An enumeration defining options for sorting commit logs. ``` -------------------------------- ### repository.diff Source: https://context7.com/ibrahimcetin/swiftgitx/llms.txt Computes differences between various states of the repository. Supports diffing the working tree against the index, index against HEAD, a commit against its parent, or between two arbitrary commits. ```APIDOC ## repository.diff — Compute Differences `repository.diff(to:)` produces a `Diff` representing current changes. `repository.diff(from:to:)` compares two arbitrary objects. `repository.diff(commit:)` diffs a commit against its parent. ```swift // Diff working tree against index (git diff) let workingTreeDiff = try repository.diff() // Diff index against HEAD (git diff --cached) let stagedDiff = try repository.diff(to: .index) // Diff HEAD plus working tree (git diff HEAD) let fullDiff = try repository.diff(to: [.workingTree, .index]) // Diff a specific commit against its parent let commit = try repository.log().first! let commitDiff = try repository.diff(commit: commit) // Diff between two commits let commits = Array(try repository.log()).prefix(3) let betweenDiff = try repository.diff(from: commits[2], to: commits[0]) // Inspect diff results print("Files changed: \(commitDiff.deltas.count)") for delta in commitDiff.deltas { print("\(delta.status): \(delta.newFile.path)") } ``` ``` -------------------------------- ### Access the Current HEAD Reference with SwiftGitX Source: https://context7.com/ibrahimcetin/swiftgitx/llms.txt Access the current HEAD reference using repository.HEAD. It can be a Branch or Tag and throws if HEAD is unborn. Retrieve the target commit details. ```swift // Get current HEAD let head = try repository.HEAD // HEAD as a Branch if let branch = head as? Branch { print("On branch: \(branch.name)") // "main" print("Full ref: \(branch.fullName)") // "refs/heads/main" print("Type: \(branch.type)") // .local } // Get HEAD's target commit if let commit = head.target as? Commit { print("Latest commit: \(commit.id)") print("Message: \(commit.summary)") print("Author: \(commit.author.name) <\(commit.author.email)>") print("Date: \(commit.date)") } // Detached HEAD (e.g., after switching to a tag) print(repository.isHEADDetached) // true when HEAD points to a commit directly ``` -------------------------------- ### repository.fetch / repository.push — Network Operations Source: https://context7.com/ibrahimcetin/swiftgitx/llms.txt Perform network operations to fetch data from or push data to remote repositories. Operations target the upstream remote by default. ```APIDOC ## repository.fetch / repository.push — Network Operations Both `fetch` and `push` are `async` and target the upstream remote of the current branch by default, falling back to `origin`. ```swift // Fetch from origin (auto-detected) try await repository.fetch() // Fetch from a specific remote let origin = try repository.remote.get(named: "origin") try await repository.fetch(remote: origin) // Push current branch to origin (auto-detected) try await repository.push() // Push to a specific remote try await repository.push(remote: origin) // Push without auto-creating refspec (throws if no refspec configured) try await repository.push(remote: origin, createsRefspec: false) ``` ``` -------------------------------- ### Patch Operations Source: https://github.com/ibrahimcetin/swiftgitx/blob/main/Sources/SwiftGitX/SwiftGitX.docc/Extensions/Repository.md Methods for generating and applying patches. ```APIDOC ## Patch ### ``patch(from:)`` Generates a patch from a specified commit or reference. ### ``patch(from:to:)-10g8i`` Generates a patch between two specified commits or references. ### ``patch(from:to:)-957bd`` Generates a patch between two specified commits or references. ``` -------------------------------- ### Look Up Git Objects by OID Source: https://context7.com/ibrahimcetin/swiftgitx/llms.txt Performs type-safe lookups for any Git object (Commit, Tree, Blob, Tag) using its Object ID (OID). ```swift // Look up a commit by OID let commitID = OID(string: "a1b2c3d4...")! let commit: Commit = try repository.show(id: commitID) print("Found: \(commit.summary)") // Look up a tag by OID let tagID = someTag.id let tag: Tag = try repository.show(id: tagID) ``` -------------------------------- ### Handle SwiftGitX Errors with Typed Throws Source: https://context7.com/ibrahimcetin/swiftgitx/llms.txt Use a `do-catch` block to handle `SwiftGitXError`. Inspect properties like `code`, `category`, `operation`, and `message` for detailed error information. Utilize semantic properties on `error.code` for cleaner conditional logic. ```swift do { let branch = try repository.branch.get(named: "nonexistent") } catch let error as SwiftGitXError { // Structured error inspection print(error.code) // .notFound print(error.category) // .reference print(error.operation?.rawValue ?? "none") // "branchList" print(error.message) // "reference 'refs/heads/nonexistent' not found" // Semantic code checks if error.code.isNotFound { print("Branch does not exist — creating it") } if error.code.isConflict { print("Merge conflict detected") } if error.code.isAuth { print("Authentication failed") } if error.code.requiresForce { print("Use force: true to overwrite") } // Pretty debug output print(error.debugDescription) // ┌─ SwiftGitXError ──────────────────────────── // │ Operation: branchList // │ Code: notFound // │ Category: reference // │ Message: reference 'refs/heads/nonexistent' not found // └───────────────────────────────────────────── } ``` -------------------------------- ### Shutdown Source: https://github.com/ibrahimcetin/swiftgitx/blob/main/Sources/SwiftGitX/SwiftGitX.docc/Extensions/SwiftGitX-Extension.md Shuts down the SwiftGitX library. This should be called when the library is no longer needed to release resources. ```APIDOC ## shutdown() ### Description Shuts down the SwiftGitX library and releases any associated resources. ### Method - ``shutdown()`` ``` -------------------------------- ### repository.HEAD Source: https://context7.com/ibrahimcetin/swiftgitx/llms.txt Accesses the current HEAD reference of the repository, which can be a Branch or a Tag. ```APIDOC ## repository.HEAD ### Description Provides access to the current HEAD reference of the repository. It can be cast to a `Branch` or used to retrieve the target `Commit`. ### Method `repository.HEAD` ### Throws `SwiftGitXError` if HEAD is unborn (repository has no commits). ### Properties of HEAD - `target` (ReferenceTarget): The commit or reference that HEAD points to. ### Casting to Branch If HEAD is a branch, it can be cast to a `Branch` type. - `name` (String): The name of the branch. - `fullName` (String): The full reference name (e.g., "refs/heads/main"). - `type` (BranchType): The type of the branch (e.g., `.local`). ### Accessing Commit Information If the `target` is a `Commit`: - `id` (String): The commit SHA. - `summary` (String): The commit summary (first line of the message). - `author` (Signature): The author's name and email. - `date` (Date): The commit date. ### Detached HEAD - `repository.isHEADDetached` (Bool): Returns `true` if HEAD points directly to a commit (detached HEAD state). ### Usage Example ```swift // Get current HEAD let head = try repository.HEAD // HEAD as a Branch if let branch = head as? Branch { print("On branch: \(branch.name)") // "main" print("Full ref: \(branch.fullName)") // "refs/heads/main" print("Type: \(branch.type)") // .local } // Get HEAD's target commit if let commit = head.target as? Commit { print("Latest commit: \(commit.id)") print("Message: \(commit.summary)") print("Author: \(commit.author.name) <\(commit.author.email)>") print("Date: \(commit.date)") } // Detached HEAD (e.g., after switching to a tag) print(repository.isHEADDetached) // true when HEAD points to a commit directly ``` ``` -------------------------------- ### Collections Source: https://github.com/ibrahimcetin/swiftgitx/blob/main/Sources/SwiftGitX/SwiftGitX.docc/Extensions/Repository.md Accessors for various collections within the repository. ```APIDOC ## Collections - ``branch``: Access the repository's branches. - ``config-swift.property``: Access repository configuration properties. - ``config-swift.type.property``: Access repository configuration types. - ``reference``: Access all references in the repository. - ``remote``: Access the repository's remotes. - ``stash``: Access stashed changes. - ``tag``: Access the repository's tags. ``` -------------------------------- ### Reset Operations Source: https://github.com/ibrahimcetin/swiftgitx/blob/main/Sources/SwiftGitX/SwiftGitX.docc/Extensions/Repository.md Methods for resetting the current branch to a specified state. ```APIDOC ## Reset ### ``reset(to:mode:)`` Resets the current branch to a specified commit or reference with a given mode. ### ``ResetOption`` An enumeration defining options for reset operations. ### ``reset(from:files:)`` Resets specified files to their state in a specified commit or reference. ### ``reset(from:paths:)`` Resets files at specified paths to their state in a specified commit or reference. ``` -------------------------------- ### repository.stash — Stash Management Source: https://context7.com/ibrahimcetin/swiftgitx/llms.txt Manage stashed changes. Supports saving, listing, applying, popping, and dropping stashes. ```APIDOC ## repository.stash — Stash Management `repository.stash` is a `StashCollection` for saving, listing, applying, popping, and dropping stashes. ```swift // Save current changes to stash try repository.stash.save(message: "WIP: refactoring auth module") // Save with options (include untracked files) try repository.stash.save(message: "With untracked", options: .includeUntracked) // List stashes let stashes = try repository.stash.list() stashes.forEach { print("stash@{\\$0.index)}: \($0.message)") } // Apply the most recent stash (does not remove it) try repository.stash.apply() // Apply a specific stash entry let entry = stashes[1] try repository.stash.apply(entry) // Pop the most recent stash (applies and removes) try repository.stash.pop() // Pop a specific entry try repository.stash.pop(stashes[0]) // Drop (remove without applying) try repository.stash.drop(stashes[0]) ``` ```