git (egit v0.2.0)
View SourceErlang NIF bindings for libgit2.
This module provides comprehensive git repository operations without requiring
the external git executable. Operations range from basic repo management
(init, clone, open) to advanced functionality (blame, cherry-pick, reflog).
Common Use Cases
Repository Operations
Repo = git:open("/path/to/repo"),
git:status(Repo),
git:fetch(Repo),
git:pull(Repo),
git:push(Repo)Commit Operations
git:add(Repo, "src/*.erl"),
git:commit(Repo, "Update implementation"),
git:rev_parse(Repo, "HEAD~5")Branch Management
git:branch_create(Repo, "feature/my-feature"),
git:checkout(Repo, "feature/my-feature"),
git:list_branches(Repo, [local])Code Analysis
git:blame(Repo, "src/main.erl"),
git:describe(Repo, "HEAD"),
git:reflog(Repo, "main")
Summary
Types
Branch creation options
Configuration source. If the value is an atom, then
List branch option.
List index option.
Status function options
Tag creation options
Functions
Add files matching PathSpecs to index. See add/3.
Add files matching PathSpecs to index with options.
Add all pending changes (equivalent to git add .). See add/2 and add/3.
Show file change history by line. Returns a list of {LineNumber, {Author, Email}, CommitOID, Time} tuples.
Show file change history by line with options. Opts is a list of
Create a branch
See: git:branch_create/3.
Create a branch Example
Delete a branch
Rename a branch
See: branch_rename/4.
Rename a branch
Same as cat_file(Repo, Rev, []). See cat_file/3.
Provide content or type and size information for repository objects. Example
Same as checkout(Repo, Revision, []).
Check out a revision or branch.
Apply a single commit to current branch. Returns ok on success, {conflict, Conflicts} on merge conflict, or {error, Reason} on failure.
Clone a remote repository to the local path
Commit staged changes to the repository. Returns {ok, OID} where OID is the new commit hash, or {ok, nil} if there are no staged changes.
Lookup commit details identified by OID.
Get git configuration value Example
Set git configuration value Example
Describe working tree state. Returns a human-readable description of the most recent tag and commits. Example: "v1.0.0-5-gabcd123"
Describe working tree state with options. Opts is a list of
Compare two revisions and return list of differences.
See: diff/4.
Compare two revisions and return list of differences. Returns list of {Path, Status, StatusCode, Similarity} tuples. Status values: "added", "deleted", "modified", "renamed", "copied", "typechange"
Fetch from origin
Fetch from given remote (e.g. origin).
Init a repository.
See: init/2.
Init a repository.
If Opts' list containsbare', a Git repository without a working
directory is created at the pointed path.
Otherwise, the provided path will be considered as the working
directory into which the .git directory will be created.
List branches. See list_branches/2.
List branches
List index. See list_index/2.
List index.
List remotes. Returns a list of {Name, URL, [push|fetch]} triples.
List all tags in the repository. Lightweight tags are returned as plain binaries; annotated tags are also returned as plain binaries unless the {lines, N} option is used. See list_tags/2.
List tags, optionally filtered by pattern or with options. When PatternOrOpts is a string or binary it is used as a glob pattern to filter tag names (e.g. "v1.*"). When it is a proplist, the following options are recognised
Merge another branch into the current branch.
Returns {ok, Status}' where Status is 'up_to_date', 'fast_forward', or 'merged'. On conflict returns{conflict, ConflictList}'.
Move/rename a file in the index and write the index.
Open a local git repository
Pull from origin
Pull from given remote (e.g. origin).
Push changes to remote (origin)
Push to given remote
Push refs to given remote
Abort the current rebase operation.
Finish the rebase operation.
Initialize a rebase operation. Returns number of operations in the rebase sequence.
Continue to the next rebase operation. Returns 'done' when all operations are complete, or operation info.
Show reference logs. Returns a list of {OID, Message, Author, Time} tuples.
Add a remote
Delete a remote
Rename a remote
Change the fetch/push URL for a remote. See remote_set_url/4.
Change the fetch/push URL for a remote. If Opts contains push, the URL is set only as the push URL.
Remove a file from the index and write the index.
Return the list of OIDs for the given specs.
Same as rev_parse(Repo, Spec, []).
Reverse parse a reference. See [https://git-scm.com/docs/git-rev-parse.html#_specifying_revisions] for the formats of a Spec.
Revert a commit (creates new commit undoing the changes).
Returns ok' on success,{conflict, Conflicts}' on merge conflict.
Apply a stash without removing it.
Returns ok' on success,{conflict, Conflicts}' on conflict.
Delete a stash.
List all stashed changes. Returns list of {Index, Name} tuples.
Apply and remove a stash.
Returns ok' on success,{conflict, Conflicts}' on conflict.
Save uncommitted changes to stash.
Returns {ok, StashOID}' or{error, no_changes}' if nothing to stash.
Get repository status
Get repository status
Create a tag
Create a tag
Create a tag
Delete a tag
Types
-type add_opt() :: verbose | dry_run | update | force.
-type add_opts() :: [add_opt()].
-type branch_create_opts() :: [overwrite | {target, binary()}].
Branch creation options
overwrite— Force to overwrite the existing branch{target, Commit}— Use the target commit (default~"HEAD")
-type cat_file_opt() :: type | size | {abbrev, pos_integer()}.
-type cat_file_opts() :: [cat_file_opt()].
-type cfg_source() :: repository() | default | system | xdg | global | local | app | highest.
Configuration source. If the value is an atom, then:
default— Find default configuration file for this appsystem— System-wide configuration file - /etc/gitconfig on Linux systemsxdg— XDG compatible configuration file, typically ~/.config/git/configglobal— User-specific global configuration file, typically ~/.gitconfiglocal— Repository specific configuration file; $WORK_DIR/.git/config on non-bare reposapp— Application specific configuration file; freely defined by applicationshighest— The most specific config file available for the app
-type checkout_opt() :: force | verbose | perf.
-type checkout_opts() :: [checkout_opt()].
-type commit_opt() ::
encoding | message | summary | time | time_offset | committer | author | header | tree_id.
-type commit_opts() :: [commit_opt()].
-type list_branch_opt() :: local | remote | all | fullname | {limit, pos_integer()}.
List branch option.
local— Return only local branchesremote— Return only remote branchesall— Return all branches (default)fullname— Return full branch names{limit, Limit}— Return up to this number of branches
-type list_branch_opts() :: [list_branch_opt()].
-type list_index_entry() :: #{path => binary(), stage => [normal | ancestor | ours | theirs], conflict => boolean(), oid => binary(), mode => pos_integer(), size => non_neg_integer(), ctime => pos_integer(), mtime => pos_integer()}.
-type list_index_opt() :: {abbrev, pos_integer()} | {fields, all | [path | stage | conflict | oid | mode | size | ctime | mtime]}.
List index option.
{abbrev, NumChars}— NumChars truncates the commit hash (must be less then 40).{fields, ListOfFields}— Field list to return. If not specified, the option will default to[path].
-type list_index_opts() :: [list_index_opt()].
-type repository() :: reference().
-type rev_list_opt() :: [topo_order | date_order | reverse | {limit, pos_integer()} | {abbrev, pos_integer()}].
-type rev_list_opts() :: [rev_list_opt()].
-type rev_parse_opt() :: {abbrev, pos_integer()}.
-type rev_parse_opts() :: [rev_parse_opt()].
-type status_opt() :: {untracked, none | normal | recursive} | {paths, [binary()]} | branch | ignored | submodules | ignore_submodules.
Status function options
{untracked, Untracked}—Untrackedcan be one of:none- don't include untracked filesnormal- include untracked filesrecursive- include untracked files and recurse into untracked directories
{paths, Paths}—Pathis an array of path patterns to matchbranch— Include branch nameignored— Include ignored filesignore_submodules— Indicates that submodules should be skippedsubmodules— Include submodules (overridesignore_submodules)
-type status_opts() :: [status_opt()].
-type tag_opt() :: [{message, binary()} | {pattern, binary()} | {target, binary()} | {lines, integer()}].
Tag creation options
{message, Msg}— Message associated with the tag's commit{pattern, Pat}— Pattern to search matching tags{target, SHA}— Target commit SHA to be associated with the tag{lines, Num}— Number of lines in the commit to store
-type tag_opts() :: [tag_opt()].
Functions
-spec add(repository(), binary() | string() | [binary() | string()]) -> add_result().
Add files matching PathSpecs to index. See add/3.
-spec add(repository(), [binary() | string()], add_opts()) -> add_result().
Add files matching PathSpecs to index with options.
-spec add_all(repository()) -> add_result().
Add all pending changes (equivalent to git add .). See add/2 and add/3.
-spec blame(repository(), string() | binary()) -> [{non_neg_integer(), {binary(), binary()}, binary(), integer()}].
Show file change history by line. Returns a list of {LineNumber, {Author, Email}, CommitOID, Time} tuples.
-spec blame(repository(), string() | binary(), list()) -> [{non_neg_integer(), {binary(), binary()}, binary(), integer()}].
Show file change history by line with options. Opts is a list of:
- {pattern, Pattern} - Pattern to match tags
Create a branch
See: git:branch_create/3.
-spec branch_create(repository(), binary() | string(), branch_create_opts()) -> ok | {error, binary()}.
Create a branch Example:
1> R = git:clone(~"https://github.com/saleyn/egit.git", "/tmp/egit").
#Ref<0.170091758.2335834136.12133>
2> git:branch_create(R, "tmp").
ok
-spec branch_delete(repository(), binary() | string()) -> ok | {error, binary()}.
Delete a branch
Rename a branch
See: branch_rename/4.
-spec branch_rename(repository(), binary() | string(), binary() | string(), [overwrite]) -> ok | {error, binary()}.
Rename a branch
-spec cat_file(repository(), binary() | string()) -> map() | {error, term()}.
Same as cat_file(Repo, Rev, []). See cat_file/3.
-spec cat_file(repository(), binary() | string(), cat_file_opts()) -> {ok, term()} | {error, term()}.
Provide content or type and size information for repository objects. Example:
1> R = git:open(".").
2> git:cat_file(R, "main", [{abbrev, 5}]).
#{type => commit,
author => {~"John Doh",~"test@gmail.com",1686195121, -14400},
oid => ~"b85d0",
parents => [~"1fd4b"]}
7> git:cat_file(R, "b85d0", [{abbrev, 5}]).
#{type => tree,
commits =>
[{~".github",~"tree",~"1e41f",16384},
{~".gitignore",~"blob",~"b893a",33188},
{~".gitmodules",~"blob",~"2550a",33188},
{~".vscode",~"tree",~"c7b1b",16384},
{~"LICENSE",~"blob",~"d6456",33188},
{~"Makefile",~"blob",~"2d635",33188},
{~"README.md",~"blob",~"7b3d0",33188},
{~"c_src",~"tree",~"147f3",16384},
{~"rebar.config",~"blob",~"1f68a",33188},
{~"rebar.lock",~"blob",~"57afc",33188},
{~"src",~"tree",~"1bccb",16384}]}
8> git:cat_file(R, "b893a", [{abbrev, 5}]).
#{type => blob,
data => ~"*.swp\n*.dump\n/c_src/*.o\n/c_src/fmt\n/priv/*.so\n/_build\n/doc\n"}
-spec checkout(repository(), binary() | string()) -> ok | {error, term()}.
Same as checkout(Repo, Revision, []).
-spec checkout(repository(), binary(), checkout_opts()) -> ok | checkout_stats() | {error, term()}.
Check out a revision or branch.
Opts is a list of:
- force - Force the checkout even if there are conflicts
- verbose - Return a checkout_stats() map instead of ok
- perf - Include performance counters in the stats map (requires verbose)
-spec cherry_pick(repository(), string() | binary()) -> ok | {conflict, [binary()]} | {error, term()}.
Apply a single commit to current branch. Returns ok on success, {conflict, Conflicts} on merge conflict, or {error, Reason} on failure.
-spec clone(binary() | string(), binary() | string()) -> repository().
Clone a remote repository to the local path
-spec commit(repository(), binary() | string()) -> {ok, OID :: binary() | nil} | {error, binary() | atom()}.
Commit staged changes to the repository. Returns {ok, OID} where OID is the new commit hash, or {ok, nil} if there are no staged changes.
-spec commit_lookup(repository(), binary() | string(), [commit_opt()]) -> #{commit_opt() => term()}.
Lookup commit details identified by OID.
Opts is a list of commit_opt() field names to return. An empty list returns an empty map. Pass any of: encoding, message, summary, time, time_offset, committer, author, header, tree_id.
Example:
1> R = git:open("/tmp/egit").
2> {ok, OID} = git:rev_parse(R, "HEAD").
3> git:commit_lookup(R, OID, [author, message, time]).
#{author => {~"John Doh",~"test@gmail.com",1686195121,-14400},
message => ~"Add test files\n",
time => 1686195121}
Get git configuration value Example:
1> R = git:clone(~"https://github.com/saleyn/egit.git", "/tmp/egit").
#Ref<0.170091758.2335834136.12133>
2> git:config_get(R, "user.name").
{ok,~"John Doh"}
-spec config_set(cfg_source(), binary() | string(), binary() | string()) -> ok | {error, binary() | atom()}.
Set git configuration value Example:
1> R = git:clone(~"https://github.com/saleyn/egit.git", "/tmp/egit").
#Ref<0.170091758.2335834136.12133>
2> git:config_set(R, "user.name", "Test User").
ok
-spec describe(repository(), string() | binary()) -> {ok, binary()} | {error, term()}.
Describe working tree state. Returns a human-readable description of the most recent tag and commits. Example: "v1.0.0-5-gabcd123"
Describe working tree state with options. Opts is a list of:
- {pattern, Pattern} - Pattern to match tags
-spec diff(repository(), string() | binary(), string() | binary()) -> [{binary(), binary(), integer(), integer()}].
Compare two revisions and return list of differences.
See: diff/4.
-spec diff(repository(), string() | binary(), string() | binary(), list()) -> [{binary(), binary(), integer(), integer()}].
Compare two revisions and return list of differences. Returns list of {Path, Status, StatusCode, Similarity} tuples. Status values: "added", "deleted", "modified", "renamed", "copied", "typechange"
-spec fetch(repository()) -> ok | {error, binary()}.
Fetch from origin
-spec fetch(repository(), binary() | string()) -> ok | {error, binary()}.
Fetch from given remote (e.g. origin).
-spec init(binary() | string()) -> repository().
Init a repository.
See: init/2.
-spec init(binary() | string(), [bare]) -> repository().
Init a repository.
If Opts' list containsbare', a Git repository without a working
directory is created at the pointed path.
Otherwise, the provided path will be considered as the working
directory into which the .git directory will be created.
List branches. See list_branches/2.
-spec list_branches(repository(), list_branch_opts()) -> [{local | remote, binary()}].
List branches
List index. See list_index/2.
-spec list_index(repository(), list_index_opts()) -> [list_index_entry()].
List index.
-spec list_remotes(repository()) -> [{binary(), binary(), [push | fetch]}].
List remotes. Returns a list of {Name, URL, [push|fetch]} triples.
List all tags in the repository. Lightweight tags are returned as plain binaries; annotated tags are also returned as plain binaries unless the {lines, N} option is used. See list_tags/2.
-spec list_tags(repository(), string() | binary() | list()) -> [binary() | {binary(), binary()}] | {error, binary() | atom()}.
List tags, optionally filtered by pattern or with options. When PatternOrOpts is a string or binary it is used as a glob pattern to filter tag names (e.g. "v1.*"). When it is a proplist, the following options are recognised:
- {pattern, Pat} - Glob pattern to filter tag names (default "*")
- {lines, N} - Include up to N lines of the tag/commit message. Annotated tags whose message is non-empty are returned as {Name, Message} tuples; all others remain plain binaries.
Example:
1> R = git:open("/tmp/egit").
2> git:list_tags(R, "v0.*").
[~"v0.1.0",~"v0.2.0"]
3> git:list_tags(R, [{lines, 1}]).
[{~"v0.1.0",~"Release 0.1.0\n"},~"v0.2.0"]
-spec merge(repository(), string() | binary()) -> {ok, atom()} | {conflict, [binary()]} | {error, term()}.
Merge another branch into the current branch.
Returns {ok, Status}' where Status is 'up_to_date', 'fast_forward', or 'merged'. On conflict returns{conflict, ConflictList}'.
Move/rename a file in the index and write the index.
-spec open(binary() | string()) -> repository().
Open a local git repository
-spec pull(repository()) -> ok | {error, binary()}.
Pull from origin
-spec pull(repository(), binary() | string()) -> ok | {error, binary()}.
Pull from given remote (e.g. origin).
-spec push(repository()) -> ok | {error, binary()}.
Push changes to remote (origin)
-spec push(repository(), binary() | string()) -> ok | {error, binary()}.
Push to given remote
Push refs to given remote
-spec rebase_abort(repository()) -> ok | {error, term()}.
Abort the current rebase operation.
-spec rebase_finish(repository()) -> ok | {error, term()}.
Finish the rebase operation.
-spec rebase_init(repository(), string() | binary()) -> integer() | {error, term()}.
Initialize a rebase operation. Returns number of operations in the rebase sequence.
-spec rebase_next(repository()) -> done | tuple() | {error, term()}.
Continue to the next rebase operation. Returns 'done' when all operations are complete, or operation info.
Show reference logs. Returns a list of {OID, Message, Author, Time} tuples.
Add a remote
-spec remote_delete(repository(), binary() | string()) -> ok | {error, binary()}.
Delete a remote
-spec remote_rename(repository(), binary() | string(), binary() | string()) -> ok | {error, binary()}.
Rename a remote
-spec remote_set_url(repository(), binary() | string(), binary() | string()) -> ok | {error, binary()}.
Change the fetch/push URL for a remote. See remote_set_url/4.
Change the fetch/push URL for a remote. If Opts contains push, the URL is set only as the push URL.
-spec remove(repository(), string() | binary()) -> ok | {error, term()}.
Remove a file from the index and write the index.
-spec reset(repository(), soft | mixed | hard) -> ok | {error, term()}.
-spec rev_list(repository(), ['not' | 'Elixir.Not' | string() | binary()] | binary(), rev_list_opts()) -> #{commit_opt() => term()}.
Return the list of OIDs for the given specs.
Opts is a list of:
- topo_order | date_order | reverse
- Control sorting order
- {limit, `Limit'}
- Limit is an integer that limits the number of refs returned
- {abbrev, `NumChars'}
- NumChars truncates the commit hash (must be less then 40)
Example:
9> git:rev_list(R, ["HEAD"], [{limit, 4}, {abbrev, 7}]).
[~"f791f01",~"1b74c46",~"c40374d",~"12968bd"]
-spec rev_parse(repository(), binary() | string()) -> {ok, binary()} | map() | {error, binary() | atom()}.
Same as rev_parse(Repo, Spec, []).
-spec rev_parse(repository(), binary() | string(), rev_parse_opts()) -> {ok, binary()} | map() | {error, binary() | atom()}.
Reverse parse a reference. See [https://git-scm.com/docs/git-rev-parse.html#_specifying_revisions] for the formats of a Spec.
Opts is a list of:
- {abbrev, NumChars} - NumChars truncates the commit hash (must be less then 40)
When a reference refers to a single object, an ok tuple with a binary string of the commit hash is returned. When it refers to a range (e.g. HEAD..HEAD~2), a map is returned with from and to keys. When using a Symmetric Difference Notation (i.e. HEAD...HEAD~4), a map with three keys from, to, and merge_base is returned.
Examples:
2> git:rev_parse(R,~"HEAD~4", [{abbrev, 7}]).
{ok,~"6d6f662"}
3> git:rev_parse(R,~"HEAD..HEAD~4", [{abbrev, 7}]).
#{from => ~"f791f01",to => ~"6d6f662"}
4> git:rev_parse(R,~"HEAD...HEAD~4", [{abbrev, 7}]).
#{from => ~"f791f01",merge_base => ~"6d6f662", to => ~"6d6f662"}
-spec revert(repository(), string() | binary()) -> ok | {conflict, [binary()]} | {error, term()}.
Revert a commit (creates new commit undoing the changes).
Returns ok' on success,{conflict, Conflicts}' on merge conflict.
-spec stash_apply(repository(), integer()) -> ok | {conflict, [binary()]} | {error, term()}.
Apply a stash without removing it.
Returns ok' on success,{conflict, Conflicts}' on conflict.
-spec stash_drop(repository(), integer()) -> ok | {error, term()}.
Delete a stash.
-spec stash_list(repository()) -> [{integer(), binary()}].
List all stashed changes. Returns list of {Index, Name} tuples.
-spec stash_pop(repository(), integer()) -> ok | {conflict, [binary()]} | {error, term()}.
Apply and remove a stash.
Returns ok' on success,{conflict, Conflicts}' on conflict.
-spec stash_save(repository(), string() | binary()) -> {ok, binary()} | {error, term()}.
Save uncommitted changes to stash.
Returns {ok, StashOID}' or{error, no_changes}' if nothing to stash.
-spec status(repository()) -> map() | {error, term()}.
Get repository status
-spec status(repository(), status_opts()) -> map() | {error, term()}.
Get repository status
-spec tag_create(repository(), string() | binary()) -> ok | {error, binary() | atom()}.
Create a tag
-spec tag_create(repository(), string() | binary(), nil | string() | binary()) -> ok | {error, binary() | atom()}.
Create a tag
-spec tag_create(repository(), string() | binary(), nil | string() | binary(), tag_opts()) -> ok | {error, binary() | atom()}.
Create a tag
-spec tag_delete(repository(), string() | binary()) -> ok | {error, binary() | atom()}.
Delete a tag