Example #1
0
int
Repository_contains(Repository *self, PyObject *value)
{
    git_oid oid;
    git_odb *odb;
    int err, len, exists;

    len = py_str_to_git_oid(value, &oid);
    if (len < 0)
        return -1;

    err = git_repository_odb(&odb, self->repo);
    if (err < 0) {
        Error_set(err);
        return -1;
    }

    if (len < GIT_OID_HEXSZ) {
        git_odb_object *obj = NULL;
        err = git_odb_read_prefix(&obj, odb, &oid, len);
        if (err < 0 && err != GIT_ENOTFOUND) {
            Error_set(err);
            exists = -1;
        } else {
            exists = (err == 0);
            if (obj)
                git_odb_object_free(obj);
        }
    } else {
        exists = git_odb_exists(odb, &oid);
    }

    git_odb_free(odb);
    return exists;
}
Example #2
0
int git_revwalk_new(git_revwalk **revwalk_out, git_repository *repo)
{
	git_revwalk *walk = git__calloc(1, sizeof(git_revwalk));
	GITERR_CHECK_ALLOC(walk);

	walk->commits = git_oidmap_alloc();
	GITERR_CHECK_ALLOC(walk->commits);

	if (git_pqueue_init(
			&walk->iterator_time, 0, 8, git_commit_list_time_cmp) < 0 ||
		git_pool_init(&walk->commit_pool, 1,
			git_pool__suggest_items_per_page(COMMIT_ALLOC) * COMMIT_ALLOC) < 0)
		return -1;

	walk->get_next = &revwalk_next_unsorted;
	walk->enqueue = &revwalk_enqueue_unsorted;

	walk->repo = repo;

	if (git_repository_odb(&walk->odb, repo) < 0) {
		git_revwalk_free(walk);
		return -1;
	}

	*revwalk_out = walk;
	return 0;
}
Example #3
0
static int
checksum_submodule (struct TreeWalkData *parent_twdata, git_submodule *sub)
{
  int r = 1;
  const git_oid *sub_head;
  struct TreeWalkData child_twdata = { FALSE, parent_twdata->evtag, NULL, NULL,
                                       parent_twdata->cancellable,
                                       parent_twdata->error };

  parent_twdata->evtag->n_submodules++;
  
  r = git_submodule_open (&child_twdata.repo, sub);
  if (!handle_libgit_ret (r, child_twdata.error))
    goto out;

  r = git_repository_odb (&child_twdata.odb, child_twdata.repo);
  if (!handle_libgit_ret (r, child_twdata.error))
    goto out;

  sub_head = git_submodule_wd_id (sub);

  if (!checksum_commit_contents (&child_twdata, sub_head,
                                 child_twdata.cancellable, child_twdata.error))
    goto out;

  r = 0;
 out:
  if (r > 0)
    child_twdata.caught_error = TRUE;
  if (child_twdata.repo)
    git_repository_free (child_twdata.repo);
  if (child_twdata.odb)
    git_odb_free (child_twdata.odb);
  return r;
}
Example #4
0
int git_merge_file_input_from_diff_file(
	git_merge_file_input *input,
	git_repository *repo,
	const git_diff_file *file)
{
	git_odb *odb = NULL;
	int error = 0;

	assert(input && repo && file);

	if (file->mode == 0)
		return 0;

	if ((error = git_repository_odb(&odb, repo)) < 0 ||
		(error = git_odb_read(&input->odb_object, odb, &file->oid)) < 0)
		goto done;

	input->mode = file->mode;
	input->path = git__strdup(file->path);
	input->mmfile.size = git_odb_object_size(input->odb_object);
	input->mmfile.ptr = (char *)git_odb_object_data(input->odb_object);

	if (input->label == NULL)
		input->label = file->path;

done:
	git_odb_free(odb);

	return error;
}
Example #5
0
File: oid.c Project: cholin/pygit2
int
py_str_to_git_oid_expand(git_repository *repo, PyObject *py_str, git_oid *oid)
{
    int err;
    int len;
    git_odb *odb;
    git_odb_object *obj;

    len = py_str_to_git_oid(py_str, oid);

    if (len == GIT_OID_HEXSZ || len < 0)
        return len;

    err = git_repository_odb(&odb, repo);
    if (err < 0) {
        Error_set(err);
        return -1;
    }

    err = git_odb_read_prefix(&obj, odb, oid, len);
    if (err < 0) {
        git_odb_free(odb);
        Error_set(err);
        return err;
    }

    git_oid_cpy(oid, git_odb_object_id(obj));

    git_odb_object_free(obj);
    git_odb_free(odb);

    return 0;
}
Example #6
0
void test_pack_indexer__corrupt_length(void)
{
	git_indexer *idx = NULL;
	git_transfer_progress stats = { 0 };
	git_repository *repo;
	git_odb *odb;
	git_oid id, should_id;

	cl_git_pass(git_repository_init(&repo, "thin.git", true));
	cl_git_pass(git_repository_odb(&odb, repo));

	/* Store the missing base into your ODB so the indexer can fix the pack */
	cl_git_pass(git_odb_write(&id, odb, base_obj, base_obj_len, GIT_OBJ_BLOB));
	git_oid_fromstr(&should_id, "e68fe8129b546b101aee9510c5328e7f21ca1d18");
	cl_assert_equal_oid(&should_id, &id);

	cl_git_pass(git_indexer_new(&idx, ".", 0, odb, NULL, NULL));
	cl_git_pass(git_indexer_append(
		idx, corrupt_thin_pack, corrupt_thin_pack_len, &stats));
	cl_git_fail(git_indexer_commit(idx, &stats));

	cl_assert(giterr_last() != NULL);
	cl_assert_equal_i(giterr_last()->klass, GITERR_ZLIB);

	git_indexer_free(idx);
	git_odb_free(odb);
	git_repository_free(repo);
}
Example #7
0
static void *cache_raw(void *arg)
{
	int i;
	git_oid oid;
	git_odb *odb;
	git_odb_object *odb_obj;

	cl_git_pass(git_repository_odb(&odb, g_repo));

	for (i = ((int *)arg)[1]; g_data[i].sha != NULL; i += 2) {
		cl_git_pass(git_oid_fromstr(&oid, g_data[i].sha));
		cl_git_pass(git_odb_read(&odb_obj, odb, &oid));
		cl_assert(g_data[i].type == git_odb_object_type(odb_obj));
		git_odb_object_free(odb_obj);
	}

	for (i = 0; i < ((int *)arg)[1]; i += 2) {
		cl_git_pass(git_oid_fromstr(&oid, g_data[i].sha));
		cl_git_pass(git_odb_read(&odb_obj, odb, &oid));
		cl_assert(g_data[i].type == git_odb_object_type(odb_obj));
		git_odb_object_free(odb_obj);
	}

	git_odb_free(odb);

	return arg;
}
Example #8
0
int
py_oid_to_git_oid_expand(git_repository *repo, PyObject *py_str, git_oid *oid)
{
    int err;
    size_t len;
    git_odb *odb = NULL;
    git_odb_object *obj = NULL;

    len = py_oid_to_git_oid(py_str, oid);
    if (len == 0)
        return -1;

    if (len == GIT_OID_HEXSZ)
        return 0;

    /* Short oid */
    err = git_repository_odb(&odb, repo);
    if (err < 0)
        goto error;

    err = git_odb_read_prefix(&obj, odb, oid, len);
    if (err < 0)
        goto error;

    git_oid_cpy(oid, git_odb_object_id(obj));
    git_odb_object_free(obj);
    git_odb_free(odb);
    return 0;

error:
    git_odb_object_free(obj);
    git_odb_free(odb);
    Error_set(err);
    return -1;
}
Example #9
0
static gboolean
checksum_commit_recurse (struct EvTag      *self,
                         git_oid           *specified_oid,
                         guint64           *out_elapsed_time,
                         GCancellable      *cancellable,
                         GError           **error)
{
  gboolean ret = FALSE;
  int r;
  guint64 checksum_start_time;
  guint64 checksum_end_time;
                         
  checksum_start_time = g_get_monotonic_time ();
  {
    struct TreeWalkData twdata = { FALSE, self, self->top_repo, NULL, cancellable, error };
    
    r = git_repository_odb (&twdata.odb, self->top_repo);
    if (!handle_libgit_ret (r, error))
      goto out;
    
    if (!checksum_commit_contents (&twdata, specified_oid, cancellable, error))
      goto out;
  }
  checksum_end_time = g_get_monotonic_time ();

  ret = TRUE;
  if (out_elapsed_time)
    *out_elapsed_time = checksum_end_time - checksum_start_time;
 out:
  return ret;
}
Example #10
0
File: git.c Project: ileitch/meanie
void mne_git_load_blobs(const char *path) {
  mne_git_initialize();

  printf("\nLoading blobs...\n\n");
  gettimeofday(&begin, NULL);

  git_repository_open(&repo, path);
  git_repository_odb(&odb, repo);

  git_strarray tag_names;
  git_tag_list(&tag_names, repo);

  total_refs = tag_names.count + 1; /* + 1 for HEAD. */
  ref_names = malloc(sizeof(char*) * total_refs);

  mne_git_walk_ctx ctx;
  ctx.bytes = 0;
  ctx.ref_index = 0;
  
  mne_git_walk_head(&ctx);
  mne_git_walk_tags(&ctx, &tag_names);

  git_strarray_free(&tag_names);
  git_repository_free(repo);

  gettimeofday(&end, NULL);

  float mb = ctx.bytes / 1048576.0;
  printf("\nLoaded %d blobs (%.2fmb) ", g_hash_table_size(blobs), mb);
  mne_print_duration(&end, &begin);
  printf(".\n");
}
Example #11
0
PyObject *
Repository_write(Repository *self, PyObject *args)
{
    int err;
    git_oid oid;
    git_odb *odb;
    git_odb_stream* stream;
    int type_id;
    const char* buffer;
    Py_ssize_t buflen;
    git_otype type;

    if (!PyArg_ParseTuple(args, "Is#", &type_id, &buffer, &buflen))
        return NULL;

    type = int_to_loose_object_type(type_id);
    if (type == GIT_OBJ_BAD)
        return PyErr_Format(PyExc_ValueError, "%d", type_id);

    err = git_repository_odb(&odb, self->repo);
    if (err < 0)
        return Error_set(err);

    err = git_odb_open_wstream(&stream, odb, buflen, type);
    git_odb_free(odb);
    if (err < 0)
        return Error_set(err);

    stream->write(stream, buffer, buflen);
    err = stream->finalize_write(&oid, stream);
    stream->free(stream);
    return git_oid_to_python(oid.id);
}
Example #12
0
/*
 * $ git --git-dir tests-clar/resources/testrepo.git count-objects --verbose
 * count: 43
 * size: 3
 * in-pack: 1640
 * packs: 3
 * size-pack: 425
 * prune-packable: 0
 * garbage: 0
 */
