### Verify Installation Source: https://pub.dev/packages/libgit2dart Verify the installation of libgit2dart by printing the version of the bundled libgit2 library. ```APIDOC ## Verify Installation ### Description Prints the version of the libgit2 library that is bundled with the package. ### Code ```dart print(Libgit2.version); ``` ``` -------------------------------- ### Verify libgit2 Installation Source: https://pub.dev/packages/libgit2dart Print the version of the libgit2 library bundled with the package to verify installation. ```dart print(Libgit2.version); ``` -------------------------------- ### Setup libgit2 Library for Dart Applications Source: https://pub.dev/packages/libgit2dart Run this command to copy the prebuilt libgit2 library for your platform into the .dart_tool/libgit2// directory. This is required for Dart applications, not Flutter release builds. ```bash dart run libgit2dart:setup ``` -------------------------------- ### Manage Submodules Source: https://pub.dev/packages/libgit2dart Get submodule paths with `repo.submodules`. Look up submodules using `Submodule.lookup`, initialize with `Submodule.init`, update with `Submodule.update`, or add new ones with `Submodule.add`. ```dart // Get list with all tracked submodules paths repo.submodules; // => ['Submodule1', 'Submodule2']; // Lookup submodule Submodule.lookup(repo: repo, name: 'Submodule'); // => Submodule // Init and update Submodule.init(repo: repo, name: 'Submodule'); Submodule.update(repo: repo, name: 'Submodule'); // Add submodule Submodule.add(repo: repo, url: 'https://some.url', path: 'submodule'); // => Submodule ``` -------------------------------- ### libgit2dart pubspec.yaml Entry Source: https://pub.dev/packages/libgit2dart/install This is an example of how the libgit2dart dependency will appear in your pubspec.yaml file after running the add command. ```yaml dependencies: libgit2dart: ^1.2.2 ``` -------------------------------- ### Setup Git User Name and Email Source: https://pub.dev/packages/libgit2dart/example Configures the user's name and email for Git commits. Similar to `git config --add user.name` and `git config --add user.email`. ```dart void setupNameAndEmail(Repository repo) { final config = repo.config; config['user.name'] = 'User Name'; config['user.email'] = 'user@email.com'; stdout.writeln(' Setup user name and email:'); stdout.writeln('user.name=${config['user.name'].value}'); stdout.writeln('user.email=${config['user.email'].value}'); } ``` -------------------------------- ### Initialize and Access Git Index Source: https://pub.dev/packages/libgit2dart Initialize an Index object to access the Git staging area. Get the number of entries, read from disk, and write to disk. ```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(); ``` -------------------------------- ### Generate Bindings with Ffigen Source: https://pub.dev/packages/libgit2dart Use the `ffigen` Dart package to generate bindings. Adjust the compiler options, including include paths, to match your libgit2dart installation. ```bash dart run ffigen --compiler-opts "-I/path/to/libgit2dart/libgit2/headers/ -I/lib64/clang/12.0.1/include" ``` -------------------------------- ### Pull Changes from Remote in libgit2dart Source: https://pub.dev/packages/libgit2dart/example Pulls changes from a remote repository, performing a fetch and merge. This example demonstrates setting up a temporary remote, fetching, analyzing for merge, and committing the merge. It cleans up the temporary remote afterward. ```dart /// Pull changes from a remote repository. /// /// Similar to `git pull` void pullChanges(Repository repo) { // Prepare "origin" repository to pull from final originDir = setupRepo( Directory(path.join('test', 'assets', 'test_repo')), ); // Add remote const remoteName = 'origin'; final remote = Remote.create( repo: repo, name: remoteName, url: originDir.path, ); // Fetch changes remote.fetch(); // Merge changes final theirHead = Reference.lookup( repo: repo, name: 'refs/remotes/origin/master', ).target; final analysis = Merge.analysis(repo: repo, theirHead: theirHead); // In reality there should be more checks for analysis result (if we should // perform merge, or checkout if fast-forward is available, etc.) if (analysis.result.contains(GitMergeAnalysis.normal)) { final commit = AnnotatedCommit.lookup(repo: repo, oid: theirHead); Merge.commit(repo: repo, commit: commit); } // Make merge commit repo.index.write(); Commit.create( repo: repo, updateRef: 'HEAD', author: repo.defaultSignature, committer: repo.defaultSignature, message: 'Merge branch "master" of some remote\n', tree: Tree.lookup(repo: repo, oid: repo.index.writeTree()), parents: [ Commit.lookup(repo: repo, oid: repo.head.target), Commit.lookup(repo: repo, oid: theirHead), ], ); repo.stateCleanup(); // Remove "origin" repository originDir.deleteSync(recursive: true); } ``` -------------------------------- ### Traverse Commits with RevWalk Source: https://pub.dev/packages/libgit2dart Use RevWalk for fine-grained control over commit traversal. Set sorting, push starting points, and hide 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, ...] ``` -------------------------------- ### Traverse Commits with Repository Log Source: https://pub.dev/packages/libgit2dart Traverse commit history starting from a given Oid using the repository's log alias. ```dart // Traverse a set of commits starting at provided oid final commits = repo.log(oid: repo['821ed6e']); // => [Commit, Commit, ...] ``` -------------------------------- ### Merge Branches (Fast-Forward) Source: https://pub.dev/packages/libgit2dart/example Performs a fast-forward merge of a specified branch into the current branch. This example demonstrates a simple merge scenario. Requires a Repository object. ```dart void mergeBranches(Repository repo) { // Making changes on 'new-branch' File(path.join(repo.workdir, 'new_branch_file.txt')).createSync(); // Committing on 'new-branch' final signature = repo.defaultSignature; repo.index.write(); final newBranchOid = Commit.create( repo: repo, updateRef: 'HEAD', author: signature, committer: signature, message: 'commit on new-branch\n', tree: Tree.lookup(repo: repo, oid: repo.index.writeTree()), parents: [Commit.lookup(repo: repo, oid: repo.head.target)], ); // Switching to 'master' Checkout.reference(repo: repo, name: 'refs/heads/master'); repo.setHead('refs/heads/master'); // Merging commit into HEAD and writing results into the working directory. // Repository is put into a merging state. Merge.commit( repo: repo, commit: AnnotatedCommit.lookup(repo: repo, oid: newBranchOid), ); } ``` -------------------------------- ### Access Repository State and HEAD Source: https://pub.dev/packages/libgit2dart Retrieve boolean state values like `isBare`, `isEmpty`, and access the repository's HEAD reference. From the HEAD reference, you can get its name, target Oid, and SHA. ```dart // Boolean repository state values repo.isBare; // => false repo.isEmpty; // => true repo.isHeadDetached; // => false repo.isBranchUnborn; // => false repo.isWorktree; // => false // Path getters repo.path; // => 'path/to/repository/.git/' repo.workdir; // => 'path/to/repository/' // 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' ``` -------------------------------- ### Iterate and Access Index Entries Source: https://pub.dev/packages/libgit2dart Iterate over index entries to access their paths. Get a specific entry using its filename. ```dart // 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 ``` -------------------------------- ### Push Changes to Remote in libgit2dart Source: https://pub.dev/packages/libgit2dart/example Pushes local commits to a remote repository, similar to `git push `. This example sets up a temporary bare repository, adds a push refspec, performs the push, and then cleans up the temporary repository. ```dart /// Push changes to a remote repository. /// /// Similar to `git push bare master` void pushChanges(Repository repo) { // Prepare bare repository to push to final bareDir = setupRepo( Directory(path.join('test', 'assets', 'empty_bare.git')), ); // Add remote const remoteName = 'bare'; final url = bareDir.path; Remote.create(repo: repo, name: remoteName, url: url); Remote.addPush(repo: repo, remote: remoteName, refspec: 'refs/heads/master'); // Push changes final remote = Remote.lookup(repo: repo, name: remoteName); remote.push(); // Remove bare repository bareDir.deleteSync(recursive: true); } ``` -------------------------------- ### Repository Instantiation Source: https://pub.dev/packages/libgit2dart Demonstrates how to instantiate a Repository object by opening an existing repository, creating a new one, or cloning a remote repository. ```APIDOC ## Repository Instantiation ### Description Provides methods to open an existing Git repository, create a new one, or clone a remote 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 the given URL to the specified local path. ### Example ```dart // Open an existing repository final repo = Repository.open('path/to/repository'); // Create a new repository final newRepo = Repository.init(path: 'path/to/folder', bare: true); // Clone a repository final clonedRepo = Repository.clone( url: 'https://some.url/', localPath: 'path/to/clone/into', ); ``` ``` -------------------------------- ### Initialize New Bare Repository Source: https://pub.dev/packages/libgit2dart Create a new Git repository at the specified path. Set `bare` to true for a bare repository. ```dart final repo = Repository.init(path: 'path/to/folder', bare: true); // => Repository ``` -------------------------------- ### Open Existing Repository Source: https://pub.dev/packages/libgit2dart Instantiate a Repository object by providing the path to an existing Git repository. ```dart final repo = Repository.open('path/to/repository'); // => Repository ``` -------------------------------- ### Initialize Repository with libgit2dart Source: https://pub.dev/packages/libgit2dart/example Initializes an empty Git repository in a specified directory. Similar to `git init`. ```dart Repository initRepo(String path) { final repo = Repository.init(path: path); stdout.writeln('Initialized empty Git repository in ${repo.path}'); return repo; } ``` -------------------------------- ### Oid Instantiation Source: https://pub.dev/packages/libgit2dart Demonstrates how to instantiate an Oid object from a SHA-1 string, which is required for looking up Git objects. ```APIDOC ## Oid Instantiation ### Description Instantiate an Oid object from a SHA-1 string. The SHA-1 string can be of any length between 4 and 40 characters. ### 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'); ``` ``` -------------------------------- ### Clean and Re-setup libgit2 Library Source: https://pub.dev/packages/libgit2dart If you upgrade the libgit2dart package, run these commands to clean the old library and set up the latest version. ```bash dart run libgit2dart:setup clean dart run libgit2dart:setup ``` -------------------------------- ### Manage Git Configuration Files Source: https://pub.dev/packages/libgit2dart Open and manipulate Git configuration files, either from a specified path or directly from a repository. Read, set, and delete configuration variables. ```dart // Open config file at provided path final config = Config.open('path/to/config'); // => Config // Open configuration file for repository final config = repo.config; // => Config // Get value of config variable config['user.name'].value; // => 'Some Name' // Set value of config variable config['user.name'] = 'Another Name'; // Delete variable from the config config.delete('user.name'); ``` -------------------------------- ### Tag Creation and Lookup Source: https://pub.dev/packages/libgit2dart Explains how to create annotated and lightweight tags, look up existing tags, and retrieve a list of all tag names in the repository. ```APIDOC ## Tag Creation and Lookup ### Description Create annotated and lightweight tags, look up existing tags, and retrieve a list of all tag names in the repository. ### Usage ```dart // Create annotated tag 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 final lightweight = Tag.createLightweight( repo: repo, tagName: 'v0.1', target: repo['821ed6e'], targetType: GitObject.commit, ); // => Oid // 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' ``` ``` -------------------------------- ### TreeBuilder Usage Source: https://pub.dev/packages/libgit2dart Demonstrates how to use the TreeBuilder to create new trees by adding entries and writing the tree to the repository. ```APIDOC ## TreeBuilder Usage ### Description Use TreeBuilder to create new trees by adding entries and writing the tree to the repository. ### Usage ```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 // ... ``` ``` -------------------------------- ### Run Tests and Generate Coverage Source: https://pub.dev/packages/libgit2dart Execute the coverage script to run all tests and generate a coverage report. Open the generated HTML report in a browser to view results. ```bash $ ./coverage.sh $ open coverage/index.html ``` -------------------------------- ### Create Symlinks for libpcre Source: https://pub.dev/packages/libgit2dart On non-Debian based Linux distributions, create symlinks for libpcre.so.3 if you encounter 'Failed to load dynamic library' errors. ```bash sudo ln -s /usr/lib64/libpcre.so /usr/lib64/libpcre.so.3 sudo ln -s /usr/lib64/libpcreposix.so /usr/lib64/libpcreposix.so.3 ``` -------------------------------- ### Perform Different Types of Checkout Source: https://pub.dev/packages/libgit2dart Use Checkout.head, Checkout.index, Checkout.reference, or Checkout.commit to update files in the working directory. Strategies like force checkout or checking out specific paths are also supported. ```dart Checkout.head(repo: repo); // Update files in the working directory to match the content of the index Checkout.index(repo: repo); // Update files in the working directory to match the content of the tree // pointed at by the reference target Checkout.reference(repo: repo, name: 'refs/heads/master'); // Update files in the working directory to match the content of the tree // pointed at by the commit Checkout.commit(repo: repo, commit: commit); // Perform checkout using various strategies Checkout.head(repo: repo, strategy: {GitCheckout.force}); // Checkout only required files Checkout.head(repo: repo, paths: ['some/file.txt']); ``` -------------------------------- ### Blob Creation and Lookup Source: https://pub.dev/packages/libgit2dart Details how to create blobs from files on disk, look up existing blobs by Oid, and access blob properties like content and size. ```APIDOC ## Blob Creation and Lookup ### Description Create blobs from files on disk, look up existing blobs by Oid, and access blob properties. ### Usage ```dart // Create a new blob from the file at provided path final oid = Blob.createFromDisk(repo: repo, path: 'path/to/file.txt'); // => Oid // Lookup blob final blob = Blob.lookup(repo: repo, oid: repo['e69de29']); // => Blob blob.oid; // => Oid blob.content; // => 'content of the file' blob.size; // => 19 ``` ``` -------------------------------- ### Config files Source: https://pub.dev/packages/libgit2dart Manage Git configuration files. ```APIDOC ## Config files ### Description APIs for opening, reading, setting, and deleting configuration variables in Git config files. ### Methods - `Config.open(path: 'path/to/config')`: Open a config file at a given path. - `repo.config`: Open the configuration file for the repository. - `config.delete(variable_name)`: Delete a configuration variable. ### Properties - `config['variable.name'].value`: Get the value of a configuration variable. - `config['variable.name'] = 'new_value'`: Set the value of a configuration variable. ``` -------------------------------- ### View Changes Before Committing Source: https://pub.dev/packages/libgit2dart/example Shows the differences between the index and the working directory. Useful for staging changes. Requires a Repository object. ```dart void viewChanges(Repository repo) { final diff = Diff.indexToWorkdir(repo: repo, index: repo.index); stdout.writeln(' ${diff.patch}'); } ``` -------------------------------- ### Manage Stashes Source: https://pub.dev/packages/libgit2dart Access stashes via `repo.stashes`. Create new stashes with `Stash.create`, apply with `Stash.apply` (optionally with specific paths), drop with `Stash.drop`, or pop with `Stash.pop`. ```dart // Get the list of all stashed states (first being the most recent) repo.stashes; // => [Stash, Stash, ...] // Save local modifications to a new stash Stash.create(repo: repo, stasher: signature, message: 'WIP'); // => Oid // Apply stash (defaults to last saved if index is not provided) Stash.apply(repo: repo); // Apply only specific paths from stash Stash.apply(repo: repo, paths: ['file.txt']); // Drop stash (defaults to last saved if index is not provided) Stash.drop(repo: repo); // Pop stash (apply and drop if successful, defaults to last saved // if index is not provided) Stash.pop(repo: repo); ``` -------------------------------- ### Create and Switch to New Branch Source: https://pub.dev/packages/libgit2dart/example Creates a new local branch pointing to the current commit and checks it out. Requires a Repository object. ```dart void createAndSwitchToBranch(Repository repo) { final branch = Branch.create( repo: repo, name: 'new-branch', target: Commit.lookup(repo: repo, oid: repo.head.target), ); final fullName = 'refs/heads/${branch.name}'; Checkout.reference(repo: repo, name: fullName); repo.setHead(fullName); stdout.writeln('Switched to a new branch "${repo.head.name}"'); } ``` -------------------------------- ### Tree and TreeEntry Lookup and Getters Source: https://pub.dev/packages/libgit2dart Illustrates how to look up Tree and TreeEntry objects and access their properties and methods, including iterating through entries. ```APIDOC ## Tree and TreeEntry Lookup and Getters ### Description Look up Tree and TreeEntry objects and access their properties and methods. ### Usage ```dart final tree = Tree.lookup(repo: repo, oid: repo['a8ae3dd']); // => Tree tree.entries; // => [TreeEntry, TreeEntry, ...] tree.length; // => 3 tree.oid; // => Oid // You can lookup single tree entry in the tree with index final entry = tree[0]; // => TreeEntry // You can lookup single tree entry in the tree with path to file final entry = tree['some/file.txt']; // => TreeEntry // Or you can lookup single tree entry in the tree with filename final entry = tree['file.txt']; // => TreeEntry entry.oid; // => Oid entry.name // => 'file.txt' entry.filemode // => GitFilemode.blob ``` ``` -------------------------------- ### Create and Lookup Blob Source: https://pub.dev/packages/libgit2dart Blobs can be created from disk paths or looked up by Oid. Access blob content, size, and Oid. ```dart // Create a new blob from the file at provided path final oid = Blob.createFromDisk(repo: repo, path: 'path/to/file.txt'); // => Oid // Lookup blob final blob = Blob.lookup(repo: repo, oid: repo['e69de29']); // => Blob blob.oid; // => Oid blob.content; // => 'content of the file' blob.size; // => 19 ``` -------------------------------- ### Discover Repository Path Source: https://pub.dev/packages/libgit2dart 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/' ``` -------------------------------- ### References and RefLog Source: https://pub.dev/packages/libgit2dart Manage Git references and access their reflogs. ```APIDOC ## References and RefLog ### Description Operations for retrieving, looking up, creating, updating, renaming, and deleting Git references. Also includes access to the reflog for a reference. ### Methods - `repo.references`: Get names of all references in the repository. - `Reference.lookup(repo: repo, name: 'ref_name')`: Look up a specific reference. - `Reference.create(repo: repo, name: 'ref_name', target: oid)`: Create a new reference. - `ref.setTarget(oid)`: Update the target of an existing reference. - `Reference.rename(repo: repo, oldName: 'old_name', newName: 'new_name')`: Rename a reference. - `Reference.delete(repo: repo, name: 'ref_name')`: Delete a reference. - `ref.log`: Access the reflog for a reference. ### Properties - `ref.type`: Type of the reference (e.g., `ReferenceType.direct`). - `ref.target`: The OID the reference points to. - `ref.name`: The full name of the reference. - `reflog.first`: Get the first entry in the reflog. - `entry.message`: The log message for a reflog entry. - `entry.committer`: The signature of the committer for a reflog entry. ``` -------------------------------- ### Manage Worktrees Source: https://pub.dev/packages/libgit2dart Retrieve worktree names with `repo.worktrees`. Look up existing worktrees using `Worktree.lookup` or create new ones with `Worktree.create`. Worktrees can be locked, unlocked, and pruned. ```dart // Get list of names of linked worktrees repo.worktrees; // => ['worktree1', 'worktree2']; // Lookup existing worktree Worktree.lookup(repo: repo, name: 'worktree1'); // => Worktree // Create new worktree final worktree = Worktree.create( repo: repo, name: 'worktree3', path: '/worktree3/path/', ); // => Worktree // Get name of worktree worktree.name; // => 'worktree3' // Get path for the worktree worktree.path; // => '/worktree3/path/' // Lock and unlock worktree worktree.lock(); worktree.unlock(); // Prune the worktree (remove the git data structures on disk) worktree.prune(); ``` -------------------------------- ### List All Branches Source: https://pub.dev/packages/libgit2dart/example Prints a list of all local and remote branches, indicating the current branch with an asterisk. Requires a Repository object. ```dart void listBranches(Repository repo) { stdout.writeln(); final branches = repo.branches; for (final branch in branches) { stdout.writeln( repo.head.shorthand == branch.name ? '* ${branch.name}' : ' ${branch.name}', ); } } ``` -------------------------------- ### Diff Source: https://pub.dev/packages/libgit2dart Calculate and inspect differences between various Git states. ```APIDOC ## Diff ### Description Methods for calculating differences between the index, working directory, and trees. Also includes parsing diffs from patch files. ### Methods - `Diff.indexToWorkdir(repo: repo, index: repo.index)`: Diff between index and working directory. - `Diff.treeToIndex(repo: repo, tree: tree, index: repo.index)`: Diff between a tree and the index. - `Diff.treeToWorkdir(repo: repo, tree: tree)`: Diff between a tree and the working directory. - `Diff.treeToWorkdirWithIndex(repo: repo, tree: tree)`: Diff between a tree and the working directory with index. - `Diff.treeToTree(repo: repo, oldTree: tree1, newTree: tree2)`: Diff between two trees. - `Diff.indexToIndex(repo: repo, oldIndex: repo.index, newIndex: index)`: Diff between two index objects. - `Diff.parse(patch_text)`: Parse a diff from a patch file string. ### Properties - `diff.length`: Number of diff records. - `diff.patch`: The full patch content as a string. - `diff.stats`: The `DiffStats` object containing insertion/deletion counts and files changed. - `diff.deltas`: A list of `DiffDelta` objects representing file changes. ``` -------------------------------- ### Create Tree with TreeBuilder Source: https://pub.dev/packages/libgit2dart Use TreeBuilder to construct and write new trees. Add entries with filename, Oid, and filemode. ```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 and IndexEntry Manipulation Source: https://pub.dev/packages/libgit2dart Covers methods for inspecting and manipulating the Git index (staging area), including reading, writing, iterating, adding, and removing entries. ```APIDOC ## Index and IndexEntry Manipulation ### Description Inspect and manipulate the Git index (staging area). This includes initializing the Index object, getting its length, reading from and writing to disk, iterating over entries, and staging or unstaging files. ### Usage ```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'); ``` ``` -------------------------------- ### Create and Lookup Tag Source: https://pub.dev/packages/libgit2dart Create annotated or lightweight tags with a name, target, and target type. Tags can be looked up by Oid, and repository tags can be listed. ```dart // Create annotated tag 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 final lightweight = Tag.createLightweight( repo: repo, tagName: 'v0.1', target: repo['821ed6e'], targetType: GitObject.commit, ); // => Oid // 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' ``` -------------------------------- ### Repository Discovery Source: https://pub.dev/packages/libgit2dart Discover the path to the '.git' directory of a repository by providing a path to a subdirectory within it. ```APIDOC ## Repository Discovery ### Description Finds the path to the '.git' directory of a repository, starting the search from a given subdirectory path. ### Method `Repository.discover({required String startPath})` ### Parameters - **startPath** (String) - Required - The path to a subdirectory within the repository. ### Returns - String - The path to the '.git' directory. ### Example ```dart final gitDirPath = Repository.discover(startPath: '/repository/lib/src'); // Returns '/repository/.git/' ``` ``` -------------------------------- ### Manage Git References Source: https://pub.dev/packages/libgit2dart Perform operations on Git references such as listing, looking up, creating, updating, renaming, and deleting them. Access the reflog for a reference to view its history. ```dart // Get names of all of the references that can be found in repository final refs = repo.references; // => ['refs/heads/master', 'refs/tags/v0.1', ...] // Lookup reference final ref = Reference.lookup(repo: repo, name: 'refs/heads/master'); // => Reference ref.type; // => ReferenceType.direct ref.target; // => Oid ref.name; // => 'refs/heads/master' // Create reference final ref = Reference.create( repo: repo, name: 'refs/heads/feature', target: repo['821ed6e'], ); // => Reference // Update reference ref.setTarget(repo['c68ff54']); // Rename reference Reference.rename(repo: repo, oldName: 'refs/heads/feature', newName: 'refs/heads/feature2'); // Delete reference Reference.delete(repo: repo, name: 'refs/heads/feature2'); // Access the reflog final reflog = ref.log; // => RefLog final entry = reflog.first; // RefLogEntry entry.message; // => 'commit (initial): init' entry.committer; // => Signature ``` -------------------------------- ### Stage and Unstage Files in Index Source: https://pub.dev/packages/libgit2dart Stage new files or update existing entries in the index using their path. Unstage entries by their path. ```dart // 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'); ``` -------------------------------- ### Instantiate Oid from SHA-1 Source: https://pub.dev/packages/libgit2dart Oid objects can be instantiated from a SHA-1 string using either a repository alias or the Oid.fromSHA constructor. The SHA-1 string can be any length between 4 and 40 characters. ```dart final oid = repo['821ed6e']; final oid = Oid.fromSHA(repo: repo, sha: '821ed6e'); ``` -------------------------------- ### Activate Coverage Tool Source: https://pub.dev/packages/libgit2dart Activate the coverage tool globally. This is a prerequisite for running tests and generating coverage reports. ```bash $ dart pub global activate coverage ``` -------------------------------- ### Accessing Repository Information Source: https://pub.dev/packages/libgit2dart Access various states and properties of a repository, including its path, HEAD reference, and objects. ```APIDOC ## Accessing Repository Information ### Description Retrieve boolean states, path information, the HEAD reference, and lookup objects within a repository. ### Properties - `isBare` (bool): Indicates if the repository is bare. - `isEmpty` (bool): Indicates if the repository is empty. - `isHeadDetached` (bool): Indicates if the HEAD is detached. - `isBranchUnborn` (bool): Indicates if the current branch is unborn. - `isWorktree` (bool): Indicates if the repository is a worktree. - `path` (String): The path to the repository's `.git` directory. - `workdir` (String): The working directory path of the repository. ### Methods - `head` (Reference): Returns the reference pointed to by HEAD. - `[String oid]` (Oid): Looks up an object by its SHA-1 OID. ### Example ```dart final repo = Repository.open('path/to/repository'); print(repo.isBare); print(repo.path); final ref = repo.head; print(ref.name); print(ref.target.sha); final oid = repo['821ed6e80627b8769d170a293862f9fc60825226']; final commit = Commit.lookup(repo: repo, oid: oid); print(commit.message); ``` ``` -------------------------------- ### Create a New Commit Source: https://pub.dev/packages/libgit2dart Stages changes in the index, writes the index to a tree, and then creates a new commit with the specified message, author, committer, tree, and parent commits. ```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 ``` -------------------------------- ### Writing to Repository Source: https://pub.dev/packages/libgit2dart Perform write operations on the repository, such as adding files to the index, writing the index, and creating commits. ```APIDOC ## Writing to Repository ### Description Demonstrates how to modify the repository by staging changes, writing the index, and creating new commits. ### Methods #### `repo.index` (Index) Gets the repository's index. #### `index.add(String filePath)` Adds a file to the index. #### `index.write()` Writes the changes in the index to the repository. #### `Tree.lookup({required Repository repo, required Oid oid})` Looks up a tree object by its OID. #### `Commit.create({...})` Creates a new commit with the specified details. ### Example ```dart final repo = Repository.open('path/to/repository'); final index = repo.index; // Stage a new file index.add('new.txt'); index.write(); // Create a tree from the index final tree = Tree.lookup(repo: repo, oid: index.writeTree()); // Create a commit 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 ); ``` ``` -------------------------------- ### Inspect Submodule Object Source: https://pub.dev/packages/libgit2dart Access submodule properties like name, path, and URL. Update the URL and synchronize changes using `submodule.url = '...'` and `submodule.sync()`. ```dart // Get name of the submodule submodule.name; // => 'Submodule' // Get path to the submodule submodule.path; // => 'Submodule' // Get URL for the submodule submodule.url; // => 'https://some.url' // Set URL for the submodule in the configuration submodule.url = 'https://updated.url'; submodule.sync(); ``` -------------------------------- ### Submodule Management Source: https://pub.dev/packages/libgit2dart Manage submodules within a repository, including retrieving lists, looking up, initializing, updating, and adding submodules. Also covers inspecting and modifying submodule properties. ```APIDOC ## Submodule Management ### Description Some API methods for submodule management. ### Methods - `repo.submodules` (getter) - `Submodule.lookup(repo: repo, name: String) - `Submodule.init(repo: repo, name: String) - `Submodule.update(repo: repo, name: String) - `Submodule.add(repo: repo, url: String, path: String) - `submodule.name` (getter) - `submodule.path` (getter) - `submodule.url` (getter/setter) - `submodule.sync() ### Examples ```dart // Get list with all tracked submodules paths repo.submodules; // => ['Submodule1', 'Submodule2']; // Lookup submodule Submodule.lookup(repo: repo, name: 'Submodule'); // => Submodule // Init and update Submodule.init(repo: repo, name: 'Submodule'); Submodule.update(repo: repo, name: 'Submodule'); // Add submodule Submodule.add(repo: repo, url: 'https://some.url', path: 'submodule'); // => Submodule // Get name of the submodule submodule.name; // => 'Submodule' // Get path to the submodule submodule.path; // => 'Submodule' // Get URL for the submodule submodule.url; // => 'https://some.url' // Set URL for the submodule in the configuration submodule.url = 'https://updated.url'; submodule.sync(); ``` ``` -------------------------------- ### Stage Untracked File with libgit2dart Source: https://pub.dev/packages/libgit2dart/example Stages a new, untracked file for the next commit. Similar to `git add `. ```dart void stageUntracked({required Repository repo, required String filePath}) { final index = repo.index; index.add(filePath); index.write(); stdout.writeln(' Staged previously untracked file $filePath'); } ``` -------------------------------- ### Patch Source: https://pub.dev/packages/libgit2dart Generate and inspect Git patches. ```APIDOC ## Patch ### Description APIs for generating patches from blobs or diffs, and for inspecting patch content. ### Methods - `Patch.fromBlobs(oldBlob: blob, newBlob: blob, newBlobPath: 'path')`: Generate a patch from two blobs. - `Patch.fromDiff(diff: diff, index: diff_index)`: Generate a patch from a diff object at a specific index. ### Properties - `patch.text`: The content of the patch as a diff text string. - `patch.hunks`: A list of `DiffHunk` objects within the patch. ``` -------------------------------- ### Lookup and Access Tree Source: https://pub.dev/packages/libgit2dart Trees can be looked up using an Oid. Access entries, length, and oid. Individual entries can be accessed by index or path. ```dart final tree = Tree.lookup(repo: repo, oid: repo['a8ae3dd']); // => Tree tree.entries; // => [TreeEntry, TreeEntry, ...] tree.length; // => 3 tree.oid; // => Oid // You can lookup single tree entry in the tree with index final entry = tree[0]; // => TreeEntry // You can lookup single tree entry in the tree with path to file final entry = tree['some/file.txt']; // => TreeEntry // Or you can lookup single tree entry in the tree with filename final entry = tree['file.txt']; // => TreeEntry entry.oid; // => Oid entry.name // => 'file.txt' entry.filemode // => GitFilemode.blob ``` -------------------------------- ### Generate Git Patch Source: https://pub.dev/packages/libgit2dart Create a Git patch from differences between two blobs or from a specific entry within a diff list. Inspect the generated patch for its text content, size, and hunks. ```dart // Patch from difference between two blobs final patch = Patch.fromBlobs( oldBlob: null, // empty blob newBlob: blob, newBlobPath: 'file.txt', ); // => Patch // Patch from entry in the diff list at provided index position final patch = Patch.fromDiff(diff: diff, index: 0); // => Patch ``` ```dart // Get the content of a patch as a single diff text patch.text; // => 'diff --git a/modified_file b/modified_file ...' // Get the size of a patch diff data in bytes patch.size(); // => 1337 // Get the list of hunks in a patch patch.hunks; // => [DiffHunk, DiffHunk, ...] ``` -------------------------------- ### Checkout Operations Source: https://pub.dev/packages/libgit2dart Provides methods to perform various types of checkouts, including updating files to match HEAD, index, a specific reference, or a commit. It also supports checkout strategies and path filtering. ```APIDOC ## Checkout Operations ### Description Perform different types of checkout. ### Methods - `Checkout.head(repo: repo, strategy: GitCheckout?, paths: List?) - `Checkout.index(repo: repo) - `Checkout.reference(repo: repo, name: String) - `Checkout.commit(repo: repo, commit: Commit) ### Examples ```dart // Update files in the index and the working directory to match the content of the commit pointed at by HEAD Checkout.head(repo: repo); // Update files in the working directory to match the content of the index Checkout.index(repo: repo); // Update files in the working directory to match the content of the tree pointed at by the reference target Checkout.reference(repo: repo, name: 'refs/heads/master'); // Update files in the working directory to match the content of the tree pointed at by the commit Checkout.commit(repo: repo, commit: commit); // Perform checkout using various strategies Checkout.head(repo: repo, strategy: GitCheckout.force); // Checkout only required files Checkout.head(repo: repo, paths: ['some/file.txt']); ``` ``` -------------------------------- ### Clone Remote Repository Source: https://pub.dev/packages/libgit2dart Clone an existing Git repository from a URL to a local path. ```dart final repo = Repository.clone( url: 'https://some.url/', localPath: 'path/to/clone/into', ); // => Repository ``` -------------------------------- ### Commit Traversal Source: https://pub.dev/packages/libgit2dart Explains two methods for traversing commits: using the repository's log alias and using the RevWalk class for more control over the traversal process. ```APIDOC ## Commit Traversal ### Description Traverse a set of commits starting at a provided Oid. This can be done through the Repository object alias or by using the RevWalk class for finer control. ### Usage ```dart // Traverse a set of commits starting at provided oid final commits = repo.log(oid: repo['821ed6e']); // => [Commit, Commit, ...] // 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, ...] ``` ``` -------------------------------- ### Stage and Commit Changes in libgit2dart Source: https://pub.dev/packages/libgit2dart/example Stages all changed files and creates a new commit on the current branch. Ensure the repository state is cleaned up afterward. ```dart // Staging merged files. repo.index.addAll(repo.status.keys.toList()); // Committing on 'master' repo.index.write(); final parent = Commit.lookup(repo: repo, oid: repo.head.target); final masterOid = Commit.create( repo: repo, updateRef: 'HEAD', author: signature, committer: signature, message: 'commit on new-branch\n', tree: Tree.lookup(repo: repo, oid: repo.index.writeTree()), parents: [parent], ); // Clearing up merging state of repository after commit is done repo.stateCleanup(); stdout.writeln( '\nUpdating ${parent.oid.sha.substring(0, 7)}..' '${masterOid.sha.substring(0, 7)}', ); ``` -------------------------------- ### Inspect Git Diff Object Source: https://pub.dev/packages/libgit2dart Analyze a Diff object to retrieve its size, patch content, statistics (insertions, deletions, files changed), and a list of file deltas with their status and old/new file information. ```dart // Get the number of diff records diff.length; // => 3 // Get the patch diff.patch; // => 'diff --git a/modified_file b/modified_file ...' // Get the DiffStats object of the diff final stats = diff.stats; // => DiffStats stats.insertions; // => 69 stats.deletions; // => 420 stats.filesChanged; // => 1 // Get the list of DiffDelta's containing file pairs with and old and new revisions final deltas = diff.deltas; // => [DiffDelta, DiffDelta, ...] final delta = deltas.first; // => DiffDelta delta.status; // => GitDelta.modified delta.oldFile; // => DiffFile delta.newFile; // => DiffFile ``` -------------------------------- ### View Commit Metadata Source: https://pub.dev/packages/libgit2dart/example Displays author, date, and message of a commit. Requires a Repository object. ```dart void viewCommit(Repository repo) { final commit = Commit.lookup(repo: repo, oid: repo.head.target); stdout.writeln(' commit ${commit.oid.sha}'); stdout.writeln('Author: ${commit.author.name} <${commit.author.email}>'); stdout.writeln( 'Date: ${DateTime.fromMillisecondsSinceEpoch(commit.time * 1000)} ' '${commit.timeOffset}', ); stdout.writeln(' ${commit.message}'); final diff = Diff.treeToTree( repo: repo, oldTree: null, newTree: commit.tree, ); stdout.writeln(' ${diff.patch}'); } ``` -------------------------------- ### Generate Git Diffs Source: https://pub.dev/packages/libgit2dart Calculate differences between various Git states, including index to working directory, tree to index, tree to working directory, and between two tree objects. Also supports parsing patch files. ```dart // Diff between index (staging area) and current working directory final diff = Diff.indexToWorkdir(repo: repo, index: repo.index); // => Diff // Diff between tree and index (staging area) final diff = Diff.treeToIndex(repo: repo, tree: tree, index: repo.index); // => Diff // Diff between tree and current working directory final diff = Diff.treeToWorkdir(repo: repo, tree: tree); // => Diff // Diff between tree and current working directory with index final diff = Diff.treeToWorkdirWithIndex(repo: repo, tree: tree); // => Diff // Diff between two tree objects final diff = Diff.treeToTree(repo: repo, oldTree: tree1, newTree: tree2); // => Diff // Diff between two index objects final diff = Diff.indexToIndex(repo: repo, oldIndex: repo.index, newIndex: index); // => Diff // Read the contents of a git patch file final diff = Diff.parse(patch.text); // => Diff ```