static int gbr_walk_next(struct gbr_walk_context *ctx) { int i; for (i = 0; i < 2; i++) { if (ctx->err[i] == 0) { ctx->err[i] = git_revwalk_next(&ctx->iter[i], ctx->w[i]); if (ctx->err[i] == 0) { ctx->tot[i]++; } } } if (ctx->err[0] == 0) { if (ctx->err[1] == 0) { /* Both had commits... */ if (git_oid_cmp(&ctx->iter[0], &ctx->iter[1])) { /* ..different commits */ ctx->count[0]++; ctx->count[1]++; } } else { /* Only first had commits */ ctx->count[0]++; } } else if (ctx->err[1] == 0) { /* Only second had commits */ ctx->count[1]++; } return ctx->count[0] <= HOPELESSLY_DIVERGED && ctx->count[1] <= HOPELESSLY_DIVERGED && (ctx->err[0] == 0 || ctx->err[1] == 0); }
void test_revwalk_simplify__first_parent(void) { git_repository *repo; git_revwalk *walk; git_oid id, expected[4]; int i, error; for (i = 0; i < 4; i++) { git_oid_fromstr(&expected[i], expected_str[i]); } repo = cl_git_sandbox_init("testrepo.git"); cl_git_pass(git_revwalk_new(&walk, repo)); git_oid_fromstr(&id, commit_head); cl_git_pass(git_revwalk_push(walk, &id)); git_revwalk_simplify_first_parent(walk); i = 0; while ((error = git_revwalk_next(&id, walk)) == 0) { cl_assert_equal_oid(&expected[i], &id); i++; } cl_assert_equal_i(i, 4); cl_assert_equal_i(error, GIT_ITEROVER); git_revwalk_free(walk); }
static int walk_and_search(git_object **out, git_revwalk *walk, regex_t *regex) { int error; git_oid oid; git_object *obj; while (!(error = git_revwalk_next(&oid, walk))) { error = git_object_lookup(&obj, git_revwalk_repository(walk), &oid, GIT_OBJ_COMMIT); if ((error < 0) && (error != GIT_ENOTFOUND)) return -1; if (!regexec(regex, git_commit_message((git_commit*)obj), 0, NULL, 0)) { *out = obj; return 0; } git_object_free(obj); } if (error < 0 && error == GIT_ITEROVER) error = GIT_ENOTFOUND; return error; }
/* * call-seq: * walker.each { |commit| block } * walker.each -> Iterator * * Perform the walk through the repository, yielding each * one of the commits found as a <tt>Rugged::Commit</tt> instance * to +block+. * * If no +block+ is given, an +Iterator+ will be returned. * * The walker must have been previously set-up before a walk can be performed * (i.e. at least one commit must have been pushed). * * walker.push("92b22bbcb37caf4f6f53d30292169e84f5e4283b") * walker.each { |commit| puts commit.oid } * * generates: * * 92b22bbcb37caf4f6f53d30292169e84f5e4283b * 6b750d5800439b502de669465b385e5f469c78b6 * ef9207141549f4ffcd3c4597e270d32e10d0a6bc * cb75e05f0f8ac3407fb3bd0ebd5ff07573b16c9f * ... */ static VALUE rb_git_walker_each(VALUE self) { git_revwalk *walk; git_commit *commit; git_repository *repo; git_oid commit_oid; int error; Data_Get_Struct(self, git_revwalk, walk); repo = git_revwalk_repository(walk); if (!rb_block_given_p()) return rb_funcall(self, rb_intern("to_enum"), 0); while ((error = git_revwalk_next(&commit_oid, walk)) == 0) { error = git_commit_lookup(&commit, repo, &commit_oid); rugged_exception_check(error); rb_yield(rugged_object_new(rugged_owner(self), (git_object *)commit)); } if (error != GIT_ITEROVER) rugged_exception_check(error); return Qnil; }
static int test_walk_only(git_revwalk *walk, const int possible_results[][commit_count], int results_count) { git_oid oid; int i; int result_array[commit_count]; for (i = 0; i < commit_count; ++i) result_array[i] = -1; i = 0; while (git_revwalk_next(&oid, walk) == 0) { result_array[i++] = get_commit_index(&oid); /*{ char str[GIT_OID_HEXSZ+1]; git_oid_fmt(str, &oid); str[GIT_OID_HEXSZ] = 0; printf(" %d) %s\n", i, str); }*/ } for (i = 0; i < results_count; ++i) if (memcmp(possible_results[i], result_array, result_bytes) == 0) return 0; return GIT_ERROR; }
//go through history using the revwalker object bool MainWindow::walkHistory(git_commit* commit) { git_commit* wcommit; const char* cmsg; const git_oid* oid = git_commit_id(commit); git_oid commit_oid; git_oid_cpy(&commit_oid, oid); git_revwalk* walker; git_revwalk_new(&walker, repo); git_revwalk_sorting(walker, GIT_SORT_TOPOLOGICAL | GIT_SORT_TIME); git_revwalk_push(walker, &commit_oid); while (git_revwalk_next(&commit_oid, walker) == 0) { int error = git_commit_lookup(&wcommit, repo, &commit_oid); cmsg = git_commit_message(wcommit); qDebug() << "Commit msg = " << cmsg; git_commit_free(wcommit); } git_revwalk_free(walker); }
static int test_walk(git_revwalk *walk, const git_oid *root, int flags, const int possible_results[][6], int results_count) { git_oid oid; int i; int result_array[commit_count]; git_revwalk_sorting(walk, flags); git_revwalk_push(walk, root); for (i = 0; i < commit_count; ++i) result_array[i] = -1; i = 0; while (git_revwalk_next(&oid, walk) == GIT_SUCCESS) { result_array[i++] = get_commit_index(&oid); /*{ char str[41]; git_oid_fmt(str, &oid); str[40] = 0; printf(" %d) %s\n", i, str); }*/ } for (i = 0; i < results_count; ++i) if (memcmp(possible_results[i], result_array, result_bytes) == 0) return GIT_SUCCESS; return GIT_ERROR; }
bool QGitRevWalk::next(QGitCommit & commit) { QGitOId oid; int err = git_revwalk_next(oid.data(), m_revWalk); if ( (err != GIT_SUCCESS) || !oid.isValid() ) commit = QGitCommit(); else commit = (repository().lookupCommit(oid)); return !commit.isNull(); }
void test_revwalk_basic__push_head(void) { int i = 0; git_oid oid; cl_git_pass(git_revwalk_push_head(_walk)); while (git_revwalk_next(&oid, _walk) == 0) { i++; } /* git log HEAD --oneline | wc -l => 7 */ cl_assert(i == 7); }
void test_revwalk_basic__glob_heads(void) { int i = 0; git_oid oid; cl_git_pass(git_revwalk_push_glob(_walk, "heads")); while (git_revwalk_next(&oid, _walk) == 0) { i++; } /* git log --branches --oneline | wc -l => 14 */ cl_assert(i == 14); }
int cmd_log(git_repository *repo, int argc, char **argv) { int err = 0; int rc; git_revwalk *walk; git_oid oid; git_reference *revision_ref = NULL; git_object *revision_obj = NULL; rc = EXIT_FAILURE; git_revwalk_new(&walk,repo); if (argc > 1) { if ((err = git_reference_dwim(&revision_ref, repo, argv[1]))) goto out; if ((err = git_reference_peel(&revision_obj, revision_ref, GIT_OBJ_ANY))) goto out; if ((err = git_revwalk_push(walk, git_object_id(revision_obj)))) goto out; } else { git_revwalk_push_head(walk); } while ((git_revwalk_next(&oid, walk)) == 0) { struct git_commit *wcommit; if (git_commit_lookup(&wcommit, repo, &oid) != 0) continue; print_commit(wcommit,"commit %C\nAuthor: %a\nDate: %d\n\n%m\n"); git_commit_free(wcommit); } git_revwalk_free(walk); rc = EXIT_SUCCESS; out: if (err != GIT_OK) libgit_error(); if (revision_obj) git_object_free(revision_obj); if (revision_ref) git_reference_free(revision_ref); return rc; }
void test_revwalk_basic__push_head_hide_ref_nobase(void) { int i = 0; git_oid oid; cl_git_pass(git_revwalk_push_head(_walk)); cl_git_pass(git_revwalk_hide_ref(_walk, "refs/heads/packed")); while (git_revwalk_next(&oid, _walk) == 0) { i++; } /* git log HEAD --oneline --not refs/heads/packed | wc -l => 7 */ cl_assert(i == 7); }
/* Helper to get the latest commit of the specified file */ int git_show_last_commit(char *filename) { git_oid oid; git_commit *commit = NULL; /* Set up pathspec. */ git_diff_options diffopts = GIT_DIFF_OPTIONS_INIT; diffopts.pathspec.strings = &filename; diffopts.pathspec.count = 1; /* Use the revwalker to traverse the history. */ check_lg2(git_revwalk_push_ref(s.walker, s.ref), "Could not find repository reference", NULL); for (; !git_revwalk_next(&oid, s.walker); git_commit_free(commit)) { check_lg2(git_commit_lookup(&commit, s.repo, &oid), "Failed to look up commit", NULL); int parents = (int)git_commit_parentcount(commit); int unmatched = parents; if (parents == 0) { git_tree *tree; git_pathspec *ps; check_lg2(git_commit_tree(&tree, commit), "Get tree", NULL); check_lg2(git_pathspec_new(&ps, &diffopts.pathspec), "Building pathspec", NULL); if (git_pathspec_match_tree( NULL, tree, GIT_PATHSPEC_NO_MATCH_ERROR, ps) != 0) unmatched = 1; git_pathspec_free(ps); git_tree_free(tree); } else { int i; for (i = 0; i < parents; ++i) { if (match_with_parent(commit, i, &diffopts)) unmatched--; } } if (unmatched > 0) continue; print_commit(commit); git_commit_free(commit); break; } git_revwalk_reset(s.walker); return 0; }
void test_revwalk_basic__glob_heads_with_invalid(void) { int i; git_oid oid; revwalk_basic_setup_walk("testrepo"); cl_git_mkfile("testrepo/.git/refs/heads/garbage", "not-a-ref"); cl_git_pass(git_revwalk_push_glob(_walk, "heads")); for (i = 0; !git_revwalk_next(&oid, _walk); ++i) /* walking */; /* git log --branches --oneline | wc -l => 16 */ cl_assert_equal_i(17, i); }
void test_revwalk_basic__push_head(void) { int i = 0; git_oid oid; revwalk_basic_setup_walk(NULL); cl_git_pass(git_revwalk_push_head(_walk)); while (git_revwalk_next(&oid, _walk) == 0) { i++; } /* git log HEAD --oneline | wc -l => 7 */ cl_assert_equal_i(i, 7); }
void test_revwalk_basic__push_head_hide_ref(void) { int i = 0; git_oid oid; revwalk_basic_setup_walk(NULL); cl_git_pass(git_revwalk_push_head(_walk)); cl_git_pass(git_revwalk_hide_ref(_walk, "refs/heads/packed-test")); while (git_revwalk_next(&oid, _walk) == 0) { i++; } /* git log HEAD --oneline --not refs/heads/packed-test | wc -l => 4 */ cl_assert_equal_i(i, 4); }
static int rebase_init_operations( git_rebase *rebase, git_repository *repo, const git_annotated_commit *branch, const git_annotated_commit *upstream, const git_annotated_commit *onto) { git_revwalk *revwalk = NULL; git_commit *commit; git_oid id; bool merge; git_rebase_operation *operation; int error; if (!upstream) upstream = onto; if ((error = git_revwalk_new(&revwalk, rebase->repo)) < 0 || (error = git_revwalk_push(revwalk, git_annotated_commit_id(branch))) < 0 || (error = git_revwalk_hide(revwalk, git_annotated_commit_id(upstream))) < 0) goto done; git_revwalk_sorting(revwalk, GIT_SORT_REVERSE | GIT_SORT_TIME); while ((error = git_revwalk_next(&id, revwalk)) == 0) { if ((error = git_commit_lookup(&commit, repo, &id)) < 0) goto done; merge = (git_commit_parentcount(commit) > 1); git_commit_free(commit); if (merge) continue; operation = git_array_alloc(rebase->operations); operation->type = GIT_REBASE_OPERATION_PICK; git_oid_cpy((git_oid *)&operation->id, &id); } error = 0; done: git_revwalk_free(revwalk); return error; }
void test_revwalk_basic__push_all(void) { git_oid oid; int i = 0; revwalk_basic_setup_walk(NULL); git_revwalk_reset(_walk); git_revwalk_sorting(_walk, 0); cl_git_pass(git_revwalk_push_glob(_walk, "*")); while (git_revwalk_next(&oid, _walk) == 0) { i++; } /* git rev-list --count --all #=> 15 */ cl_assert_equal_i(15, i); }
void test_revwalk_basic__push_mixed(void) { git_oid oid; int i = 0; revwalk_basic_setup_walk(NULL); git_revwalk_reset(_walk); git_revwalk_sorting(_walk, 0); cl_git_pass(git_revwalk_push_glob(_walk, "tags")); while (git_revwalk_next(&oid, _walk) == 0) { i++; } /* git rev-list --count --glob=tags #=> 9 */ cl_assert_equal_i(9, i); }
/* * Difference between test_revwalk_basic__multiple_push_1 and * test_revwalk_basic__multiple_push_2 is in the order reference * refs/heads/packed-test and commit 5b5b02 are pushed. * revwalk should return same commits in both the tests. * $ git rev-list 5b5b02 HEAD ^refs/heads/packed-test * a65fedf39aefe402d3bb6e24df4d4f5fe4547750 * be3563ae3f795b2b4353bcce3a527ad0a4f7f644 * c47800c7266a2be04c571c04d5a6614691ea99bd * 9fd738e8f7967c078dceed8190330fc8648ee56a * $ git log 5b5b02 HEAD --oneline --not refs/heads/packed-test | wc -l => 4 * a65fedf * be3563a Merge branch 'br2' * c47800c branch commit one * 9fd738e a fourth commit */ void test_revwalk_basic__multiple_push_2(void) { int i = 0; git_oid oid; revwalk_basic_setup_walk(NULL); cl_git_pass(git_oid_fromstr(&oid, "5b5b025afb0b4c913b4c338a42934a3863bf3644")); cl_git_pass(git_revwalk_push(_walk, &oid)); cl_git_pass(git_revwalk_hide_ref(_walk, "refs/heads/packed-test")); cl_git_pass(git_revwalk_push_head(_walk)); while (git_revwalk_next(&oid, _walk) == 0) i++; cl_assert_equal_i(i, 4); }
int main (int argc, char **argv) { git_repository *repo; git_revwalk *walk; git_oid oid; char buf[GIT_OID_HEXSZ+1]; git_libgit2_init(); check_lg2(git_repository_open_ext(&repo, ".", 0, NULL), "opening repository", NULL); check_lg2(git_revwalk_new(&walk, repo), "allocating revwalk", NULL); check_lg2(revwalk_parseopts(repo, walk, argc-1, argv+1), "parsing options", NULL); while (!git_revwalk_next(&oid, walk)) { git_oid_fmt(buf, &oid); buf[GIT_OID_HEXSZ] = '\0'; printf("%s\n", buf); } git_libgit2_shutdown(); return 0; }
int cmd_revwalk(git_repository *repo, int argc, const char **argv) { git_revwalk *walker; git_oid oid; int error; if (git_revwalk_new(&walker, repo) < 0) return -1; git_revwalk_sorting(walker, GIT_SORT_TIME); if (git_revwalk_push_head(walker) < 0) return -1; while ((error = git_revwalk_next(&oid, walker)) == 0) { char hex[41]; hex[40] = '\0'; git_oid_fmt(hex, &oid); printf("%s\n", hex); } return error == GIT_ITEROVER ? 0 : error; }
PyObject * Walker_iternext(Walker *self) { int err; git_commit *commit; Commit *py_commit; git_oid oid; err = git_revwalk_next(&oid, self->walk); if (err < 0) return Error_set(err); err = git_commit_lookup(&commit, self->repo->repo, &oid); if (err < 0) return Error_set(err); py_commit = PyObject_New(Commit, &CommitType); if (py_commit) { py_commit->commit = commit; Py_INCREF(self->repo); py_commit->repo = self->repo; } return (PyObject*)py_commit; }
void test_revwalk_basic__mimic_git_rev_list(void) { git_oid oid; revwalk_basic_setup_walk(NULL); git_revwalk_sorting(_walk, GIT_SORT_TIME); cl_git_pass(git_revwalk_push_ref(_walk, "refs/heads/br2")); cl_git_pass(git_revwalk_push_ref(_walk, "refs/heads/master")); cl_git_pass(git_oid_fromstr(&oid, "e90810b8df3e80c413d903f631643c716887138d")); cl_git_pass(git_revwalk_push(_walk, &oid)); cl_git_pass(git_revwalk_next(&oid, _walk)); cl_assert(!git_oid_streq(&oid, "a65fedf39aefe402d3bb6e24df4d4f5fe4547750")); cl_git_pass(git_revwalk_next(&oid, _walk)); cl_assert(!git_oid_streq(&oid, "e90810b8df3e80c413d903f631643c716887138d")); cl_git_pass(git_revwalk_next(&oid, _walk)); cl_assert(!git_oid_streq(&oid, "6dcf9bf7541ee10456529833502442f385010c3d")); cl_git_pass(git_revwalk_next(&oid, _walk)); cl_assert(!git_oid_streq(&oid, "a4a7dce85cf63874e984719f4fdd239f5145052f")); cl_git_pass(git_revwalk_next(&oid, _walk)); cl_assert(!git_oid_streq(&oid, "be3563ae3f795b2b4353bcce3a527ad0a4f7f644")); cl_git_pass(git_revwalk_next(&oid, _walk)); cl_assert(!git_oid_streq(&oid, "c47800c7266a2be04c571c04d5a6614691ea99bd")); cl_git_pass(git_revwalk_next(&oid, _walk)); cl_assert(!git_oid_streq(&oid, "9fd738e8f7967c078dceed8190330fc8648ee56a")); cl_git_pass(git_revwalk_next(&oid, _walk)); cl_assert(!git_oid_streq(&oid, "4a202b346bb0fb0db7eff3cffeb3c70babbd2045")); cl_git_pass(git_revwalk_next(&oid, _walk)); cl_assert(!git_oid_streq(&oid, "5b5b025afb0b4c913b4c338a42934a3863bf3644")); cl_git_pass(git_revwalk_next(&oid, _walk)); cl_assert(!git_oid_streq(&oid, "8496071c1b46c854b31185ea97743be6a8774479")); cl_git_fail_with(git_revwalk_next(&oid, _walk), GIT_ITEROVER); }
void QGit::listCommits(QString object, int length) { QList<QGitCommit> commits; git_repository *repo = nullptr; git_revwalk *walker = nullptr; git_commit *parent = nullptr; git_commit *commit = nullptr; git_diff *diff = nullptr; git_oid oid; int count = 0; int res = 0; QGitError error; try { res = git_repository_open(&repo, m_path.absolutePath().toUtf8().constData()); if (res) { throw QGitError("git_repository_open", res); } res = git_revwalk_new(&walker, repo); if (res) { throw QGitError("git_revwalk_new", res); } if (object.isEmpty()) { res = git_revwalk_push_head(walker); if (res) { length = 0; } } else { res = git_oid_fromstr(&oid, object.toLatin1().constData()); if (res) { throw QGitError("git_oid_fromstr", res); } res = git_revwalk_push(walker, &oid); if (res) { throw QGitError("git_revwalk_push", res); } memset(&oid, 0, sizeof(oid)); git_revwalk_next(&oid, walker); memset(&oid, 0, sizeof(oid)); } while ((!git_revwalk_next(&oid, walker))&&(count < length)) { QGitCommit item; unsigned int parents = 0; QString commit_id; QList<QGitCommitDiffParent> commit_parents; QDateTime commit_time; QGitSignature commit_author; QGitSignature commit_commiter; QString commit_message; res = git_commit_lookup(&commit, repo, &oid); if (res) { throw QGitError("git_commit_lookup", res); } commit_id = QString::fromUtf8(git_oid_tostr_s(&oid)); parents = git_commit_parentcount(commit); for(unsigned int index = 0; index < parents; index++) { git_commit *parent = nullptr; QByteArray parentStr; res = git_commit_parent(&parent, commit, index); if (res) { throw QGitError("git_commit_parent", res); } const git_oid *parent_iod = git_commit_id(parent); parentStr = QByteArray(git_oid_tostr_s(parent_iod)); commit_parents.append(QGitCommitDiffParent(parentStr)); git_commit_free(parent); parent = nullptr; } auto time = git_commit_time(commit); auto timeOffset = git_commit_time_offset(commit); commit_time = QDateTime::fromMSecsSinceEpoch(time * 1000); commit_time.setOffsetFromUtc(timeOffset * 60); QString author_name = QString::fromUtf8(git_commit_author(commit)->name); QString author_email = QString::fromUtf8(git_commit_author(commit)->email); QDateTime author_when = QDateTime::fromMSecsSinceEpoch(git_commit_author(commit)->when.time * 1000); author_when.setOffsetFromUtc(git_commit_author(commit)->when.offset * 60); commit_author = QGitSignature(author_name, author_email, author_when); QString commiter_name = QString::fromUtf8(git_commit_committer(commit)->name); QString commiter_email = QString::fromUtf8(git_commit_committer(commit)->email); QDateTime commiter_when = QDateTime::fromMSecsSinceEpoch(git_commit_committer(commit)->when.time * 1000); commiter_when.setOffsetFromUtc(git_commit_committer(commit)->when.offset * 60); commit_commiter = QGitSignature(commiter_name, commiter_email, commiter_when); commit_message = QString::fromUtf8(git_commit_message(commit)); item = QGitCommit(commit_id, commit_parents, commit_time, commit_author, commit_commiter, commit_message); commits.push_back(item); git_diff_free(diff); diff = nullptr; git_commit_free(parent); parent = nullptr; git_commit_free(commit); commit = nullptr; count++; } } catch(const QGitError &ex) { error = ex; } emit listCommitsReply(commits, error); if (diff) { git_diff_free(diff); diff = nullptr; } if (parent) { git_commit_free(parent); parent = nullptr; } if (walker) { git_revwalk_free(walker); walker = nullptr; } if (repo) { git_repository_free(repo); repo = nullptr; } }
int cmd_rev_list(int argc, const char **argv) { /* Doesn't pass the tests due to bug in libgit2 apparently */ please_git_do_it_for_me(); const char *commit_string = NULL; const char *format = NULL; int i = 0; git_repository *repository=NULL; git_oid commit_oid; git_oid current_oid; char commit_oid_string[GIT_OID_HEXSZ+1]; size_t len; int e; /* For now, we only implement --format=oneline */ if (argc != 3) { please_git_do_it_for_me(); } for (i = 1; i < 3; ++i) { if (*argv[i] == '-') { if (!prefixcmp(argv[i], "--pretty=")) { format = argv[i] + strlen("--pretty="); } } else { commit_string = argv[i]; } } if (!commit_string) { /* Show usage : ask git for now */ please_git_do_it_for_me(); } if (!format) { /* No option or not handled option */ please_git_do_it_for_me(); } if (strcmp(format, "oneline")) { /* Format not supported for now */ please_git_do_it_for_me(); } /* Supported object specifications are full or short oid */ /* Create the partial oid (filled with '0's) from the given argument */ len = strlen(commit_string); if (len > GIT_OID_HEXSZ) { /* It's not a sha1 */ please_git_do_it_for_me(); } memcpy(commit_oid_string, commit_string, len * sizeof(char)); memset(commit_oid_string + len, '0', (GIT_OID_HEXSZ - len) * sizeof(char)); commit_oid_string[GIT_OID_HEXSZ] = '\0'; e = git_oid_fromstr(&commit_oid, commit_oid_string); if (e) { /* Not an OID. The object can be specified in a lot * of different ways (not supported by libgit2 yet). * Fall back to git. */ please_git_do_it_for_me(); } repository = get_git_repository(); /* Lookup the commit object */ e = git_object_lookup_prefix((git_object **)&commit, repository, &commit_oid, len, GIT_OBJ_ANY); if (e != GIT_OK) { if (e == GIT_ENOTFOUND) { /* Maybe the given argument is not a sha1 * but a tag name (which looks like a sha1) * Fall back to git. */ please_git_do_it_for_me(); } else if (e == GIT_EAMBIGUOUS) { error("%s is an ambiguous prefix", commit_string); } else { libgit_error(); } } if (git_object_type((git_object *)commit) != GIT_OBJ_COMMIT) { /* Not a commit : nothing to do */ cleanup(); return EXIT_SUCCESS; } if (git_revwalk_new(&walk, repository)) { cleanup(); libgit_error(); } git_revwalk_sorting(walk, GIT_SORT_TIME); if (git_revwalk_push(walk, &commit_oid)) { cleanup(); libgit_error(); } git_commit_close(commit); if ((git_revwalk_next(¤t_oid, walk)) == GIT_OK) { char oid_string[GIT_OID_HEXSZ+1]; oid_string[GIT_OID_HEXSZ] = '\0'; const char *cmsg; while (1) { git_oid_fmt(oid_string, ¤t_oid); if (git_commit_lookup(&commit, repository, ¤t_oid)) { libgit_error(); } cmsg = git_commit_message(commit); git_oid_fmt(oid_string, git_commit_id(commit)); printf("%s %s\n", oid_string, cmsg); if ((git_revwalk_next(¤t_oid, walk)) != GIT_OK) break; git_commit_close(commit); } } cleanup(); return EXIT_SUCCESS; }
QGitOId QGitRevWalk::next() const { QGitOId oid; git_revwalk_next(oid.data(), m_revWalk); return oid; }
int main (int argc, char** argv) { // ### Opening the Repository // There are a couple of methods for opening a repository, this being the simplest. // There are also [methods][me] for specifying the index file and work tree locations, here // we are assuming they are in the normal places. // // [me]: http://libgit2.github.com/libgit2/#HEAD/group/repository git_repository *repo; if (argc > 1) { git_repository_open(&repo, argv[1]); } else { git_repository_open(&repo, "/opt/libgit2-test/.git"); } // ### SHA-1 Value Conversions // For our first example, we will convert a 40 character hex value to the 20 byte raw SHA1 value. printf("*Hex to Raw*\n"); char hex[] = "fd6e612585290339ea8bf39c692a7ff6a29cb7c3"; // The `git_oid` is the structure that keeps the SHA value. We will use this throughout the example // for storing the value of the current SHA key we're working with. git_oid oid; git_oid_fromstr(&oid, hex); // Once we've converted the string into the oid value, we can get the raw value of the SHA. printf("Raw 20 bytes: [%.20s]\n", (&oid)->id); // Next we will convert the 20 byte raw SHA1 value to a human readable 40 char hex value. printf("\n*Raw to Hex*\n"); char out[41]; out[40] = '\0'; // If you have a oid, you can easily get the hex value of the SHA as well. git_oid_fmt(out, &oid); printf("SHA hex string: %s\n", out); // ### Working with the Object Database // **libgit2** provides [direct access][odb] to the object database. // The object database is where the actual objects are stored in Git. For // working with raw objects, we'll need to get this structure from the // repository. // [odb]: http://libgit2.github.com/libgit2/#HEAD/group/odb git_odb *odb; git_repository_odb(&odb, repo); // #### Raw Object Reading printf("\n*Raw Object Read*\n"); git_odb_object *obj; git_otype otype; const unsigned char *data; const char *str_type; int error; // We can read raw objects directly from the object database if we have the oid (SHA) // of the object. This allows us to access objects without knowing thier type and inspect // the raw bytes unparsed. error = git_odb_read(&obj, odb, &oid); // A raw object only has three properties - the type (commit, blob, tree or tag), the size // of the raw data and the raw, unparsed data itself. For a commit or tag, that raw data // is human readable plain ASCII text. For a blob it is just file contents, so it could be // text or binary data. For a tree it is a special binary format, so it's unlikely to be // hugely helpful as a raw object. data = (const unsigned char *)git_odb_object_data(obj); otype = git_odb_object_type(obj); // We provide methods to convert from the object type which is an enum, to a string // representation of that value (and vice-versa). str_type = git_object_type2string(otype); printf("object length and type: %d, %s\n", (int)git_odb_object_size(obj), str_type); // For proper memory management, close the object when you are done with it or it will leak // memory. git_odb_object_free(obj); // #### Raw Object Writing printf("\n*Raw Object Write*\n"); // You can also write raw object data to Git. This is pretty cool because it gives you // direct access to the key/value properties of Git. Here we'll write a new blob object // that just contains a simple string. Notice that we have to specify the object type as // the `git_otype` enum. git_odb_write(&oid, odb, "test data", sizeof("test data") - 1, GIT_OBJ_BLOB); // Now that we've written the object, we can check out what SHA1 was generated when the // object was written to our database. git_oid_fmt(out, &oid); printf("Written Object: %s\n", out); // ### Object Parsing // libgit2 has methods to parse every object type in Git so you don't have to work directly // with the raw data. This is much faster and simpler than trying to deal with the raw data // yourself. // #### Commit Parsing // [Parsing commit objects][pco] is simple and gives you access to all the data in the commit // - the // author (name, email, datetime), committer (same), tree, message, encoding and parent(s). // [pco]: http://libgit2.github.com/libgit2/#HEAD/group/commit printf("\n*Commit Parsing*\n"); git_commit *commit; git_oid_fromstr(&oid, "f0877d0b841d75172ec404fc9370173dfffc20d1"); error = git_commit_lookup(&commit, repo, &oid); const git_signature *author, *cmtter; const char *message; time_t ctime; unsigned int parents, p; // Each of the properties of the commit object are accessible via methods, including commonly // needed variations, such as `git_commit_time` which returns the author time and `_message` // which gives you the commit message. message = git_commit_message(commit); author = git_commit_author(commit); cmtter = git_commit_committer(commit); ctime = git_commit_time(commit); // The author and committer methods return [git_signature] structures, which give you name, email // and `when`, which is a `git_time` structure, giving you a timestamp and timezone offset. printf("Author: %s (%s)\n", author->name, author->email); // Commits can have zero or more parents. The first (root) commit will have no parents, most commits // will have one, which is the commit it was based on, and merge commits will have two or more. // Commits can technically have any number, though it's pretty rare to have more than two. parents = git_commit_parentcount(commit); for (p = 0;p < parents;p++) { git_commit *parent; git_commit_parent(&parent, commit, p); git_oid_fmt(out, git_commit_id(parent)); printf("Parent: %s\n", out); git_commit_free(parent); } // Don't forget to close the object to prevent memory leaks. You will have to do this for // all the objects you open and parse. git_commit_free(commit); // #### Writing Commits // // libgit2 provides a couple of methods to create commit objects easily as well. There are four // different create signatures, we'll just show one of them here. You can read about the other // ones in the [commit API docs][cd]. // [cd]: http://libgit2.github.com/libgit2/#HEAD/group/commit printf("\n*Commit Writing*\n"); git_oid tree_id, parent_id, commit_id; git_tree *tree; git_commit *parent; // Creating signatures for an authoring identity and time is pretty simple - you will need to have // this to create a commit in order to specify who created it and when. Default values for the name // and email should be found in the `user.name` and `user.email` configuration options. See the `config` // section of this example file to see how to access config values. git_signature_new((git_signature **)&author, "Scott Chacon", "*****@*****.**", 123456789, 60); git_signature_new((git_signature **)&cmtter, "Scott A Chacon", "*****@*****.**", 987654321, 90); // Commit objects need a tree to point to and optionally one or more parents. Here we're creating oid // objects to create the commit with, but you can also use git_oid_fromstr(&tree_id, "28873d96b4e8f4e33ea30f4c682fd325f7ba56ac"); git_tree_lookup(&tree, repo, &tree_id); git_oid_fromstr(&parent_id, "f0877d0b841d75172ec404fc9370173dfffc20d1"); git_commit_lookup(&parent, repo, &parent_id); // Here we actually create the commit object with a single call with all the values we need to create // the commit. The SHA key is written to the `commit_id` variable here. git_commit_create_v( &commit_id, /* out id */ repo, NULL, /* do not update the HEAD */ author, cmtter, NULL, /* use default message encoding */ "example commit", tree, 1, parent); // Now we can take a look at the commit SHA we've generated. git_oid_fmt(out, &commit_id); printf("New Commit: %s\n", out); // #### Tag Parsing // You can parse and create tags with the [tag management API][tm], which functions very similarly // to the commit lookup, parsing and creation methods, since the objects themselves are very similar. // [tm]: http://libgit2.github.com/libgit2/#HEAD/group/tag printf("\n*Tag Parsing*\n"); git_tag *tag; const char *tmessage, *tname; git_otype ttype; // We create an oid for the tag object if we know the SHA and look it up in the repository the same // way that we would a commit (or any other) object. git_oid_fromstr(&oid, "bc422d45275aca289c51d79830b45cecebff7c3a"); error = git_tag_lookup(&tag, repo, &oid); // Now that we have the tag object, we can extract the information it generally contains: the target // (usually a commit object), the type of the target object (usually 'commit'), the name ('v1.0'), // the tagger (a git_signature - name, email, timestamp), and the tag message. git_tag_target((git_object **)&commit, tag); tname = git_tag_name(tag); // "test" ttype = git_tag_type(tag); // GIT_OBJ_COMMIT (otype enum) tmessage = git_tag_message(tag); // "tag message\n" printf("Tag Message: %s\n", tmessage); git_commit_free(commit); // #### Tree Parsing // [Tree parsing][tp] is a bit different than the other objects, in that we have a subtype which is the // tree entry. This is not an actual object type in Git, but a useful structure for parsing and // traversing tree entries. // // [tp]: http://libgit2.github.com/libgit2/#HEAD/group/tree printf("\n*Tree Parsing*\n"); const git_tree_entry *entry; git_object *objt; // Create the oid and lookup the tree object just like the other objects. git_oid_fromstr(&oid, "2a741c18ac5ff082a7caaec6e74db3075a1906b5"); git_tree_lookup(&tree, repo, &oid); // Getting the count of entries in the tree so you can iterate over them if you want to. int cnt = git_tree_entrycount(tree); // 3 printf("tree entries: %d\n", cnt); entry = git_tree_entry_byindex(tree, 0); printf("Entry name: %s\n", git_tree_entry_name(entry)); // "hello.c" // You can also access tree entries by name if you know the name of the entry you're looking for. entry = git_tree_entry_byname(tree, "hello.c"); git_tree_entry_name(entry); // "hello.c" // Once you have the entry object, you can access the content or subtree (or commit, in the case // of submodules) that it points to. You can also get the mode if you want. git_tree_entry_to_object(&objt, repo, entry); // blob // Remember to close the looked-up object once you are done using it git_object_free(objt); // #### Blob Parsing // // The last object type is the simplest and requires the least parsing help. Blobs are just file // contents and can contain anything, there is no structure to it. The main advantage to using the // [simple blob api][ba] is that when you're creating blobs you don't have to calculate the size // of the content. There is also a helper for reading a file from disk and writing it to the db and // getting the oid back so you don't have to do all those steps yourself. // // [ba]: http://libgit2.github.com/libgit2/#HEAD/group/blob printf("\n*Blob Parsing*\n"); git_blob *blob; git_oid_fromstr(&oid, "af7574ea73f7b166f869ef1a39be126d9a186ae0"); git_blob_lookup(&blob, repo, &oid); // You can access a buffer with the raw contents of the blob directly. // Note that this buffer may not be contain ASCII data for certain blobs (e.g. binary files): // do not consider the buffer a NULL-terminated string, and use the `git_blob_rawsize` attribute to // find out its exact size in bytes printf("Blob Size: %ld\n", git_blob_rawsize(blob)); // 8 git_blob_rawcontent(blob); // "content" // ### Revwalking // // The libgit2 [revision walking api][rw] provides methods to traverse the directed graph created // by the parent pointers of the commit objects. Since all commits point back to the commit that // came directly before them, you can walk this parentage as a graph and find all the commits that // were ancestors of (reachable from) a given starting point. This can allow you to create `git log` // type functionality. // // [rw]: http://libgit2.github.com/libgit2/#HEAD/group/revwalk printf("\n*Revwalking*\n"); git_revwalk *walk; git_commit *wcommit; git_oid_fromstr(&oid, "f0877d0b841d75172ec404fc9370173dfffc20d1"); // To use the revwalker, create a new walker, tell it how you want to sort the output and then push // one or more starting points onto the walker. If you want to emulate the output of `git log` you // would push the SHA of the commit that HEAD points to into the walker and then start traversing them. // You can also 'hide' commits that you want to stop at or not see any of their ancestors. So if you // want to emulate `git log branch1..branch2`, you would push the oid of `branch2` and hide the oid // of `branch1`. git_revwalk_new(&walk, repo); git_revwalk_sorting(walk, GIT_SORT_TOPOLOGICAL | GIT_SORT_REVERSE); git_revwalk_push(walk, &oid); const git_signature *cauth; const char *cmsg; // Now that we have the starting point pushed onto the walker, we can start asking for ancestors. It // will return them in the sorting order we asked for as commit oids. // We can then lookup and parse the commited pointed at by the returned OID; // note that this operation is specially fast since the raw contents of the commit object will // be cached in memory while ((git_revwalk_next(&oid, walk)) == 0) { error = git_commit_lookup(&wcommit, repo, &oid); cmsg = git_commit_message(wcommit); cauth = git_commit_author(wcommit); printf("%s (%s)\n", cmsg, cauth->email); git_commit_free(wcommit); } // Like the other objects, be sure to free the revwalker when you're done to prevent memory leaks. // Also, make sure that the repository being walked it not deallocated while the walk is in // progress, or it will result in undefined behavior git_revwalk_free(walk); // ### Index File Manipulation // // The [index file API][gi] allows you to read, traverse, update and write the Git index file // (sometimes thought of as the staging area). // // [gi]: http://libgit2.github.com/libgit2/#HEAD/group/index printf("\n*Index Walking*\n"); git_index *index; unsigned int i, ecount; // You can either open the index from the standard location in an open repository, as we're doing // here, or you can open and manipulate any index file with `git_index_open_bare()`. The index // for the repository will be located and loaded from disk. git_repository_index(&index, repo); // For each entry in the index, you can get a bunch of information including the SHA (oid), path // and mode which map to the tree objects that are written out. It also has filesystem properties // to help determine what to inspect for changes (ctime, mtime, dev, ino, uid, gid, file_size and flags) // All these properties are exported publicly in the `git_index_entry` struct ecount = git_index_entrycount(index); for (i = 0; i < ecount; ++i) { git_index_entry *e = git_index_get(index, i); printf("path: %s\n", e->path); printf("mtime: %d\n", (int)e->mtime.seconds); printf("fs: %d\n", (int)e->file_size); } git_index_free(index); // ### References // // The [reference API][ref] allows you to list, resolve, create and update references such as // branches, tags and remote references (everything in the .git/refs directory). // // [ref]: http://libgit2.github.com/libgit2/#HEAD/group/reference printf("\n*Reference Listing*\n"); // Here we will implement something like `git for-each-ref` simply listing out all available // references and the object SHA they resolve to. git_strarray ref_list; git_reference_list(&ref_list, repo, GIT_REF_LISTALL); const char *refname; git_reference *ref; // Now that we have the list of reference names, we can lookup each ref one at a time and // resolve them to the SHA, then print both values out. for (i = 0; i < ref_list.count; ++i) { refname = ref_list.strings[i]; git_reference_lookup(&ref, repo, refname); switch (git_reference_type(ref)) { case GIT_REF_OID: git_oid_fmt(out, git_reference_oid(ref)); printf("%s [%s]\n", refname, out); break; case GIT_REF_SYMBOLIC: printf("%s => %s\n", refname, git_reference_target(ref)); break; default: fprintf(stderr, "Unexpected reference type\n"); exit(1); } } git_strarray_free(&ref_list); // ### Config Files // // The [config API][config] allows you to list and updatee config values in // any of the accessible config file locations (system, global, local). // // [config]: http://libgit2.github.com/libgit2/#HEAD/group/config printf("\n*Config Listing*\n"); const char *email; int32_t j; git_config *cfg; // Open a config object so we can read global values from it. git_config_open_ondisk(&cfg, "~/.gitconfig"); git_config_get_int32(cfg, "help.autocorrect", &j); printf("Autocorrect: %d\n", j); git_config_get_string(cfg, "user.email", &email); printf("Email: %s\n", email); // Finally, when you're done with the repository, you can free it as well. git_repository_free(repo); return 0; }
static int http_negotiate_fetch(git_transport *transport, git_repository *repo, const git_vector *wants) { transport_http *t = (transport_http *) transport; int ret; unsigned int i; char buff[128]; gitno_buffer buf; git_revwalk *walk = NULL; git_oid oid; git_pkt_ack *pkt; git_vector *common = &t->common; git_buf request = GIT_BUF_INIT, data = GIT_BUF_INIT; gitno_buffer_setup(transport, &buf, buff, sizeof(buff)); if (git_vector_init(common, 16, NULL) < 0) return -1; if (git_fetch_setup_walk(&walk, repo) < 0) return -1; do { if ((ret = do_connect(t, t->host, t->port)) < 0) goto cleanup; if ((ret = git_pkt_buffer_wants(wants, &t->caps, &data)) < 0) goto cleanup; /* We need to send these on each connection */ git_vector_foreach (common, i, pkt) { if ((ret = git_pkt_buffer_have(&pkt->oid, &data)) < 0) goto cleanup; } i = 0; while ((i < 20) && ((ret = git_revwalk_next(&oid, walk)) == 0)) { if ((ret = git_pkt_buffer_have(&oid, &data)) < 0) goto cleanup; i++; } git_pkt_buffer_done(&data); if ((ret = gen_request(&request, t->path, t->host, "POST", "upload-pack", data.size, 0)) < 0) goto cleanup; if ((ret = gitno_send(transport, request.ptr, request.size, 0)) < 0) goto cleanup; if ((ret = gitno_send(transport, data.ptr, data.size, 0)) < 0) goto cleanup; git_buf_clear(&request); git_buf_clear(&data); if (ret < 0 || i >= 256) break; if ((ret = parse_response(t)) < 0) goto cleanup; if (t->pack_ready) { ret = 0; goto cleanup; } } while(1); cleanup: git_buf_free(&request); git_buf_free(&data); git_revwalk_free(walk); return ret; }
int cmd_rev_list(git_repository *repo, int argc, char **argv) { const char *commit_string = NULL; const char *format = NULL; int i = 0; git_oid commit_oid; git_oid current_oid; char current_oid_str[GIT_OID_HEXSZ+1]; int err = 0; int rc = EXIT_FAILURE; git_commit *commit; git_revwalk *walk; for (i = 1; i < argc; i++) { if (*argv[i] == '-') { if (!prefixcmp(argv[i], "--pretty=")) { format = argv[i] + strlen("--pretty="); } else { fprintf(stderr,"Unknown option \"%s\"\n",argv[i]); goto out; } } else { commit_string = argv[i]; } } if (!commit_string) { fprintf(stderr,"No commit id given!\n"); goto out; } if (format) { fprintf(stderr,"Format \"%s\" not supported!\n",format); goto out; } if ((err = git_oid_fromstrn(&commit_oid,commit_string,strlen(commit_string))) != GIT_OK) goto out; if ((err = git_commit_lookup_prefix(&commit,repo,&commit_oid,strlen(commit_string))) != GIT_OK) goto out; if ((err = git_revwalk_new(&walk, repo)) != GIT_OK) goto out; git_revwalk_sorting(walk, GIT_SORT_TIME); if ((err = git_revwalk_push(walk, &commit_oid)) != GIT_OK) goto out; while ((git_revwalk_next(¤t_oid, walk)) == GIT_OK) { struct git_commit *wcommit; if (git_commit_lookup(&wcommit, repo, ¤t_oid) != 0) continue; git_oid_tostr(current_oid_str,sizeof(current_oid_str),¤t_oid); printf("%s\n",current_oid_str); git_commit_free(wcommit); } git_revwalk_free(walk); out: if (err) libgit_error(); if (commit) git_commit_free(commit); return rc; }