void test_odb_foreach__foreach(void)
{
	cl_git_pass(git_repository_open(&_repo, cl_fixture("testrepo.git")));
	git_repository_odb(&_odb, _repo);

	cl_git_pass(git_odb_foreach(_odb, foreach_cb, NULL));
	cl_assert_equal_i(46 + 1640, nobj); /* count + in-pack */
}
Example #13
0
void test_index_collision__initialize(void)
{
	g_repo = cl_git_sandbox_init("empty_standard_repo");
	cl_git_pass(git_repository_odb(&g_odb, g_repo));
	cl_git_pass(git_repository_index(&g_index, g_repo));

	cl_git_pass(git_odb_write(&g_empty_id, g_odb, "", 0, GIT_OBJ_BLOB));
}
Example #14
0
void test_odb_foreach__interrupt_foreach(void)
{
	nobj = 0;
	cl_git_pass(git_repository_open(&_repo, cl_fixture("testrepo.git")));
	git_repository_odb(&_odb, _repo);

	cl_assert_equal_i(GIT_EUSER, git_odb_foreach(_odb, foreach_stop_cb, NULL));
	cl_assert(nobj == 1000);
}
Example #15
0
void test_odb_foreach__interrupt_foreach(void)
{
	int nobj = 0;
	git_oid id;

	cl_git_pass(git_repository_open(&_repo, cl_fixture("testrepo.git")));
	git_repository_odb(&_odb, _repo);

	cl_assert_equal_i(-321, git_odb_foreach(_odb, foreach_stop_cb, &nobj));
	cl_assert(nobj == 1000);

	git_odb_free(_odb);
	git_repository_free(_repo);

	cl_git_pass(git_repository_init(&_repo, "onlyloose.git", true));
	git_repository_odb(&_odb, _repo);

	cl_git_pass(git_odb_write(&id, _odb, "", 0, GIT_OBJECT_BLOB));
	cl_assert_equal_i(-123, git_odb_foreach(_odb, foreach_stop_first_cb, &nobj));
}
Example #16
0
int repository_create_memory_cb(git_repository **out, const char *path, int bare, void *payload) {
    git_odb *odb = NULL;
    git_odb_backend *odb_mem = NULL;
    int error;
    if (    (error = git_repository_init(out, path, bare)) ||
            (error = git_repository_odb(&odb, *out)) ||
            (error = git_odb_backend_memory(&odb_mem)) ||
            (error = git_odb_add_backend(odb, odb_mem, 999))) {
        // TODO: free?
        return error;
    }
    return GIT_OK;
}
Example #17
0
void test_odb_backend_nobackend__write_fails_gracefully(void)
{
	git_oid id;
	git_odb *odb;
	const git_error *err;

	git_repository_odb(&odb, _repo);
	cl_git_fail(git_odb_write(&id, odb, "Hello world!\n", 13, GIT_OBJ_BLOB));

	err = giterr_last();
	cl_assert_equal_s(err->message, "cannot write object - unsupported in the loaded odb backends");

	git_odb_free(odb);
}
Example #18
0
void test_object_cache__cache_everything(void)
{
	int i, start;
	git_oid oid;
	git_odb_object *odb_obj;
	git_object *obj;
	git_odb *odb;

	git_libgit2_opts(
		GIT_OPT_SET_CACHE_OBJECT_LIMIT, (int)GIT_OBJ_BLOB, (size_t)32767);

	cl_git_pass(git_repository_open(&g_repo, cl_fixture("testrepo.git")));
	cl_git_pass(git_repository_odb(&odb, g_repo));

	start = (int)git_cache_size(&g_repo->objects);

	for (i = 0; g_data[i].sha != NULL; ++i) {
		int count = (int)git_cache_size(&g_repo->objects);

		cl_git_pass(git_oid_fromstr(&oid, g_data[i].sha));

		/* alternate between loading raw and parsed objects */
		if ((i & 1) == 0) {
			cl_git_pass(git_odb_read(&odb_obj, odb, &oid));
			cl_assert(g_data[i].type == git_odb_object_type(odb_obj));
			git_odb_object_free(odb_obj);
		} else {
			cl_git_pass(git_object_lookup(&obj, g_repo, &oid, GIT_OBJ_ANY));
			cl_assert(g_data[i].type == git_object_type(obj));
			git_object_free(obj);
		}

		cl_assert_equal_i(count + 1, (int)git_cache_size(&g_repo->objects));
	}

	cl_assert_equal_i(i, (int)git_cache_size(&g_repo->objects) - start);

	git_odb_free(odb);

	for (i = 0; g_data[i].sha != NULL; ++i) {
		int count = (int)git_cache_size(&g_repo->objects);

		cl_git_pass(git_oid_fromstr(&oid, g_data[i].sha));
		cl_git_pass(git_object_lookup(&obj, g_repo, &oid, GIT_OBJ_ANY));
		cl_assert(g_data[i].type == git_object_type(obj));
		git_object_free(obj);

		cl_assert_equal_i(count, (int)git_cache_size(&g_repo->objects));
	}
}
Example #19
0
static void commit_result(char* msg, git_oid *commit){
    git_odb *odb;

    check_lg2(git_repository_odb(&odb, repo),
              "Could not allocate odb poiner", NULL);

    check_lg2(git_odb_write(commit, odb, &msg[PREAMBLE_LENGTH], MSG_LENGTH, GIT_OBJ_COMMIT),
              "Error writing commit", NULL);

    check_lg2(git_reference_create(NULL, repo, "refs/heads/master", commit, 1),
              "Could not update head", NULL);

    git_odb_free(odb);
}
Example #20
0
void test_repo_getters__retrieving_the_odb_honors_the_refcount(void)
{
	git_odb *odb;
	git_repository *repo;

	cl_git_pass(git_repository_open(&repo, "testrepo.git"));

	cl_git_pass(git_repository_odb(&odb, repo));
	cl_assert(((git_refcount *)odb)->refcount == 2);

	git_repository_free(repo);
	cl_assert(((git_refcount *)odb)->refcount == 1);

	git_odb_free(odb);
}
Example #21
0
int cmd_write_tree(int argc, const char **argv)
{
	please_git_do_it_for_me();

	int verify_index = 1;
	if (argc == 1)
		verify_index = 1;
	else if (argc == 2 && strcmp(argv[1], "--missing-ok") == 0 )
		verify_index = 0;
	else
		please_git_do_it_for_me();
	

	char sha1buf[GIT_OID_HEXSZ + 1];

	git_repository *repo = get_git_repository();
	git_index *index_cur;
	int e = git_repository_index(&index_cur, repo);
	if(e != GIT_OK)
		libgit_error();

	/* check the index */
	if (verify_index) {
		git_odb * odb;
		git_repository_odb(&odb, repo);
		for (unsigned i = 0; i < git_index_entrycount(index_cur); i++) {
			git_index_entry *gie = git_index_get(index_cur, i);

			if (git_odb_exists(odb, &gie->oid) != 1) {
				printf("error: invalid object %06o %s for '%s'\n", gie->mode, git_oid_tostr(sha1buf, GIT_OID_HEXSZ+1, &gie->oid), gie->path);
				printf("fatal: git-write-tree: error building trees\n");
				return EXIT_FAILURE;
			}
		}
	}
	
	/* create the tree */
	git_oid oid;
	e = git_tree_create_fromindex(&oid, index_cur);
	if(e != GIT_OK)
		libgit_error();

	printf("%s\n", git_oid_tostr(sha1buf, GIT_OID_HEXSZ+1, &oid));

	return EXIT_SUCCESS;
}
Example #22
0
void test_clone_nonetwork__clone_tag_to_tree(void)
{
	git_repository *stage;
	git_index_entry entry;
	git_index *index;
	git_odb *odb;
	git_oid tree_id;
	git_tree *tree;
	git_reference *tag;
	git_tree_entry *tentry;
	const char *file_path = "some/deep/path.txt";
	const char *file_content = "some content\n";
	const char *tag_name = "refs/tags/tree-tag";

	stage = cl_git_sandbox_init("testrepo.git");
	cl_git_pass(git_repository_odb(&odb, stage));
	cl_git_pass(git_index_new(&index));

	memset(&entry, 0, sizeof(git_index_entry));
	entry.path = file_path;
	entry.mode = GIT_FILEMODE_BLOB;
	cl_git_pass(git_odb_write(&entry.id, odb, file_content, strlen(file_content), GIT_OBJ_BLOB));

	cl_git_pass(git_index_add(index, &entry));
	cl_git_pass(git_index_write_tree_to(&tree_id, index, stage));
	cl_git_pass(git_reference_create(&tag, stage, tag_name, &tree_id, 0, NULL));
	git_reference_free(tag);
	git_odb_free(odb);
	git_index_free(index);

	g_options.local = GIT_CLONE_NO_LOCAL;
	cl_git_pass(git_clone(&g_repo, cl_git_path_url(git_repository_path(stage)), "./foo", &g_options));
	git_repository_free(stage);

	cl_git_pass(git_reference_lookup(&tag, g_repo, tag_name));
	cl_git_pass(git_tree_lookup(&tree, g_repo, git_reference_target(tag)));
	git_reference_free(tag);

	cl_git_pass(git_tree_entry_bypath(&tentry, tree, file_path));
	git_tree_entry_free(tentry);
	git_tree_free(tree);

	cl_fixture_cleanup("testrepo.git");
}
Example #23
0
PyObject *
Repository_as_iter(Repository *self)
{
    git_odb *odb;
    int err;
    PyObject *accum = PyList_New(0);

    err = git_repository_odb(&odb, self->repo);
    if (err < 0)
        return Error_set(err);

    err = git_odb_foreach(odb, Repository_build_as_iter, (void*)accum);
    git_odb_free(odb);
    if (err == GIT_EUSER)
        return NULL;
    if (err < 0)
        return Error_set(err);

    return PyObject_GetIter(accum);
}
Example #24
0
int git_object_short_id(git_buf *out, const git_object *obj)
{
	git_repository *repo;
	int len = GIT_ABBREV_DEFAULT, error;
	git_oid id = {{0}};
	git_odb *odb;

	assert(out && obj);

	git_buf_sanitize(out);
	repo = git_object_owner(obj);

	if ((error = git_repository__cvar(&len, repo, GIT_CVAR_ABBREV)) < 0)
		return error;

	if ((error = git_repository_odb(&odb, repo)) < 0)
		return error;

	while (len < GIT_OID_HEXSZ) {
		/* set up short oid */
		memcpy(&id.id, &obj->cached.oid.id, (len + 1) / 2);
		if (len & 1)
			id.id[len / 2] &= 0xf0;

		error = git_odb_exists_prefix(NULL, odb, &id, len);
		if (error != GIT_EAMBIGUOUS)
			break;

		giterr_clear();
		len++;
	}

	if (!error && !(error = git_buf_grow(out, len + 1))) {
		git_oid_tostr(out->ptr, len + 1, &id);
		out->size = len;
	}

	git_odb_free(odb);

	return error;
}
Example #25
0
git_odb_object *
Repository_read_raw(git_repository *repo, const git_oid *oid, size_t len)
{
    git_odb *odb;
    git_odb_object *obj;
    int err;

    err = git_repository_odb(&odb, repo);
    if (err < 0) {
        Error_set(err);
        return NULL;
    }

    err = git_odb_read_prefix(&obj, odb, oid, (unsigned int)len);
    git_odb_free(odb);
    if (err < 0) {
        Error_set_oid(err, oid, len);
        return NULL;
    }

    return obj;
}
Example #26
0
void test_odb_foreach__files_in_objects_dir(void)
{
	git_repository *repo;
	git_odb *odb;
	git_buf buf = GIT_BUF_INIT;
	int nobj = 0;

	cl_fixture_sandbox("testrepo.git");
	cl_git_pass(git_repository_open(&repo, "testrepo.git"));

	cl_git_pass(git_buf_printf(&buf, "%s/objects/somefile", git_repository_path(repo)));
	cl_git_mkfile(buf.ptr, "");
	git_buf_dispose(&buf);

	cl_git_pass(git_repository_odb(&odb, repo));
	cl_git_pass(git_odb_foreach(odb, foreach_cb, &nobj));
	cl_assert_equal_i(60 + 1640, nobj); /* count + in-pack */

	git_odb_free(odb);
	git_repository_free(repo);
	cl_fixture_cleanup("testrepo.git");
}
Example #27
0
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;
}
Example #28
0
/* The wiki handler */
static int wiki_handler(request_rec *r)
{
    wiki_conf *conf;
    git_repository *repo;
    const git_oid *tree_oid;
    char *path;

    const git_oid *oid;
    char hash[41];
    hash[40] = '\0';
    int ret;
    int type;

    MMIOT *doc;

    if (strcmp(r->handler, "wiki")) {
        return DECLINED;
    }

    if (r->header_only) {
        return OK;
    }

    conf =
        (wiki_conf *) ap_get_module_config(r->per_dir_config,
                                           &wiki_module);

    ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r, "filename=%s",
                  r->filename);
    if (conf->basepath) {
        path = ltrim(conf->basepath, r->parsed_uri.path);
    } else {
        path = r->parsed_uri.path + 1;
    }

    ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r, "path=%s", path);
    ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r,
                  "r->content_type=%s", r->content_type);

    if (conf->repo == NULL) {
        ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r,
                      "WikiRepository is not set.");
        return HTTP_INTERNAL_SERVER_ERROR;
    }
    ret = git_repository_open(&repo, conf->repo);
    if (ret) {
        ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r,
                      "Cannot open git repository.(%s)", conf->repo);
        return HTTP_INTERNAL_SERVER_ERROR;
    }

    tree_oid = lookup_master_tree(repo);
    if (tree_oid == NULL) {
        ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r,
                      "Not found master tree.");
        git_repository_free(repo);
    }

    type = lookup_object_oid(r, repo, tree_oid, path, &oid);
    if (type == WIKI_NOTFOUND) {
        ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r,
                      "Object is not found.");
        git_repository_free(repo);
        return HTTP_NOT_FOUND;
    } else if(type == WIKI_DIR) {
        ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
                      "Directory listing is not implement yet.");
        git_repository_free(repo);
        return HTTP_FORBIDDEN;
    } else if(type == WIKI_ERROR) {
        ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
                      "Error at lookup.");
        git_repository_free(repo);
        return HTTP_NOT_FOUND;
    }

    git_oid_fmt(hash, oid);
    ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r, "object hash=%s", hash);

    const char *data;
    size_t size;

    git_odb *odb;
    ret = git_repository_odb(&odb, repo);
    git_odb_object *odb_object;
    ret = git_odb_read(&odb_object, odb, oid);
    data = git_odb_object_data(odb_object);
    size = git_odb_object_size(odb_object);

    git_odb_object_free(odb_object);	// is this safe?

    if (type == WIKI_FOUND) {
        ap_rwrite(data, size, r);
    } else if(type == WIKI_MARKDOWN) {
        r->content_type = "text/html";
        doc = mkd_string(data, size, 0);
        if (doc == NULL) {
            ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
                          "mkd_string() returned NULL\n");
            git_repository_free(repo);
            return HTTP_INTERNAL_SERVER_ERROR;
        }
        wiki_output(doc, r);
        mkd_cleanup(doc);
    } else {
        ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
                      "Unknown Error.\n");
        git_repository_free(repo);
        return HTTP_INTERNAL_SERVER_ERROR;
    }

    git_repository_free(repo);
    return OK;
}
Example #29
0
int git_blob__create_from_paths(
	git_oid *id,
	struct stat *out_st,
	git_repository *repo,
	const char *content_path,
	const char *hint_path,
	mode_t hint_mode,
	bool try_load_filters)
{
	int error;
	struct stat st;
	git_odb *odb = NULL;
	git_off_t size;
	mode_t mode;
	git_buf path = GIT_BUF_INIT;

	assert(hint_path || !try_load_filters);

	if (!content_path) {
		if (git_repository__ensure_not_bare(repo, "create blob from file") < 0)
			return GIT_EBAREREPO;

		if (git_buf_joinpath(
				&path, git_repository_workdir(repo), hint_path) < 0)
			return -1;

		content_path = path.ptr;
	}

	if ((error = git_path_lstat(content_path, &st)) < 0 ||
		(error = git_repository_odb(&odb, repo)) < 0)
		goto done;

	if (S_ISDIR(st.st_mode)) {
		giterr_set(GITERR_ODB, "cannot create blob from '%s': it is a directory", content_path);
		error = GIT_EDIRECTORY;
		goto done;
	}

	if (out_st)
		memcpy(out_st, &st, sizeof(st));

	size = st.st_size;
	mode = hint_mode ? hint_mode : st.st_mode;

	if (S_ISLNK(mode)) {
		error = write_symlink(id, odb, content_path, (size_t)size);
	} else {
		git_filter_list *fl = NULL;

		if (try_load_filters)
			/* Load the filters for writing this file to the ODB */
			error = git_filter_list_load(
				&fl, repo, NULL, hint_path,
				GIT_FILTER_TO_ODB, GIT_FILTER_DEFAULT);

		if (error < 0)
			/* well, that didn't work */;
		else if (fl == NULL)
			/* No filters need to be applied to the document: we can stream
			 * directly from disk */
			error = write_file_stream(id, odb, content_path, size);
		else {
			/* We need to apply one or more filters */
			error = write_file_filtered(id, &size, odb, content_path, fl);

			git_filter_list_free(fl);
		}

		/*
		 * TODO: eventually support streaming filtered files, for files
		 * which are bigger than a given threshold. This is not a priority
		 * because applying a filter in streaming mode changes the final
		 * size of the blob, and without knowing its final size, the blob
		 * cannot be written in stream mode to the ODB.
		 *
		 * The plan is to do streaming writes to a tempfile on disk and then
		 * opening streaming that file to the ODB, using
		 * `write_file_stream`.
		 *
		 * CAREFULLY DESIGNED APIS YO
		 */
	}

done:
	git_odb_free(odb);
	git_buf_dispose(&path);

	return error;
}
Example #30
0
void test_odb_largefiles__initialize(void)
{
	repo = cl_git_sandbox_init("testrepo.git");
	cl_git_pass(git_repository_odb(&odb, repo));
}