### Get libgit2 Version Source: https://github.com/skinnymind/libgit2dart/blob/master/README.md Verify the installation by printing the version of the bundled libgit2 library. ```dart print(Libgit2.version); ``` -------------------------------- ### Manage Git Configuration Files Source: https://github.com/skinnymind/libgit2dart/blob/master/README.md Demonstrates how to open configuration files, access repository-specific configurations, get, set, and delete configuration variables. ```dart final config = Config.open('path/to/config'); // => Config final config = repo.config; // => Config config['user.name'].value; // => 'Some Name' config['user.name'] = 'Another Name'; config.delete('user.name'); ``` -------------------------------- ### Clean and Setup libgit2dart Source: https://github.com/skinnymind/libgit2dart/blob/master/README.md If you upgrade the libgit2dart package, run these commands to clean the existing library and set up the latest version. ```shell dart run libgit2dart:setup clean dart run libgit2dart:setup ``` -------------------------------- ### Import libgit2dart Package Source: https://github.com/skinnymind/libgit2dart/blob/master/README.md Import the libgit2dart package to start using its functionalities. ```dart import 'package:libgit2dart/libgit2dart.dart'; ``` -------------------------------- ### Manage Git References Source: https://github.com/skinnymind/libgit2dart/blob/master/README.md Learn how to get, lookup, create, update, rename, and delete references in a Git repository. Also shows how to access and inspect the reflog. ```dart final refs = repo.references; // => ['refs/heads/master', 'refs/tags/v0.1', ...] final ref = Reference.lookup(repo: repo, name: 'refs/heads/master'); // => Reference ref.type; // => ReferenceType.direct ref.target; // => Oid ref.name; // => 'refs/heads/master' final ref = Reference.create( repo: repo, name: 'refs/heads/feature', target: repo['821ed6e'], ); // => Reference ref.setTarget(repo['c68ff54']); Reference.rename(repo: repo, oldName: 'refs/heads/feature', newName: 'refs/heads/feature2'); Reference.delete(repo: repo, name: 'refs/heads/feature2'); final reflog = ref.log; // => RefLog final entry = reflog.first; // RefLogEntry entry.message; // => 'commit (initial): init' entry.committer; // => Signature ``` -------------------------------- ### Setup libgit2dart for Dart Applications Source: https://github.com/skinnymind/libgit2dart/blob/master/README.md Run this command to copy the prebuilt libgit2 library for your platform into the .dart_tool directory. This is required for Dart applications, not Flutter release builds. ```shell dart run libgit2dart:setup ``` -------------------------------- ### Open, Initialize, and Clone Repositories with libgit2dart Source: https://context7.com/skinnymind/libgit2dart/llms.txt Demonstrates opening an existing repository, initializing a new one, cloning a remote repository, and discovering the Git directory from a sub-path. Includes examples of accessing repository properties and handling credentials during cloning. ```dart import 'package:libgit2dart/libgit2dart.dart'; void main() { // Open an existing repository final repo = Repository.open('/path/to/my-repo'); print(repo.path); // => '/path/to/my-repo/.git/' print(repo.workdir); // => '/path/to/my-repo/' print(repo.isBare); // => false print(repo.isEmpty); // => false print(repo.state); // => GitRepositoryState.none // Initialize a new repository (mkpath creates intermediate directories) final newRepo = Repository.init( path: '/tmp/new-repo', bare: false, initialHead: 'main', ); print(newRepo.isEmpty); // => true // Clone from a remote URL final cloned = Repository.clone( url: 'https://github.com/example/repo.git', localPath: '/tmp/cloned-repo', checkoutBranch: 'main', callbacks: Callbacks( credentials: (url, usernameFromUrl, allowedTypes) => Keypair( username: 'git', pubKey: '/home/user/.ssh/id_rsa.pub', privateKey: '/home/user/.ssh/id_rsa', passPhrase: '', ), ), ); print(cloned.remotes); // => ['origin'] // Discover .git from a sub-directory final gitDir = Repository.discover(startPath: '/path/to/my-repo/lib/src'); print(gitDir); // => '/path/to/my-repo/.git/' repo.free(); newRepo.free(); cloned.free(); } ``` -------------------------------- ### Get Repository Paths Source: https://github.com/skinnymind/libgit2dart/blob/master/README.md Retrieve the path to the '.git' directory and the working directory of the repository. ```dart // Path getters repo.path; // => 'path/to/repository/.git/' repo.workdir; // => 'path/to/repository/' ``` -------------------------------- ### Generate Bindings with Ffigen Source: https://github.com/skinnymind/libgit2dart/blob/master/README.md Use the dart run ffigen command to generate bindings. Adjust the compiler include paths (-I) to match your libgit2 and clang installation. ```bash dart run ffigen --compiler-opts "-I/path/to/libgit2dart/libgit2/headers/ -I/lib64/clang/12.0.1/include" ``` -------------------------------- ### Activate Coverage Package Source: https://github.com/skinnymind/libgit2dart/blob/master/README.md Activate the coverage package globally. Ensure lcov is also installed. ```sh $ dart pub global activate coverage ``` -------------------------------- ### Manage Submodules Source: https://github.com/skinnymind/libgit2dart/blob/master/README.md Use repo.submodules to get a list of submodule paths. Submodule.lookup finds a submodule, Submodule.init initializes, Submodule.update updates, and Submodule.add adds a new submodule. Submodule objects have properties for name, path, and URL, and a sync method. ```dart repo.submodules; // => ['Submodule1', 'Submodule2']; Submodule.lookup(repo: repo, name: 'Submodule'); // => Submodule Submodule.init(repo: repo, name: 'Submodule'); Submodule.update(repo: repo, name: 'Submodule'); Submodule.add(repo: repo, url: 'https://some.url', path: 'submodule'); // => Submodule submodule.name; // => 'Submodule' submodule.path; // => 'Submodule' submodule.url; // => 'https://some.url' submodule.url = 'https://updated.url'; submodule.sync(); ``` -------------------------------- ### Perform Interactive-Style Rebases Source: https://context7.com/skinnymind/libgit2dart/llms.txt Rebase wraps libgit2's rebase API for replaying commits onto a new base. This example shows how to initialize a rebase, apply operations, and handle conflicts. ```dart import 'package:libgit2dart/libgit2dart.dart'; void main() { final repo = Repository.open('/path/to/my-repo'); // Start a rebase of current branch onto 'main' final onto = AnnotatedCommit.lookup( repo: repo, oid: Branch.lookup(repo: repo, name: 'main').target, ); final rebase = Rebase.init(repo: repo, onto: onto); print('Operations to apply: ${rebase.operationsCount}'); // Apply each operation while (rebase.operationCurrentIndex < rebase.operationsCount) { final op = rebase.next(); // applies the next commit print('Applying: ${op?.id}'); if (repo.index.hasConflicts) { // Resolve conflicts, then: repo.index.cleanupConflict(); repo.index.write(); } rebase.commit( committer: repo.defaultSignature, ); } rebase.finish(repo.defaultSignature); repo.free(); } ``` -------------------------------- ### Manage Worktrees Source: https://github.com/skinnymind/libgit2dart/blob/master/README.md Use repo.worktrees to get a list of worktree names. Worktree.lookup finds an existing worktree, Worktree.create creates a new one. Worktree objects have methods to lock, unlock, and prune. ```dart repo.worktrees; // => ['worktree1', 'worktree2']; Worktree.lookup(repo: repo, name: 'worktree1'); // => Worktree final worktree = Worktree.create( repo: repo, name: 'worktree3', path: '/worktree3/path/', ); // => Worktree worktree.name; // => 'worktree3' worktree.path; // => '/worktree3/path/'; worktree.lock(); worktree.unlock(); worktree.prune(); ``` -------------------------------- ### Access Repository HEAD Source: https://github.com/skinnymind/libgit2dart/blob/master/README.md Get the HEAD reference of the repository. From the reference, you can access its name, target Oid, and target SHA. ```dart // The HEAD of the repository final ref = repo.head; // => Reference // From returned ref you can get the 'name', 'target', target 'sha' and much more ref.name; // => 'refs/heads/master' ref.target; // => Oid ref.target.sha; // => '821ed6e80627b8769d170a293862f9fc60825226' ``` -------------------------------- ### Repository Status, Reset, and Describe Operations Source: https://context7.com/skinnymind/libgit2dart/llms.txt Covers checking the status of files in the working tree and index, performing hard and soft resets to specific commits, and describing the current worktree using `git describe` conventions. Also shows how to get ahead/behind counts between branches. ```dart import 'package:libgit2dart/libgit2dart.dart'; void main() { final repo = Repository.open('/path/to/my-repo'); // Full working-tree status final statusMap = repo.status; for (final entry in statusMap.entries) { print('${entry.key}: ${entry.value}'); // e.g. 'README.md: {GitStatus.indexModified}' } // Single-file status final fileStatus = repo.statusFile('README.md'); print(fileStatus); // => {GitStatus.wtModified} // Hard reset to a specific commit repo.reset( oid: repo['abc1234'], resetType: GitReset.hard, ); // Soft reset, keeping staged changes repo.reset( oid: repo['HEAD~1'], resetType: GitReset.soft, ); // Describe current worktree (like `git describe --tags`) final description = repo.describe( describeStrategy: GitDescribeStrategy.tags, abbreviatedSize: 7, dirtySuffix: '-dirty', ); print(description); // => 'v1.2.0-3-gabcdef1-dirty' // Ahead/behind counts between two commits final counts = repo.aheadBehind( local: repo['refs/heads/feature'], upstream: repo['refs/heads/main'], ); print('ahead: ${counts[0]}, behind: ${counts[1]}'); repo.free(); } ``` -------------------------------- ### Manage Stashes Source: https://github.com/skinnymind/libgit2dart/blob/master/README.md Use repo.stashes to get a list of stashes. Stash.create saves local modifications, Stash.apply applies a stash, Stash.drop removes a stash, and Stash.pop applies and removes a stash. Defaults to the last saved stash if index is not provided. ```dart repo.stashes; // => [Stash, Stash, ...] Stash.create(repo: repo, stasher: signature, message: 'WIP'); // => Oid Stash.apply(repo: repo); Stash.apply(repo: repo, paths: ['file.txt']); Stash.drop(repo: repo); Stash.pop(repo: repo); ``` -------------------------------- ### Repository Instantiation Source: https://github.com/skinnymind/libgit2dart/blob/master/README.md Demonstrates how to open an existing repository, create a new one, or clone a remote repository. ```APIDOC ## Repository Instantiation ### Description Instantiate a `Repository` class to interact with a Git repository. ### Methods - `Repository.open(String path)`: Opens an existing repository at the specified path. - `Repository.init({required String path, bool bare = false})`: Creates a new repository at the specified path. The `bare` parameter determines if it's a bare repository. - `Repository.clone({required String url, required String localPath})`: Clones an existing repository from a URL to a local path. - `Repository.discover({required String startPath})`: Discovers the path to the `.git` directory starting from a given path. ### Examples ```dart // Open an existing repository final repo = Repository.open('path/to/repository'); // Create a new bare repository final newRepo = Repository.init(path: 'path/to/new/repo', bare: true); // Clone a repository final clonedRepo = Repository.clone( url: 'https://github.com/user/repo.git', localPath: 'path/to/clone/destination', ); // Discover repository path final gitDirPath = Repository.discover(startPath: '/path/to/repo/subdir'); ``` ``` -------------------------------- ### Initialize New Repository Source: https://github.com/skinnymind/libgit2dart/blob/master/README.md Create a new Git repository at the specified path. Use the 'bare' argument to create a bare repository. ```dart final repo = Repository.init(path: 'path/to/folder', bare: true); // => Repository ``` -------------------------------- ### Get Repository State Source: https://github.com/skinnymind/libgit2dart/blob/master/README.md Access boolean properties to check the state of the repository, such as whether it is bare, empty, or has a detached HEAD. ```dart // Boolean repository state values repo.isBare; // => false repo.isEmpty; // => true repo.isHeadDetached; // => false repo.isBranchUnborn; // => false repo.isWorktree; // => false ``` -------------------------------- ### Oid Instantiation Source: https://github.com/skinnymind/libgit2dart/blob/master/README.md Demonstrates how to instantiate an Oid object from a SHA-1 string using either a repository alias or the Oid.fromSHA constructor. ```APIDOC ## Oid Instantiation ### Description Lookups of Git objects require an Oid object, which can be instantiated from a provided SHA-1 string. ### Usage ```dart // Using alias on repository object with SHA-1 string that can be any length // between 4 and 40 characters final oid = repo['821ed6e']; // Using named constructor from Oid class (rules for SHA-1 string length is // the same) final oid = Oid.fromSHA(repo: repo, sha: '821ed6e'); ``` ``` -------------------------------- ### Lookup Blob and Get Properties Source: https://github.com/skinnymind/libgit2dart/blob/master/README.md Lookup a blob object using its Oid and access its properties like Oid, content, and size. ```dart // Lookup blob final blob = Blob.lookup(repo: repo, oid: repo['e69de29']); // => Blob blob.oid; // => Oid blob.content; // => 'content of the file' blob.size; // => 19 ``` -------------------------------- ### Manage Libgit2 Global Version and Options Source: https://context7.com/skinnymind/libgit2dart/llms.txt Verify the bundled libgit2 version and get/set global options like search path, mwindow size, and caching. ```dart import 'package:libgit2dart/libgit2dart.dart'; void main() { // Verify the bundled library version print(Libgit2.version); // => '1.5.0' // Get/set global options final opts = Libgit2.opts; print(opts.searchPath(GitConfigLevel.global)); // => '/home/user' opts.setSearchPath( level: GitConfigLevel.global, path: '/custom/config/path', ); // Mwindow size for pack reads print(opts.mwindowSize); opts.setMwindowSize(128 * 1024 * 1024); // 128 MB // Enable caching opts.enableCaching(true); } ``` -------------------------------- ### Open Existing Repository Source: https://github.com/skinnymind/libgit2dart/blob/master/README.md Instantiate a Repository object by providing the path to an existing Git repository. ```dart final repo = Repository.open('path/to/repository'); // => Repository ``` -------------------------------- ### Lookup Tag and Get Properties Source: https://github.com/skinnymind/libgit2dart/blob/master/README.md Lookup a tag object using its Oid and access its properties like Oid, name, and target information. ```dart // Lookup tag final tag = Tag.lookup(repo: repo, oid: repo['f0fdbf5']); // => Tag // Get list of all the tags names in repository repo.tags; // => ['v0.1', 'v0.2'] tag.oid; // => Oid tag.name; // => 'v0.1' ``` -------------------------------- ### Lookup Commit and Get Properties Source: https://github.com/skinnymind/libgit2dart/blob/master/README.md Lookup a commit object using its Oid and access its properties like message, time, author, and tree. ```dart final commit = Commit.lookup(repo: repo, oid: repo['821ed6e']); // => Commit commit.message; // => 'initial commit\n' commit.time; // => 1635869993 (seconds since epoch) commit.author; // => Signature commit.tree; // => Tree ``` -------------------------------- ### Traverse Commits with RevWalk Source: https://github.com/skinnymind/libgit2dart/blob/master/README.md Use the RevWalk class for fine-grained control over commit traversal. Allows setting sorting, pushing starting points, and hiding commits. ```dart // Use RevWalk object to fine tune traversal final walker = RevWalk(repo); // => RevWalk // Set desired sorting (optional) walker.sorting({GitSort.topological, GitSort.time}); // Push Oid for the starting point walker.push(repo['821ed6e']); // Hide commits if you are not interested in anything beneath them walker.hide(repo['c68ff54']); // Perform traversal final commits = walker.walk(); // => [Commit, Commit, ...] ``` -------------------------------- ### Repository Management Source: https://context7.com/skinnymind/libgit2dart/llms.txt Operations for opening, initializing, cloning, and discovering Git repositories. ```APIDOC ## Repository — open, initialize, and clone repositories `Repository` is the central entry point. It can open an existing repository, initialize a new one, clone a remote repository, or discover the `.git` directory from any sub-path. ### Method - `Repository.open(String path)` - `Repository.init({required String path, bool bare = false, String? initialHead})` - `Repository.clone({required String url, required String localPath, String? checkoutBranch, Callbacks? callbacks})` - `Repository.discover({required String startPath})` ### Description These methods allow for interacting with Git repositories by opening existing ones, creating new ones, cloning from remote URLs, or finding the Git directory from a subdirectory. ### Request Example ```dart import 'package:libgit2dart/libgit2dart.dart'; // Open an existing repository final repo = Repository.open('/path/to/my-repo'); // Initialize a new repository final newRepo = Repository.init( path: '/tmp/new-repo', bare: false, initialHead: 'main', ); // Clone from a remote URL final cloned = Repository.clone( url: 'https://github.com/example/repo.git', localPath: '/tmp/cloned-repo', checkoutBranch: 'main', ); // Discover .git from a sub-directory final gitDir = Repository.discover(startPath: '/path/to/my-repo/lib/src'); ``` ### Response #### Success Response - `Repository`: An instance of the Repository class representing the opened, initialized, or cloned repository. #### Response Example ```dart // For Repository.open print(repo.path); // => '/path/to/my-repo/.git/' // For Repository.init print(newRepo.isEmpty); // => true // For Repository.clone print(cloned.remotes); // => ['origin'] // For Repository.discover print(gitDir); // => '/path/to/my-repo/.git/' ``` ``` -------------------------------- ### Traverse Commits with Repository Log Source: https://github.com/skinnymind/libgit2dart/blob/master/README.md Traverse a set of commits starting from a provided Oid using the repository's log method. Returns a list of Commit objects. ```dart // Traverse a set of commits starting at provided oid final commits = repo.log(oid: repo['821ed6e']); // => [Commit, Commit, ...] ``` -------------------------------- ### Blob Creation and Lookup Source: https://github.com/skinnymind/libgit2dart/blob/master/README.md Details how to create blobs from disk and look up existing blobs, along with accessing blob properties. ```APIDOC ## Blob ### Description Provides methods for creating and looking up Git blobs. ### Create Blob from Disk ```dart final oid = Blob.createFromDisk(repo: repo, path: 'path/to/file.txt'); // => Oid ``` ### Lookup Blob ```dart final blob = Blob.lookup(repo: repo, oid: repo['e69de29']); // => Blob ``` ### Blob Getters ```dart blob.oid; // => Oid blob.content; // => 'content of the file' blob.size; // => 19 ``` ``` -------------------------------- ### Run Tests and Generate Coverage Source: https://github.com/skinnymind/libgit2dart/blob/master/README.md Execute the coverage script to run all tests and generate a coverage report. Open the generated HTML report in a browser. ```sh $ ./coverage.sh $ open coverage/index.html ``` -------------------------------- ### Inspect and Manipulate Index Source: https://github.com/skinnymind/libgit2dart/blob/master/README.md Access and modify the Git index (staging area). Operations include reading, writing, iterating over entries, getting specific entries, staging, and unstaging files. ```dart // Initialize Index object final index = repo.index; // => Index // Get number of entries in index index.length; // => 69 // Re-read the index from disk index.read(); // Write an existing index object to disk index.write(); // Iterate over index entries for (final entry in index) { print(entry.path); // => 'path/to/file.txt' } // Get a specific entry final entry = index['file.txt']; // => IndexEntry // Stage using path to file or IndexEntry (updates existing entry if there is one) index.add('new.txt'); // Unstage entry from index index.remove('new.txt'); ``` -------------------------------- ### Tag Creation and Lookup Source: https://github.com/skinnymind/libgit2dart/blob/master/README.md Explains how to create annotated and lightweight tags, look up existing tags, and retrieve tag information. ```APIDOC ## Tag ### Description Provides methods for creating and looking up Git tags. ### Create Annotated Tag ```dart final annotated = Tag.createAnnotated( repo: repo, tagName: 'v0.1', target: repo['821ed6e'], targetType: GitObject.commit, tagger: repo.defaultSignature, message: 'tag message', ); // => Oid ``` ### Create Lightweight Tag ```dart final lightweight = Tag.createLightweight( repo: repo, tagName: 'v0.1', target: repo['821ed6e'], targetType: GitObject.commit, ); // => Oid ``` ### Lookup Tag ```dart final tag = Tag.lookup(repo: repo, oid: repo['f0fdbf5']); // => Tag ``` ### Repository Tags ```dart // Get list of all the tags names in repository repo.tags; // => ['v0.1', 'v0.2'] ``` ### Tag Getters ```dart tag.oid; // => Oid tag.name; // => 'v0.1' ``` ``` -------------------------------- ### Configure Target Properties and Link Libraries Source: https://github.com/skinnymind/libgit2dart/blob/master/windows/CMakeLists.txt Sets target properties such as include directories and links necessary libraries for the plugin. ```cmake target_include_directories(${PLUGIN_NAME} INTERFACE "${CMAKE_CURRENT_SOURCE_DIR}/include") target_link_libraries(${PLUGIN_NAME} PRIVATE flutter flutter_wrapper_plugin) ``` -------------------------------- ### Create Symlinks for Shared Libraries on Linux Source: https://github.com/skinnymind/libgit2dart/blob/master/README.md On non-Debian based Linux distributions, create symlinks for libpcre.so.3 and libpcreposix.so.3 if you encounter 'Failed to load dynamic library' errors. ```shell sudo ln -s /usr/lib64/libpcre.so /usr/lib64/libpcre.so.3 sudo ln -s /usr/lib64/libpcreposix.so /usr/lib64/libpcreposix.so.3 ``` -------------------------------- ### Config files Source: https://github.com/skinnymind/libgit2dart/blob/master/README.md Manage Git configuration files, including opening, accessing, setting, and deleting configuration variables. ```APIDOC ## Config files ### Description Manage Git configuration files, including opening, accessing, setting, and deleting configuration variables. ### Methods - **`Config.open(path: 'path/to/config')`**: Open a config file at a given path. - **`repo.config`**: Access the repository's configuration. ### Operations - **`config['variable.name'].value`**: Get the value of a config variable. - **`config['variable.name'] = 'new_value'`**: Set the value of a config variable. - **`config.delete('variable.name')`**: Delete a config variable. ``` -------------------------------- ### Perform Different Types of Checkout Source: https://github.com/skinnymind/libgit2dart/blob/master/README.md Use Checkout.head, Checkout.index, Checkout.reference, or Checkout.commit to update files in the index and working directory. Strategies and specific paths can be specified. ```dart Checkout.head(repo: repo); Checkout.index(repo: repo); Checkout.reference(repo: repo, name: 'refs/heads/master'); Checkout.commit(repo: repo, commit: commit); Checkout.head(repo: repo, strategy: {GitCheckout.force}); Checkout.head(repo: repo, paths: ['some/file.txt']); ``` -------------------------------- ### List Bundled Libraries Source: https://github.com/skinnymind/libgit2dart/blob/master/windows/CMakeLists.txt Defines a list of absolute paths to libraries that should be bundled with the plugin. ```cmake set(libgit2dart_bundled_libraries "${CMAKE_CURRENT_SOURCE_DIR}/libgit2-1.5.0.dll" PARENT_SCOPE ) ``` -------------------------------- ### Manage Git Configuration with libgit2dart Source: https://context7.com/skinnymind/libgit2dart/llms.txt Provides access to repository, global, and system Git configuration files. Supports reading, writing, and deleting configuration variables. ```dart import 'package:libgit2dart/libgit2dart.dart'; void main() { final repo = Repository.open('/path/to/my-repo'); // Repository config (includes global and system layers) final config = repo.config; // Read values print(config['user.name'].value); // => 'Alice' print(config['user.email'].value); // => 'alice@example.com' print(config['core.bare'].value); // => 'false' // Write values (bool, int, or String) config['user.name'] = 'Bob'; config['core.autocrlf'] = false; config['core.repositoryformatversion'] = 0; // Delete a variable config.delete('user.name'); // Iterate all entries at any level for (final entry in config) { print('${entry.name} = ${entry.value} [${entry.level}]'); } // Open a specific file final localConfig = Config.open('/path/to/my-repo/.git/config'); print(localConfig['remote.origin.url'].value); // Open the global config final globalConfig = Config.global(); // Multi-value variables final values = config.multivar(variable: 'remote.origin.fetch'); print(values); // => ['+refs/heads/*:refs/remotes/origin/*'] repo.free(); } ``` -------------------------------- ### Repository Status, Reset, and Describe Source: https://context7.com/skinnymind/libgit2dart/llms.txt Operations for checking repository status, performing resets, and describing the repository state. ```APIDOC ## Repository — status, reset, and describe `repo.status` returns a map of file paths to their status flags, `repo.reset` performs soft/mixed/hard resets, and `repo.describe` mimics `git describe`. ### Method - `Repository.status` - `Repository.statusFile(String path)` - `Repository.reset({required Oid oid, required GitReset resetType})` - `Repository.describe({GitDescribeStrategy? describeStrategy, int? abbreviatedSize, String? dirtySuffix})` - `Repository.aheadBehind({required Revspec local, required Revspec upstream})` ### Description These methods provide functionalities to inspect the current state of the working tree, reset changes to a specific commit, describe the repository's current state similar to `git describe`, and compare branches to determine ahead/behind counts. ### Request Example ```dart import 'package:libgit2dart/libgit2dart.dart'; final repo = Repository.open('/path/to/my-repo'); // Full working-tree status final statusMap = repo.status; // Single-file status final fileStatus = repo.statusFile('README.md'); // Hard reset to a specific commit repo.reset( oid: repo['abc1234'], resetType: GitReset.hard, ); // Soft reset, keeping staged changes repo.reset( oid: repo['HEAD~1'], resetType: GitReset.soft, ); // Describe current worktree final description = repo.describe( describeStrategy: GitDescribeStrategy.tags, abbreviatedSize: 7, dirtySuffix: '-dirty', ); // Ahead/behind counts between two commits final counts = repo.aheadBehind( local: repo['refs/heads/feature'], upstream: repo['refs/heads/main'], ); ``` ### Response #### Success Response - `repo.status`: A `Map>` where keys are file paths and values are sets of status flags. - `repo.statusFile`: A `Set` representing the status flags for a single file. - `repo.reset`: Returns `void` upon successful reset. - `repo.describe`: A `String` describing the repository state. - `repo.aheadBehind`: A `List` containing two elements: the number of commits the local branch is ahead of the upstream, and the number of commits it is behind. #### Response Example ```dart // For repo.status print(statusMap); // e.g., {'README.md': {GitStatus.indexModified}} // For repo.statusFile print(fileStatus); // => {GitStatus.wtModified} // For repo.describe print(description); // => 'v1.2.0-3-gabcdef1-dirty' // For repo.aheadBehind print('ahead: ${counts[0]}, behind: ${counts[1]}'); // => 'ahead: 3, behind: 1' ``` ``` -------------------------------- ### Manage Git Branches with libgit2dart Source: https://context7.com/skinnymind/libgit2dart/llms.txt Use Branch.lookup to find branches by name, Branch.create to make new ones, and methods like setUpstream, rename, and delete for management. Branches can be local or remote-tracking. ```dart import 'package:libgit2dart/libgit2dart.dart'; void main() { final repo = Repository.open('/path/to/my-repo'); // List all branches print(repo.branches.map((b) => b.name).toList()); // => ['main', 'feature/my-branch'] // Lookup a local branch final main = Branch.lookup(repo: repo, name: 'main'); print(main.isHead); // => true print(main.isCheckedOut); // => true print(main.target); // => Oid{sha: ...} // Lookup a remote-tracking branch final remote = Branch.lookup( repo: repo, name: 'origin/main', type: GitBranch.remote, ); print(remote.remoteName); // => 'origin' // Create a new branch at the current HEAD commit final headCommit = Commit.lookup(repo: repo, oid: repo.head.target); final feature = Branch.create( repo: repo, name: 'feature/my-branch', target: headCommit, ); print(feature.name); // => 'feature/my-branch' // Set upstream tracking feature.setUpstream('origin/main'); print(feature.upstreamName); // => 'refs/remotes/origin/main' // Rename a branch Branch.rename( repo: repo, oldName: 'feature/my-branch', newName: 'feature/renamed', ); // Delete a branch Branch.delete(repo: repo, name: 'feature/renamed'); repo.free(); } ``` -------------------------------- ### Generate and Inspect Diffs Source: https://github.com/skinnymind/libgit2dart/blob/master/README.md Explore various methods for generating diffs between different states of a repository, such as index to working directory, tree to index, and between two trees. Also shows how to parse patch files and inspect diff statistics. ```dart final diff = Diff.indexToWorkdir(repo: repo, index: repo.index); // => Diff final diff = Diff.treeToIndex(repo: repo, tree: tree, index: repo.index); // => Diff final diff = Diff.treeToWorkdir(repo: repo, tree: tree); // => Diff final diff = Diff.treeToWorkdirWithIndex(repo: repo, tree: tree); // => Diff final diff = Diff.treeToTree(repo: repo, oldTree: tree1, newTree: tree2); // => Diff final diff = Diff.indexToIndex(repo: repo, oldIndex: repo.index, newIndex: index); // => Diff final diff = Diff.parse(patch.text); // => Diff ``` ```dart diff.length; // => 3 diff.patch; // => 'diff --git a/modified_file b/modified_file ...' final stats = diff.stats; // => DiffStats stats.insertions; // => 69 stats.deletions; // => 420 stats.filesChanged; // => 1 final deltas = diff.deltas; // => [DiffDelta, DiffDelta, ...] final delta = deltas.first; // => DiffDelta delta.status; // => GitDelta.modified delta.oldFile; // => DiffFile delta.newFile; // => DiffFile ``` -------------------------------- ### Discover Repository Path Source: https://github.com/skinnymind/libgit2dart/blob/master/README.md Find the path to the '.git' directory of a repository by providing a path to a subdirectory within it. ```dart Repository.discover(startPath: '/repository/lib/src'); // => '/repository/.git/' ``` -------------------------------- ### Manage Git Branches Source: https://github.com/skinnymind/libgit2dart/blob/master/README.md Discover how to retrieve all branches, filter by local or remote, lookup specific branches, and perform create, rename, and delete operations. ```dart final branches = repo.branches; // => [Branch, Branch, ...] final local = repo.branchesLocal; // => [Branch, Branch, ...] final remote = repo.branchesRemote; // => [Branch, Branch, ...] final branch = Branch.lookup(repo: repo, name: 'master'); // => Branch branch.target; // => Oid branch.isHead; // => true branch.name; // => 'master' Branch.create(repo: repo, name: 'feature', target: commit); // => Branch Branch.rename(repo: repo, oldName: 'feature', newName: 'feature2'); Branch.delete(repo: repo, name: 'feature2'); ``` -------------------------------- ### Define Plugin Name and Create Shared Library Source: https://github.com/skinnymind/libgit2dart/blob/master/windows/CMakeLists.txt Defines the name for the plugin library and creates a shared library target. ```cmake set(PLUGIN_NAME "libgit2dart_plugin") add_library(${PLUGIN_NAME} SHARED "libgit2dart_plugin.cpp" ) apply_standard_settings(${PLUGIN_NAME}) set_target_properties(${PLUGIN_NAME} PROPERTIES CXX_VISIBILITY_PRESET hidden) target_compile_definitions(${PLUGIN_NAME} PRIVATE FLUTTER_PLUGIN_IMPL) ``` -------------------------------- ### Create Commit Source: https://github.com/skinnymind/libgit2dart/blob/master/README.md Create a new commit in the repository. This involves adding files to the index, writing the index to a tree, and then creating the commit with specified details like message, author, committer, tree, and parents. ```dart // Suppose you created a new file named 'new.txt' in your freshly initialized // repository and you want to commit it. final index = repo.index; // => Index index.add('new.txt'); index.write(); final tree = Tree.lookup(repo: repo, oid: index.writeTree()); // => Tree Commit.create( repo: repo, updateRef: 'refs/heads/master', message: 'initial commit\n', author: repo.defaultSignature, committer: repo.defaultSignature, tree: tree, parents: [], // empty list for initial commit, 1 parent for regular and 2+ for merge commits ); // => Oid ``` -------------------------------- ### Tree and TreeBuilder Source: https://context7.com/skinnymind/libgit2dart/llms.txt Represents directory snapshots and constructs them in memory. Allows lookup of entries by index or path and building new trees. ```APIDOC ## Tree and TreeBuilder — read and construct git trees `Tree` represents directory snapshots; `TreeBuilder` constructs them in memory. ```dart import 'package:libgit2dart/libgit2dart.dart'; void main() { final repo = Repository.open('/path/to/my-repo'); final commit = Commit.lookup(repo: repo, oid: repo.head.target); final tree = commit.tree; print(tree.length); // number of entries at root // Lookup entries by index or path final entry0 = tree[0]; final byPath = tree['lib/src/foo.dart']; print(entry0.name); // => 'README.md' print(entry0.filemode); // => GitFilemode.blob print(entry0.oid); // Build a new tree final index = repo.index; index.read(); final builder = TreeBuilder(repo: repo); // Add an entry sourced from the index builder.add( filename: 'hello.txt', oid: index['hello.txt'].oid, filemode: GitFilemode.blob, ); final newTreeOid = builder.write(); print(newTreeOid); // => Oid of the new tree object // Use in a commit final newTree = Tree.lookup(repo: repo, oid: newTreeOid); final sig = repo.defaultSignature; Commit.create( repo: repo, updateRef: 'HEAD', author: sig, committer: sig, message: 'chore: update tree\n', tree: newTree, parents: [commit], ); repo.free(); } ``` ``` -------------------------------- ### Tree and TreeEntry Lookup and Methods Source: https://github.com/skinnymind/libgit2dart/blob/master/README.md Details how to look up Tree and TreeEntry objects, access their properties, and use the TreeBuilder to create new trees. ```APIDOC ## Tree and TreeEntry ### Description Provides methods for looking up Tree and TreeEntry objects, accessing their properties, and manipulating trees. ### Lookup ```dart final tree = Tree.lookup(repo: repo, oid: repo['a8ae3dd']); // => Tree // Lookup single tree entry by index final entry = tree[0]; // => TreeEntry // Lookup single tree entry by path final entry = tree['some/file.txt']; // => TreeEntry // Lookup single tree entry by filename final entry = tree['file.txt']; // => TreeEntry ``` ### Getters ```dart tree.entries; // => [TreeEntry, TreeEntry, ...] tree.length; // => 3 tree.oid; // => Oid entry.oid; // => Oid entry.name // => 'file.txt' entry.filemode // => GitFilemode.blob ``` ### TreeBuilder ```dart final builder = TreeBuilder(repo: repo); // => TreeBuilder builder.add( filename: 'file.txt', oid: index['file.txt'].oid, filemode: GitFilemode.blob, ); final treeOid = builder.write(); // => Oid ``` ``` -------------------------------- ### Index - Staging Area Manipulation Source: https://context7.com/skinnymind/libgit2dart/llms.txt The `Index` class allows for direct manipulation of the Git staging area. You can add, remove, and inspect entries, detect conflicts, and write changes back to disk. ```APIDOC ## Index - Staging Area Manipulation `Index` exposes the full staging area: add, remove, iterate entries, detect conflicts, and write the tree. ### Methods - **`read()`**: Reloads the index from disk. - **`find(String path)`**: Checks if an entry exists at the given path. Returns `true` if found, `false` otherwise. - **`add(String path)`**: Stages a single file at the specified path. - **`addAll(List globPatterns)`**: Stages files matching the provided glob patterns. - **`remove(String path)`**: Unstages a file at the specified path. - **`write()`**: Writes the current index state to disk. - **`writeTree()`**: Writes the index to disk and returns the OID of the resulting tree. - **`cleanupConflict()`**: Cleans up merge conflicts in the index. ### Properties - **`length`**: Returns the number of entries in the index. - **`hasConflicts`**: Returns `true` if there are merge conflicts, `false` otherwise. - **`conflicts`**: Returns a map of conflicting entries. ### Index Entry Properties When iterating through the index or accessing an entry, the following properties are available: - **`path`**: The path of the entry. - **`oid`**: The Oid of the entry's content. - **`mode`**: The file mode of the entry (e.g., `GitFilemode.blob`). - **`stage`**: The stage of the entry (relevant for merge conflicts). ``` -------------------------------- ### Submodule Operations Source: https://context7.com/skinnymind/libgit2dart/llms.txt Wraps all `git submodule` operations, including adding, looking up, initializing, updating, and inspecting submodules. ```APIDOC ## Submodule Operations `Submodule` wraps all `git submodule` operations. ### List tracked submodule paths ```dart print(repo.submodules); // => ['vendor/some-lib'] ``` ### Add a new submodule ```dart final sub = Submodule.add( repo: repo, url: 'https://github.com/example/lib.git', path: 'vendor/example-lib', ); ``` ### Lookup existing submodule ```dart final existing = Submodule.lookup(repo: repo, name: 'vendor/some-lib'); print(existing.headOid); print(existing.indexOid); print(existing.workdirOid); ``` ### Initialize and update submodule ```dart Submodule.init(repo: repo, name: 'vendor/some-lib'); Submodule.update(repo: repo, name: 'vendor/some-lib', init: true); ``` ### Open the submodule as its own Repository ```dart final subRepo = existing.open(); print(subRepo.head.target); subRepo.free(); ``` ### Get submodule status flags ```dart final status = existing.status(); print(status); ``` ### Update URL and sync submodule config ```dart existing.url = 'https://github.com/example/lib-updated.git'; existing.sync(); ``` ``` -------------------------------- ### Create Blob from Disk Source: https://github.com/skinnymind/libgit2dart/blob/master/README.md Create a new blob object by providing the path to a file on disk. Returns the Oid of the created blob. ```dart // Create a new blob from the file at provided path final oid = Blob.createFromDisk(repo: repo, path: 'path/to/file.txt'); // => Oid ``` -------------------------------- ### Create and Inspect Blob Objects Source: https://context7.com/skinnymind/libgit2dart/llms.txt Create blobs from disk files or in-memory buffers. Inspect blob content, size, and binary status. Blobs store raw file content in the ODB. ```dart import 'package:libgit2dart/libgit2dart.dart'; void main() { final repo = Repository.open('/path/to/my-repo'); // Create a blob from a file on disk final blobOid = Blob.createFromDisk(repo: repo, path: '/tmp/my-file.txt'); print(blobOid); // Create a blob from an in-memory buffer final bufferOid = Blob.createFromBuffer( repo: repo, buffer: 'Hello, libgit2dart!\n', ); // Lookup a blob final blob = Blob.lookup(repo: repo, oid: bufferOid); print(blob.content); // => 'Hello, libgit2dart!\n' print(blob.size); // => 20 print(blob.isBinary); // => false // Filter content through .gitattributes (e.g. line-ending conversion) final filtered = blob.filter( asPath: 'README.md', flags: {GitBlobFilter.checkForBinary}, ); print(filtered); repo.free(); } ``` -------------------------------- ### Create Tree with TreeBuilder Source: https://github.com/skinnymind/libgit2dart/blob/master/README.md Use TreeBuilder to create a new tree by adding entries with filename, Oid, and filemode. The builder then writes the tree to the repository. ```dart final builder = TreeBuilder(repo: repo); // => TreeBuilder builder.add( filename: 'file.txt', oid: index['file.txt'].oid, filemode: GitFilemode.blob, ); final treeOid = builder.write(); // => Oid // Perform commit using that tree in arguments ... ``` -------------------------------- ### Manage Git Tags with libgit2dart Source: https://context7.com/skinnymind/libgit2dart/llms.txt Create annotated or lightweight tags using Tag.createAnnotated and Tag.createLightweight. Lookup, list, and delete tags using the Tag class methods. Annotated tags store additional metadata. ```dart import 'package:libgit2dart/libgit2dart.dart'; void main() { final repo = Repository.open('/path/to/my-repo'); final sig = repo.defaultSignature; final headOid = repo.head.target; // Create an annotated tag final tagOid = Tag.createAnnotated( repo: repo, tagName: 'v1.0.0', target: headOid, targetType: GitObject.commit, tagger: sig, message: 'Release version 1.0.0', ); print(tagOid); // => Oid{sha: ...} // Create a lightweight tag Tag.createLightweight( repo: repo, tagName: 'v1.0.0-lw', target: headOid, targetType: GitObject.commit, ); // List all tags print(repo.tags); // => ['v1.0.0', 'v1.0.0-lw'] // Lookup and inspect an annotated tag final tag = Tag.lookup(repo: repo, oid: tagOid); print(tag.name); // => 'v1.0.0' print(tag.message); // => 'Release version 1.0.0' print(tag.tagger); // => Signature{...} final commit = tag.target as Commit; print(commit.oid); // Delete a tag Tag.delete(repo: repo, name: 'v1.0.0-lw'); repo.free(); } ``` -------------------------------- ### Config Operations Source: https://context7.com/skinnymind/libgit2dart/llms.txt Provides access to read and write Git configuration files at various levels (repository, global, system). ```APIDOC ## Config Operations `Config` supports repository-level, global, system, and XDG config files with operator overloads for ergonomic access. ### Read values ```dart print(config['user.name'].value); print(config['user.email'].value); print(config['core.bare'].value); ``` ### Write values (bool, int, or String) ```dart config['user.name'] = 'Bob'; config['core.autocrlf'] = false; config['core.repositoryformatversion'] = 0; ``` ### Delete a variable ```dart config.delete('user.name'); ``` ### Iterate all entries at any level ```dart for (final entry in config) { print('${entry.name} = ${entry.value} [${entry.level}]'); } ``` ### Open a specific file ```dart final localConfig = Config.open('/path/to/my-repo/.git/config'); print(localConfig['remote.origin.url'].value); ``` ### Open the global config ```dart final globalConfig = Config.global(); ``` ### Multi-value variables ```dart final values = config.multivar(variable: 'remote.origin.fetch'); print(values); ``` ```