Unnamed: 0
int64 0
0
| repo_id
stringlengths 5
186
| file_path
stringlengths 15
223
| content
stringlengths 1
32.8M
⌀ |
---|---|---|---|
0 |
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2
|
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2/src/patch_parse.h
|
/*
* Copyright (C) the libgit2 contributors. All rights reserved.
*
* This file is part of libgit2, distributed under the GNU GPL v2 with
* a Linking Exception. For full terms see the included COPYING file.
*/
#ifndef INCLUDE_patch_parse_h__
#define INCLUDE_patch_parse_h__
#include "common.h"
#include "parse.h"
#include "patch.h"
typedef struct {
git_refcount rc;
git_patch_options opts;
git_parse_ctx parse_ctx;
} git_patch_parse_ctx;
extern git_patch_parse_ctx *git_patch_parse_ctx_init(
const char *content,
size_t content_len,
const git_patch_options *opts);
extern void git_patch_parse_ctx_free(git_patch_parse_ctx *ctx);
/**
* Create a patch for a single file from the contents of a patch buffer.
*
* @param out The patch to be created
* @param contents The contents of a patch file
* @param contents_len The length of the patch file
* @param opts The git_patch_options
* @return 0 on success, <0 on failure.
*/
extern int git_patch_from_buffer(
git_patch **out,
const char *contents,
size_t contents_len,
const git_patch_options *opts);
extern int git_patch_parse(
git_patch **out,
git_patch_parse_ctx *ctx);
extern int git_patch_parsed_from_diff(git_patch **, git_diff *, size_t);
#endif
|
0 |
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2
|
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2/src/rebase.c
|
/*
* Copyright (C) the libgit2 contributors. All rights reserved.
*
* This file is part of libgit2, distributed under the GNU GPL v2 with
* a Linking Exception. For full terms see the included COPYING file.
*/
#include "common.h"
#include "buffer.h"
#include "repository.h"
#include "posix.h"
#include "filebuf.h"
#include "merge.h"
#include "array.h"
#include "config.h"
#include "annotated_commit.h"
#include "index.h"
#include <git2/types.h>
#include <git2/annotated_commit.h>
#include <git2/rebase.h>
#include <git2/commit.h>
#include <git2/reset.h>
#include <git2/revwalk.h>
#include <git2/notes.h>
#define REBASE_APPLY_DIR "rebase-apply"
#define REBASE_MERGE_DIR "rebase-merge"
#define HEAD_NAME_FILE "head-name"
#define ORIG_HEAD_FILE "orig-head"
#define HEAD_FILE "head"
#define ONTO_FILE "onto"
#define ONTO_NAME_FILE "onto_name"
#define QUIET_FILE "quiet"
#define MSGNUM_FILE "msgnum"
#define END_FILE "end"
#define CMT_FILE_FMT "cmt.%" PRIuZ
#define CURRENT_FILE "current"
#define REWRITTEN_FILE "rewritten"
#define ORIG_DETACHED_HEAD "detached HEAD"
#define NOTES_DEFAULT_REF NULL
#define REBASE_DIR_MODE 0777
#define REBASE_FILE_MODE 0666
typedef enum {
GIT_REBASE_NONE = 0,
GIT_REBASE_APPLY = 1,
GIT_REBASE_MERGE = 2,
GIT_REBASE_INTERACTIVE = 3,
} git_rebase_t;
struct git_rebase {
git_repository *repo;
git_rebase_options options;
git_rebase_t type;
char *state_path;
int head_detached : 1,
inmemory : 1,
quiet : 1,
started : 1;
git_array_t(git_rebase_operation) operations;
size_t current;
/* Used by in-memory rebase */
git_index *index;
git_commit *last_commit;
/* Used by regular (not in-memory) merge-style rebase */
git_oid orig_head_id;
char *orig_head_name;
git_oid onto_id;
char *onto_name;
};
#define GIT_REBASE_STATE_INIT {0}
static int rebase_state_type(
git_rebase_t *type_out,
char **path_out,
git_repository *repo)
{
git_buf path = GIT_BUF_INIT;
git_rebase_t type = GIT_REBASE_NONE;
if (git_buf_joinpath(&path, repo->gitdir, REBASE_APPLY_DIR) < 0)
return -1;
if (git_path_isdir(git_buf_cstr(&path))) {
type = GIT_REBASE_APPLY;
goto done;
}
git_buf_clear(&path);
if (git_buf_joinpath(&path, repo->gitdir, REBASE_MERGE_DIR) < 0)
return -1;
if (git_path_isdir(git_buf_cstr(&path))) {
type = GIT_REBASE_MERGE;
goto done;
}
done:
*type_out = type;
if (type != GIT_REBASE_NONE && path_out)
*path_out = git_buf_detach(&path);
git_buf_dispose(&path);
return 0;
}
GIT_INLINE(int) rebase_readfile(
git_buf *out,
git_buf *state_path,
const char *filename)
{
size_t state_path_len = state_path->size;
int error;
git_buf_clear(out);
if ((error = git_buf_joinpath(state_path, state_path->ptr, filename)) < 0 ||
(error = git_futils_readbuffer(out, state_path->ptr)) < 0)
goto done;
git_buf_rtrim(out);
done:
git_buf_truncate(state_path, state_path_len);
return error;
}
GIT_INLINE(int) rebase_readint(
size_t *out, git_buf *asc_out, git_buf *state_path, const char *filename)
{
int32_t num;
const char *eol;
int error = 0;
if ((error = rebase_readfile(asc_out, state_path, filename)) < 0)
return error;
if (git__strntol32(&num, asc_out->ptr, asc_out->size, &eol, 10) < 0 || num < 0 || *eol) {
git_error_set(GIT_ERROR_REBASE, "the file '%s' contains an invalid numeric value", filename);
return -1;
}
*out = (size_t) num;
return 0;
}
GIT_INLINE(int) rebase_readoid(
git_oid *out, git_buf *str_out, git_buf *state_path, const char *filename)
{
int error;
if ((error = rebase_readfile(str_out, state_path, filename)) < 0)
return error;
if (str_out->size != GIT_OID_HEXSZ || git_oid_fromstr(out, str_out->ptr) < 0) {
git_error_set(GIT_ERROR_REBASE, "the file '%s' contains an invalid object ID", filename);
return -1;
}
return 0;
}
static git_rebase_operation *rebase_operation_alloc(
git_rebase *rebase,
git_rebase_operation_t type,
git_oid *id,
const char *exec)
{
git_rebase_operation *operation;
GIT_ASSERT_WITH_RETVAL((type == GIT_REBASE_OPERATION_EXEC) == !id, NULL);
GIT_ASSERT_WITH_RETVAL((type == GIT_REBASE_OPERATION_EXEC) == !!exec, NULL);
if ((operation = git_array_alloc(rebase->operations)) == NULL)
return NULL;
operation->type = type;
git_oid_cpy((git_oid *)&operation->id, id);
operation->exec = exec;
return operation;
}
static int rebase_open_merge(git_rebase *rebase)
{
git_buf state_path = GIT_BUF_INIT, buf = GIT_BUF_INIT, cmt = GIT_BUF_INIT;
git_oid id;
git_rebase_operation *operation;
size_t i, msgnum = 0, end;
int error;
if ((error = git_buf_puts(&state_path, rebase->state_path)) < 0)
goto done;
/* Read 'msgnum' if it exists (otherwise, let msgnum = 0) */
if ((error = rebase_readint(&msgnum, &buf, &state_path, MSGNUM_FILE)) < 0 &&
error != GIT_ENOTFOUND)
goto done;
if (msgnum) {
rebase->started = 1;
rebase->current = msgnum - 1;
}
/* Read 'end' */
if ((error = rebase_readint(&end, &buf, &state_path, END_FILE)) < 0)
goto done;
/* Read 'current' if it exists */
if ((error = rebase_readoid(&id, &buf, &state_path, CURRENT_FILE)) < 0 &&
error != GIT_ENOTFOUND)
goto done;
/* Read cmt.* */
git_array_init_to_size(rebase->operations, end);
GIT_ERROR_CHECK_ARRAY(rebase->operations);
for (i = 0; i < end; i++) {
git_buf_clear(&cmt);
if ((error = git_buf_printf(&cmt, "cmt.%" PRIuZ, (i+1))) < 0 ||
(error = rebase_readoid(&id, &buf, &state_path, cmt.ptr)) < 0)
goto done;
operation = rebase_operation_alloc(rebase, GIT_REBASE_OPERATION_PICK, &id, NULL);
GIT_ERROR_CHECK_ALLOC(operation);
}
/* Read 'onto_name' */
if ((error = rebase_readfile(&buf, &state_path, ONTO_NAME_FILE)) < 0)
goto done;
rebase->onto_name = git_buf_detach(&buf);
done:
git_buf_dispose(&cmt);
git_buf_dispose(&state_path);
git_buf_dispose(&buf);
return error;
}
static int rebase_alloc(git_rebase **out, const git_rebase_options *rebase_opts)
{
git_rebase *rebase = git__calloc(1, sizeof(git_rebase));
GIT_ERROR_CHECK_ALLOC(rebase);
*out = NULL;
if (rebase_opts)
memcpy(&rebase->options, rebase_opts, sizeof(git_rebase_options));
else
git_rebase_options_init(&rebase->options, GIT_REBASE_OPTIONS_VERSION);
if (rebase_opts && rebase_opts->rewrite_notes_ref) {
rebase->options.rewrite_notes_ref = git__strdup(rebase_opts->rewrite_notes_ref);
GIT_ERROR_CHECK_ALLOC(rebase->options.rewrite_notes_ref);
}
*out = rebase;
return 0;
}
static int rebase_check_versions(const git_rebase_options *given_opts)
{
GIT_ERROR_CHECK_VERSION(given_opts, GIT_REBASE_OPTIONS_VERSION, "git_rebase_options");
if (given_opts)
GIT_ERROR_CHECK_VERSION(&given_opts->checkout_options, GIT_CHECKOUT_OPTIONS_VERSION, "git_checkout_options");
return 0;
}
int git_rebase_open(
git_rebase **out,
git_repository *repo,
const git_rebase_options *given_opts)
{
git_rebase *rebase;
git_buf path = GIT_BUF_INIT, orig_head_name = GIT_BUF_INIT,
orig_head_id = GIT_BUF_INIT, onto_id = GIT_BUF_INIT;
size_t state_path_len;
int error;
GIT_ASSERT_ARG(repo);
if ((error = rebase_check_versions(given_opts)) < 0)
return error;
if (rebase_alloc(&rebase, given_opts) < 0)
return -1;
rebase->repo = repo;
if ((error = rebase_state_type(&rebase->type, &rebase->state_path, repo)) < 0)
goto done;
if (rebase->type == GIT_REBASE_NONE) {
git_error_set(GIT_ERROR_REBASE, "there is no rebase in progress");
error = GIT_ENOTFOUND;
goto done;
}
if ((error = git_buf_puts(&path, rebase->state_path)) < 0)
goto done;
state_path_len = git_buf_len(&path);
if ((error = git_buf_joinpath(&path, path.ptr, HEAD_NAME_FILE)) < 0 ||
(error = git_futils_readbuffer(&orig_head_name, path.ptr)) < 0)
goto done;
git_buf_rtrim(&orig_head_name);
if (strcmp(ORIG_DETACHED_HEAD, orig_head_name.ptr) == 0)
rebase->head_detached = 1;
git_buf_truncate(&path, state_path_len);
if ((error = git_buf_joinpath(&path, path.ptr, ORIG_HEAD_FILE)) < 0)
goto done;
if (!git_path_isfile(path.ptr)) {
/* Previous versions of git.git used 'head' here; support that. */
git_buf_truncate(&path, state_path_len);
if ((error = git_buf_joinpath(&path, path.ptr, HEAD_FILE)) < 0)
goto done;
}
if ((error = git_futils_readbuffer(&orig_head_id, path.ptr)) < 0)
goto done;
git_buf_rtrim(&orig_head_id);
if ((error = git_oid_fromstr(&rebase->orig_head_id, orig_head_id.ptr)) < 0)
goto done;
git_buf_truncate(&path, state_path_len);
if ((error = git_buf_joinpath(&path, path.ptr, ONTO_FILE)) < 0 ||
(error = git_futils_readbuffer(&onto_id, path.ptr)) < 0)
goto done;
git_buf_rtrim(&onto_id);
if ((error = git_oid_fromstr(&rebase->onto_id, onto_id.ptr)) < 0)
goto done;
if (!rebase->head_detached)
rebase->orig_head_name = git_buf_detach(&orig_head_name);
switch (rebase->type) {
case GIT_REBASE_INTERACTIVE:
git_error_set(GIT_ERROR_REBASE, "interactive rebase is not supported");
error = -1;
break;
case GIT_REBASE_MERGE:
error = rebase_open_merge(rebase);
break;
case GIT_REBASE_APPLY:
git_error_set(GIT_ERROR_REBASE, "patch application rebase is not supported");
error = -1;
break;
default:
abort();
}
done:
if (error == 0)
*out = rebase;
else
git_rebase_free(rebase);
git_buf_dispose(&path);
git_buf_dispose(&orig_head_name);
git_buf_dispose(&orig_head_id);
git_buf_dispose(&onto_id);
return error;
}
static int rebase_cleanup(git_rebase *rebase)
{
if (!rebase || rebase->inmemory)
return 0;
return git_path_isdir(rebase->state_path) ?
git_futils_rmdir_r(rebase->state_path, NULL, GIT_RMDIR_REMOVE_FILES) :
0;
}
static int rebase_setupfile(git_rebase *rebase, const char *filename, int flags, const char *fmt, ...)
{
git_buf path = GIT_BUF_INIT,
contents = GIT_BUF_INIT;
va_list ap;
int error;
va_start(ap, fmt);
git_buf_vprintf(&contents, fmt, ap);
va_end(ap);
if ((error = git_buf_joinpath(&path, rebase->state_path, filename)) == 0)
error = git_futils_writebuffer(&contents, path.ptr, flags, REBASE_FILE_MODE);
git_buf_dispose(&path);
git_buf_dispose(&contents);
return error;
}
static const char *rebase_onto_name(const git_annotated_commit *onto)
{
if (onto->ref_name && git__strncmp(onto->ref_name, "refs/heads/", 11) == 0)
return onto->ref_name + 11;
else if (onto->ref_name)
return onto->ref_name;
else
return onto->id_str;
}
static int rebase_setupfiles_merge(git_rebase *rebase)
{
git_buf commit_filename = GIT_BUF_INIT;
char id_str[GIT_OID_HEXSZ];
git_rebase_operation *operation;
size_t i;
int error = 0;
if ((error = rebase_setupfile(rebase, END_FILE, 0, "%" PRIuZ "\n", git_array_size(rebase->operations))) < 0 ||
(error = rebase_setupfile(rebase, ONTO_NAME_FILE, 0, "%s\n", rebase->onto_name)) < 0)
goto done;
for (i = 0; i < git_array_size(rebase->operations); i++) {
operation = git_array_get(rebase->operations, i);
git_buf_clear(&commit_filename);
git_buf_printf(&commit_filename, CMT_FILE_FMT, i+1);
git_oid_fmt(id_str, &operation->id);
if ((error = rebase_setupfile(rebase, commit_filename.ptr, 0,
"%.*s\n", GIT_OID_HEXSZ, id_str)) < 0)
goto done;
}
done:
git_buf_dispose(&commit_filename);
return error;
}
static int rebase_setupfiles(git_rebase *rebase)
{
char onto[GIT_OID_HEXSZ], orig_head[GIT_OID_HEXSZ];
const char *orig_head_name;
git_oid_fmt(onto, &rebase->onto_id);
git_oid_fmt(orig_head, &rebase->orig_head_id);
if (p_mkdir(rebase->state_path, REBASE_DIR_MODE) < 0) {
git_error_set(GIT_ERROR_OS, "failed to create rebase directory '%s'", rebase->state_path);
return -1;
}
orig_head_name = rebase->head_detached ? ORIG_DETACHED_HEAD :
rebase->orig_head_name;
if (git_repository__set_orig_head(rebase->repo, &rebase->orig_head_id) < 0 ||
rebase_setupfile(rebase, HEAD_NAME_FILE, 0, "%s\n", orig_head_name) < 0 ||
rebase_setupfile(rebase, ONTO_FILE, 0, "%.*s\n", GIT_OID_HEXSZ, onto) < 0 ||
rebase_setupfile(rebase, ORIG_HEAD_FILE, 0, "%.*s\n", GIT_OID_HEXSZ, orig_head) < 0 ||
rebase_setupfile(rebase, QUIET_FILE, 0, rebase->quiet ? "t\n" : "\n") < 0)
return -1;
return rebase_setupfiles_merge(rebase);
}
int git_rebase_options_init(git_rebase_options *opts, unsigned int version)
{
GIT_INIT_STRUCTURE_FROM_TEMPLATE(
opts, version, git_rebase_options, GIT_REBASE_OPTIONS_INIT);
return 0;
}
#ifndef GIT_DEPRECATE_HARD
int git_rebase_init_options(git_rebase_options *opts, unsigned int version)
{
return git_rebase_options_init(opts, version);
}
#endif
static int rebase_ensure_not_in_progress(git_repository *repo)
{
int error;
git_rebase_t type;
if ((error = rebase_state_type(&type, NULL, repo)) < 0)
return error;
if (type != GIT_REBASE_NONE) {
git_error_set(GIT_ERROR_REBASE, "there is an existing rebase in progress");
return -1;
}
return 0;
}
static int rebase_ensure_not_dirty(
git_repository *repo,
bool check_index,
bool check_workdir,
int fail_with)
{
git_tree *head = NULL;
git_index *index = NULL;
git_diff *diff = NULL;
int error = 0;
if (check_index) {
if ((error = git_repository_head_tree(&head, repo)) < 0 ||
(error = git_repository_index(&index, repo)) < 0 ||
(error = git_diff_tree_to_index(&diff, repo, head, index, NULL)) < 0)
goto done;
if (git_diff_num_deltas(diff) > 0) {
git_error_set(GIT_ERROR_REBASE, "uncommitted changes exist in index");
error = fail_with;
goto done;
}
git_diff_free(diff);
diff = NULL;
}
if (check_workdir) {
git_diff_options diff_opts = GIT_DIFF_OPTIONS_INIT;
diff_opts.ignore_submodules = GIT_SUBMODULE_IGNORE_UNTRACKED;
if ((error = git_diff_index_to_workdir(&diff, repo, index, &diff_opts)) < 0)
goto done;
if (git_diff_num_deltas(diff) > 0) {
git_error_set(GIT_ERROR_REBASE, "unstaged changes exist in workdir");
error = fail_with;
goto done;
}
}
done:
git_diff_free(diff);
git_index_free(index);
git_tree_free(head);
return error;
}
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);
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 = rebase_operation_alloc(rebase, GIT_REBASE_OPERATION_PICK, &id, NULL);
GIT_ERROR_CHECK_ALLOC(operation);
}
error = 0;
done:
git_revwalk_free(revwalk);
return error;
}
static int rebase_init_merge(
git_rebase *rebase,
git_repository *repo,
const git_annotated_commit *branch,
const git_annotated_commit *upstream,
const git_annotated_commit *onto)
{
git_reference *head_ref = NULL;
git_commit *onto_commit = NULL;
git_buf reflog = GIT_BUF_INIT;
git_buf state_path = GIT_BUF_INIT;
int error;
GIT_UNUSED(upstream);
if ((error = git_buf_joinpath(&state_path, repo->gitdir, REBASE_MERGE_DIR)) < 0)
goto done;
rebase->state_path = git_buf_detach(&state_path);
GIT_ERROR_CHECK_ALLOC(rebase->state_path);
if (branch->ref_name && strcmp(branch->ref_name, "HEAD")) {
rebase->orig_head_name = git__strdup(branch->ref_name);
GIT_ERROR_CHECK_ALLOC(rebase->orig_head_name);
} else {
rebase->head_detached = 1;
}
rebase->onto_name = git__strdup(rebase_onto_name(onto));
GIT_ERROR_CHECK_ALLOC(rebase->onto_name);
rebase->quiet = rebase->options.quiet;
git_oid_cpy(&rebase->orig_head_id, git_annotated_commit_id(branch));
git_oid_cpy(&rebase->onto_id, git_annotated_commit_id(onto));
if ((error = rebase_setupfiles(rebase)) < 0 ||
(error = git_buf_printf(&reflog,
"rebase: checkout %s", rebase_onto_name(onto))) < 0 ||
(error = git_commit_lookup(
&onto_commit, repo, git_annotated_commit_id(onto))) < 0 ||
(error = git_checkout_tree(repo,
(git_object *)onto_commit, &rebase->options.checkout_options)) < 0 ||
(error = git_reference_create(&head_ref, repo, GIT_HEAD_FILE,
git_annotated_commit_id(onto), 1, reflog.ptr)) < 0)
goto done;
done:
git_reference_free(head_ref);
git_commit_free(onto_commit);
git_buf_dispose(&reflog);
git_buf_dispose(&state_path);
return error;
}
static int rebase_init_inmemory(
git_rebase *rebase,
git_repository *repo,
const git_annotated_commit *branch,
const git_annotated_commit *upstream,
const git_annotated_commit *onto)
{
GIT_UNUSED(branch);
GIT_UNUSED(upstream);
return git_commit_lookup(
&rebase->last_commit, repo, git_annotated_commit_id(onto));
}
int git_rebase_init(
git_rebase **out,
git_repository *repo,
const git_annotated_commit *branch,
const git_annotated_commit *upstream,
const git_annotated_commit *onto,
const git_rebase_options *given_opts)
{
git_rebase *rebase = NULL;
git_annotated_commit *head_branch = NULL;
git_reference *head_ref = NULL;
bool inmemory = (given_opts && given_opts->inmemory);
int error;
GIT_ASSERT_ARG(repo);
GIT_ASSERT_ARG(upstream || onto);
*out = NULL;
if (!onto)
onto = upstream;
if ((error = rebase_check_versions(given_opts)) < 0)
goto done;
if (!inmemory) {
if ((error = git_repository__ensure_not_bare(repo, "rebase")) < 0 ||
(error = rebase_ensure_not_in_progress(repo)) < 0 ||
(error = rebase_ensure_not_dirty(repo, true, true, GIT_ERROR)) < 0)
goto done;
}
if (!branch) {
if ((error = git_repository_head(&head_ref, repo)) < 0 ||
(error = git_annotated_commit_from_ref(&head_branch, repo, head_ref)) < 0)
goto done;
branch = head_branch;
}
if (rebase_alloc(&rebase, given_opts) < 0)
return -1;
rebase->repo = repo;
rebase->inmemory = inmemory;
rebase->type = GIT_REBASE_MERGE;
if ((error = rebase_init_operations(rebase, repo, branch, upstream, onto)) < 0)
goto done;
if (inmemory)
error = rebase_init_inmemory(rebase, repo, branch, upstream, onto);
else
error = rebase_init_merge(rebase, repo, branch ,upstream, onto);
if (error == 0)
*out = rebase;
done:
git_reference_free(head_ref);
git_annotated_commit_free(head_branch);
if (error < 0) {
rebase_cleanup(rebase);
git_rebase_free(rebase);
}
return error;
}
static void normalize_checkout_options_for_apply(
git_checkout_options *checkout_opts,
git_rebase *rebase,
git_commit *current_commit)
{
memcpy(checkout_opts, &rebase->options.checkout_options, sizeof(git_checkout_options));
if (!checkout_opts->ancestor_label)
checkout_opts->ancestor_label = "ancestor";
if (rebase->type == GIT_REBASE_MERGE) {
if (!checkout_opts->our_label)
checkout_opts->our_label = rebase->onto_name;
if (!checkout_opts->their_label)
checkout_opts->their_label = git_commit_summary(current_commit);
} else {
abort();
}
}
GIT_INLINE(int) rebase_movenext(git_rebase *rebase)
{
size_t next = rebase->started ? rebase->current + 1 : 0;
if (next == git_array_size(rebase->operations))
return GIT_ITEROVER;
rebase->started = 1;
rebase->current = next;
return 0;
}
static int rebase_next_merge(
git_rebase_operation **out,
git_rebase *rebase)
{
git_buf path = GIT_BUF_INIT;
git_commit *current_commit = NULL, *parent_commit = NULL;
git_tree *current_tree = NULL, *head_tree = NULL, *parent_tree = NULL;
git_index *index = NULL;
git_indexwriter indexwriter = GIT_INDEXWRITER_INIT;
git_rebase_operation *operation;
git_checkout_options checkout_opts;
char current_idstr[GIT_OID_HEXSZ];
unsigned int parent_count;
int error;
*out = NULL;
operation = git_array_get(rebase->operations, rebase->current);
if ((error = git_commit_lookup(¤t_commit, rebase->repo, &operation->id)) < 0 ||
(error = git_commit_tree(¤t_tree, current_commit)) < 0 ||
(error = git_repository_head_tree(&head_tree, rebase->repo)) < 0)
goto done;
if ((parent_count = git_commit_parentcount(current_commit)) > 1) {
git_error_set(GIT_ERROR_REBASE, "cannot rebase a merge commit");
error = -1;
goto done;
} else if (parent_count) {
if ((error = git_commit_parent(&parent_commit, current_commit, 0)) < 0 ||
(error = git_commit_tree(&parent_tree, parent_commit)) < 0)
goto done;
}
git_oid_fmt(current_idstr, &operation->id);
normalize_checkout_options_for_apply(&checkout_opts, rebase, current_commit);
if ((error = git_indexwriter_init_for_operation(&indexwriter, rebase->repo, &checkout_opts.checkout_strategy)) < 0 ||
(error = rebase_setupfile(rebase, MSGNUM_FILE, 0, "%" PRIuZ "\n", rebase->current+1)) < 0 ||
(error = rebase_setupfile(rebase, CURRENT_FILE, 0, "%.*s\n", GIT_OID_HEXSZ, current_idstr)) < 0 ||
(error = git_merge_trees(&index, rebase->repo, parent_tree, head_tree, current_tree, &rebase->options.merge_options)) < 0 ||
(error = git_merge__check_result(rebase->repo, index)) < 0 ||
(error = git_checkout_index(rebase->repo, index, &checkout_opts)) < 0 ||
(error = git_indexwriter_commit(&indexwriter)) < 0)
goto done;
*out = operation;
done:
git_indexwriter_cleanup(&indexwriter);
git_index_free(index);
git_tree_free(current_tree);
git_tree_free(head_tree);
git_tree_free(parent_tree);
git_commit_free(parent_commit);
git_commit_free(current_commit);
git_buf_dispose(&path);
return error;
}
static int rebase_next_inmemory(
git_rebase_operation **out,
git_rebase *rebase)
{
git_commit *current_commit = NULL, *parent_commit = NULL;
git_tree *current_tree = NULL, *head_tree = NULL, *parent_tree = NULL;
git_rebase_operation *operation;
git_index *index = NULL;
unsigned int parent_count;
int error;
*out = NULL;
operation = git_array_get(rebase->operations, rebase->current);
if ((error = git_commit_lookup(¤t_commit, rebase->repo, &operation->id)) < 0 ||
(error = git_commit_tree(¤t_tree, current_commit)) < 0)
goto done;
if ((parent_count = git_commit_parentcount(current_commit)) > 1) {
git_error_set(GIT_ERROR_REBASE, "cannot rebase a merge commit");
error = -1;
goto done;
} else if (parent_count) {
if ((error = git_commit_parent(&parent_commit, current_commit, 0)) < 0 ||
(error = git_commit_tree(&parent_tree, parent_commit)) < 0)
goto done;
}
if ((error = git_commit_tree(&head_tree, rebase->last_commit)) < 0 ||
(error = git_merge_trees(&index, rebase->repo, parent_tree, head_tree, current_tree, &rebase->options.merge_options)) < 0)
goto done;
if (!rebase->index) {
rebase->index = index;
index = NULL;
} else {
if ((error = git_index_read_index(rebase->index, index)) < 0)
goto done;
}
*out = operation;
done:
git_commit_free(current_commit);
git_commit_free(parent_commit);
git_tree_free(current_tree);
git_tree_free(head_tree);
git_tree_free(parent_tree);
git_index_free(index);
return error;
}
int git_rebase_next(
git_rebase_operation **out,
git_rebase *rebase)
{
int error;
GIT_ASSERT_ARG(out);
GIT_ASSERT_ARG(rebase);
if ((error = rebase_movenext(rebase)) < 0)
return error;
if (rebase->inmemory)
error = rebase_next_inmemory(out, rebase);
else if (rebase->type == GIT_REBASE_MERGE)
error = rebase_next_merge(out, rebase);
else
abort();
return error;
}
int git_rebase_inmemory_index(
git_index **out,
git_rebase *rebase)
{
GIT_ASSERT_ARG(out);
GIT_ASSERT_ARG(rebase);
GIT_ASSERT_ARG(rebase->index);
GIT_REFCOUNT_INC(rebase->index);
*out = rebase->index;
return 0;
}
#ifndef GIT_DEPRECATE_HARD
static int create_signed(
git_oid *out,
git_rebase *rebase,
const git_signature *author,
const git_signature *committer,
const char *message_encoding,
const char *message,
git_tree *tree,
size_t parent_count,
const git_commit **parents)
{
git_buf commit_content = GIT_BUF_INIT,
commit_signature = GIT_BUF_INIT,
signature_field = GIT_BUF_INIT;
int error;
git_error_clear();
if ((error = git_commit_create_buffer(&commit_content,
rebase->repo, author, committer, message_encoding,
message, tree, parent_count, parents)) < 0)
goto done;
error = rebase->options.signing_cb(&commit_signature,
&signature_field, commit_content.ptr,
rebase->options.payload);
if (error) {
if (error != GIT_PASSTHROUGH)
git_error_set_after_callback_function(error, "signing_cb");
goto done;
}
error = git_commit_create_with_signature(out, rebase->repo,
commit_content.ptr,
commit_signature.size > 0 ? commit_signature.ptr : NULL,
signature_field.size > 0 ? signature_field.ptr : NULL);
done:
git_buf_dispose(&commit_signature);
git_buf_dispose(&signature_field);
git_buf_dispose(&commit_content);
return error;
}
#endif
static int rebase_commit__create(
git_commit **out,
git_rebase *rebase,
git_index *index,
git_commit *parent_commit,
const git_signature *author,
const git_signature *committer,
const char *message_encoding,
const char *message)
{
git_rebase_operation *operation;
git_commit *current_commit = NULL, *commit = NULL;
git_tree *parent_tree = NULL, *tree = NULL;
git_oid tree_id, commit_id;
int error;
operation = git_array_get(rebase->operations, rebase->current);
if (git_index_has_conflicts(index)) {
git_error_set(GIT_ERROR_REBASE, "conflicts have not been resolved");
error = GIT_EUNMERGED;
goto done;
}
if ((error = git_commit_lookup(¤t_commit, rebase->repo, &operation->id)) < 0 ||
(error = git_commit_tree(&parent_tree, parent_commit)) < 0 ||
(error = git_index_write_tree_to(&tree_id, index, rebase->repo)) < 0 ||
(error = git_tree_lookup(&tree, rebase->repo, &tree_id)) < 0)
goto done;
if (git_oid_equal(&tree_id, git_tree_id(parent_tree))) {
git_error_set(GIT_ERROR_REBASE, "this patch has already been applied");
error = GIT_EAPPLIED;
goto done;
}
if (!author)
author = git_commit_author(current_commit);
if (!message) {
message_encoding = git_commit_message_encoding(current_commit);
message = git_commit_message(current_commit);
}
git_error_clear();
error = GIT_PASSTHROUGH;
if (rebase->options.commit_create_cb) {
error = rebase->options.commit_create_cb(&commit_id,
author, committer, message_encoding, message,
tree, 1, (const git_commit **)&parent_commit,
rebase->options.payload);
git_error_set_after_callback_function(error,
"commit_create_cb");
}
#ifndef GIT_DEPRECATE_HARD
else if (rebase->options.signing_cb) {
error = create_signed(&commit_id, rebase, author,
committer, message_encoding, message, tree,
1, (const git_commit **)&parent_commit);
}
#endif
if (error == GIT_PASSTHROUGH)
error = git_commit_create(&commit_id, rebase->repo, NULL,
author, committer, message_encoding, message,
tree, 1, (const git_commit **)&parent_commit);
if (error)
goto done;
if ((error = git_commit_lookup(&commit, rebase->repo, &commit_id)) < 0)
goto done;
*out = commit;
done:
if (error < 0)
git_commit_free(commit);
git_commit_free(current_commit);
git_tree_free(parent_tree);
git_tree_free(tree);
return error;
}
static int rebase_commit_merge(
git_oid *commit_id,
git_rebase *rebase,
const git_signature *author,
const git_signature *committer,
const char *message_encoding,
const char *message)
{
git_rebase_operation *operation;
git_reference *head = NULL;
git_commit *head_commit = NULL, *commit = NULL;
git_index *index = NULL;
char old_idstr[GIT_OID_HEXSZ], new_idstr[GIT_OID_HEXSZ];
int error;
operation = git_array_get(rebase->operations, rebase->current);
GIT_ASSERT(operation);
if ((error = rebase_ensure_not_dirty(rebase->repo, false, true, GIT_EUNMERGED)) < 0 ||
(error = git_repository_head(&head, rebase->repo)) < 0 ||
(error = git_reference_peel((git_object **)&head_commit, head, GIT_OBJECT_COMMIT)) < 0 ||
(error = git_repository_index(&index, rebase->repo)) < 0 ||
(error = rebase_commit__create(&commit, rebase, index, head_commit,
author, committer, message_encoding, message)) < 0 ||
(error = git_reference__update_for_commit(
rebase->repo, NULL, "HEAD", git_commit_id(commit), "rebase")) < 0)
goto done;
git_oid_fmt(old_idstr, &operation->id);
git_oid_fmt(new_idstr, git_commit_id(commit));
if ((error = rebase_setupfile(rebase, REWRITTEN_FILE, O_CREAT|O_WRONLY|O_APPEND,
"%.*s %.*s\n", GIT_OID_HEXSZ, old_idstr, GIT_OID_HEXSZ, new_idstr)) < 0)
goto done;
git_oid_cpy(commit_id, git_commit_id(commit));
done:
git_index_free(index);
git_reference_free(head);
git_commit_free(head_commit);
git_commit_free(commit);
return error;
}
static int rebase_commit_inmemory(
git_oid *commit_id,
git_rebase *rebase,
const git_signature *author,
const git_signature *committer,
const char *message_encoding,
const char *message)
{
git_commit *commit = NULL;
int error = 0;
GIT_ASSERT_ARG(rebase->index);
GIT_ASSERT_ARG(rebase->last_commit);
GIT_ASSERT_ARG(rebase->current < rebase->operations.size);
if ((error = rebase_commit__create(&commit, rebase, rebase->index,
rebase->last_commit, author, committer, message_encoding, message)) < 0)
goto done;
git_commit_free(rebase->last_commit);
rebase->last_commit = commit;
git_oid_cpy(commit_id, git_commit_id(commit));
done:
if (error < 0)
git_commit_free(commit);
return error;
}
int git_rebase_commit(
git_oid *id,
git_rebase *rebase,
const git_signature *author,
const git_signature *committer,
const char *message_encoding,
const char *message)
{
int error;
GIT_ASSERT_ARG(rebase);
GIT_ASSERT_ARG(committer);
if (rebase->inmemory)
error = rebase_commit_inmemory(
id, rebase, author, committer, message_encoding, message);
else if (rebase->type == GIT_REBASE_MERGE)
error = rebase_commit_merge(
id, rebase, author, committer, message_encoding, message);
else
abort();
return error;
}
int git_rebase_abort(git_rebase *rebase)
{
git_reference *orig_head_ref = NULL;
git_commit *orig_head_commit = NULL;
int error;
GIT_ASSERT_ARG(rebase);
if (rebase->inmemory)
return 0;
error = rebase->head_detached ?
git_reference_create(&orig_head_ref, rebase->repo, GIT_HEAD_FILE,
&rebase->orig_head_id, 1, "rebase: aborting") :
git_reference_symbolic_create(
&orig_head_ref, rebase->repo, GIT_HEAD_FILE, rebase->orig_head_name, 1,
"rebase: aborting");
if (error < 0)
goto done;
if ((error = git_commit_lookup(
&orig_head_commit, rebase->repo, &rebase->orig_head_id)) < 0 ||
(error = git_reset(rebase->repo, (git_object *)orig_head_commit,
GIT_RESET_HARD, &rebase->options.checkout_options)) < 0)
goto done;
error = rebase_cleanup(rebase);
done:
git_commit_free(orig_head_commit);
git_reference_free(orig_head_ref);
return error;
}
static int notes_ref_lookup(git_buf *out, git_rebase *rebase)
{
git_config *config = NULL;
int do_rewrite, error;
if (rebase->options.rewrite_notes_ref) {
git_buf_attach_notowned(out,
rebase->options.rewrite_notes_ref,
strlen(rebase->options.rewrite_notes_ref));
return 0;
}
if ((error = git_repository_config(&config, rebase->repo)) < 0 ||
(error = git_config_get_bool(&do_rewrite, config, "notes.rewrite.rebase")) < 0) {
if (error != GIT_ENOTFOUND)
goto done;
git_error_clear();
do_rewrite = 1;
}
error = do_rewrite ?
git_config_get_string_buf(out, config, "notes.rewriteref") :
GIT_ENOTFOUND;
done:
git_config_free(config);
return error;
}
static int rebase_copy_note(
git_rebase *rebase,
const char *notes_ref,
git_oid *from,
git_oid *to,
const git_signature *committer)
{
git_note *note = NULL;
git_oid note_id;
git_signature *who = NULL;
int error;
if ((error = git_note_read(¬e, rebase->repo, notes_ref, from)) < 0) {
if (error == GIT_ENOTFOUND) {
git_error_clear();
error = 0;
}
goto done;
}
if (!committer) {
if((error = git_signature_default(&who, rebase->repo)) < 0) {
if (error != GIT_ENOTFOUND ||
(error = git_signature_now(&who, "unknown", "unknown")) < 0)
goto done;
git_error_clear();
}
committer = who;
}
error = git_note_create(¬e_id, rebase->repo, notes_ref,
git_note_author(note), committer, to, git_note_message(note), 0);
done:
git_note_free(note);
git_signature_free(who);
return error;
}
static int rebase_copy_notes(
git_rebase *rebase,
const git_signature *committer)
{
git_buf path = GIT_BUF_INIT, rewritten = GIT_BUF_INIT, notes_ref = GIT_BUF_INIT;
char *pair_list, *fromstr, *tostr, *end;
git_oid from, to;
unsigned int linenum = 1;
int error = 0;
if ((error = notes_ref_lookup(¬es_ref, rebase)) < 0) {
if (error == GIT_ENOTFOUND) {
git_error_clear();
error = 0;
}
goto done;
}
if ((error = git_buf_joinpath(&path, rebase->state_path, REWRITTEN_FILE)) < 0 ||
(error = git_futils_readbuffer(&rewritten, path.ptr)) < 0)
goto done;
pair_list = rewritten.ptr;
while (*pair_list) {
fromstr = pair_list;
if ((end = strchr(fromstr, '\n')) == NULL)
goto on_error;
pair_list = end+1;
*end = '\0';
if ((end = strchr(fromstr, ' ')) == NULL)
goto on_error;
tostr = end+1;
*end = '\0';
if (strlen(fromstr) != GIT_OID_HEXSZ ||
strlen(tostr) != GIT_OID_HEXSZ ||
git_oid_fromstr(&from, fromstr) < 0 ||
git_oid_fromstr(&to, tostr) < 0)
goto on_error;
if ((error = rebase_copy_note(rebase, notes_ref.ptr, &from, &to, committer)) < 0)
goto done;
linenum++;
}
goto done;
on_error:
git_error_set(GIT_ERROR_REBASE, "invalid rewritten file at line %d", linenum);
error = -1;
done:
git_buf_dispose(&rewritten);
git_buf_dispose(&path);
git_buf_dispose(¬es_ref);
return error;
}
static int return_to_orig_head(git_rebase *rebase)
{
git_reference *terminal_ref = NULL, *branch_ref = NULL, *head_ref = NULL;
git_commit *terminal_commit = NULL;
git_buf branch_msg = GIT_BUF_INIT, head_msg = GIT_BUF_INIT;
char onto[GIT_OID_HEXSZ];
int error = 0;
git_oid_fmt(onto, &rebase->onto_id);
if ((error = git_buf_printf(&branch_msg,
"rebase finished: %s onto %.*s",
rebase->orig_head_name, GIT_OID_HEXSZ, onto)) == 0 &&
(error = git_buf_printf(&head_msg,
"rebase finished: returning to %s",
rebase->orig_head_name)) == 0 &&
(error = git_repository_head(&terminal_ref, rebase->repo)) == 0 &&
(error = git_reference_peel((git_object **)&terminal_commit,
terminal_ref, GIT_OBJECT_COMMIT)) == 0 &&
(error = git_reference_create_matching(&branch_ref,
rebase->repo, rebase->orig_head_name,
git_commit_id(terminal_commit), 1,
&rebase->orig_head_id, branch_msg.ptr)) == 0)
error = git_reference_symbolic_create(&head_ref,
rebase->repo, GIT_HEAD_FILE, rebase->orig_head_name, 1,
head_msg.ptr);
git_buf_dispose(&head_msg);
git_buf_dispose(&branch_msg);
git_commit_free(terminal_commit);
git_reference_free(head_ref);
git_reference_free(branch_ref);
git_reference_free(terminal_ref);
return error;
}
int git_rebase_finish(
git_rebase *rebase,
const git_signature *signature)
{
int error = 0;
GIT_ASSERT_ARG(rebase);
if (rebase->inmemory)
return 0;
if (!rebase->head_detached)
error = return_to_orig_head(rebase);
if (error == 0 && (error = rebase_copy_notes(rebase, signature)) == 0)
error = rebase_cleanup(rebase);
return error;
}
const char *git_rebase_orig_head_name(git_rebase *rebase) {
GIT_ASSERT_ARG_WITH_RETVAL(rebase, NULL);
return rebase->orig_head_name;
}
const git_oid *git_rebase_orig_head_id(git_rebase *rebase) {
GIT_ASSERT_ARG_WITH_RETVAL(rebase, NULL);
return &rebase->orig_head_id;
}
const char *git_rebase_onto_name(git_rebase *rebase) {
GIT_ASSERT_ARG_WITH_RETVAL(rebase, NULL);
return rebase->onto_name;
}
const git_oid *git_rebase_onto_id(git_rebase *rebase) {
return &rebase->onto_id;
}
size_t git_rebase_operation_entrycount(git_rebase *rebase)
{
GIT_ASSERT_ARG_WITH_RETVAL(rebase, 0);
return git_array_size(rebase->operations);
}
size_t git_rebase_operation_current(git_rebase *rebase)
{
GIT_ASSERT_ARG_WITH_RETVAL(rebase, 0);
return rebase->started ? rebase->current : GIT_REBASE_NO_OPERATION;
}
git_rebase_operation *git_rebase_operation_byindex(git_rebase *rebase, size_t idx)
{
GIT_ASSERT_ARG_WITH_RETVAL(rebase, NULL);
return git_array_get(rebase->operations, idx);
}
void git_rebase_free(git_rebase *rebase)
{
if (rebase == NULL)
return;
git_index_free(rebase->index);
git_commit_free(rebase->last_commit);
git__free(rebase->onto_name);
git__free(rebase->orig_head_name);
git__free(rebase->state_path);
git_array_clear(rebase->operations);
git__free((char *)rebase->options.rewrite_notes_ref);
git__free(rebase);
}
|
0 |
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2
|
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2/src/repo_template.h
|
/*
* Copyright (C) the libgit2 contributors. All rights reserved.
*
* This file is part of libgit2, distributed under the GNU GPL v2 with
* a Linking Exception. For full terms see the included COPYING file.
*/
#ifndef INCLUDE_repo_template_h__
#define INCLUDE_repo_template_h__
#define GIT_OBJECTS_INFO_DIR GIT_OBJECTS_DIR "info/"
#define GIT_OBJECTS_PACK_DIR GIT_OBJECTS_DIR "pack/"
#define GIT_HOOKS_DIR "hooks/"
#define GIT_HOOKS_DIR_MODE 0777
#define GIT_HOOKS_README_FILE GIT_HOOKS_DIR "README.sample"
#define GIT_HOOKS_README_MODE 0777
#define GIT_HOOKS_README_CONTENT \
"#!/bin/sh\n"\
"#\n"\
"# Place appropriately named executable hook scripts into this directory\n"\
"# to intercept various actions that git takes. See `git help hooks` for\n"\
"# more information.\n"
#define GIT_INFO_DIR "info/"
#define GIT_INFO_DIR_MODE 0777
#define GIT_INFO_EXCLUDE_FILE GIT_INFO_DIR "exclude"
#define GIT_INFO_EXCLUDE_MODE 0666
#define GIT_INFO_EXCLUDE_CONTENT \
"# File patterns to ignore; see `git help ignore` for more information.\n"\
"# Lines that start with '#' are comments.\n"
#define GIT_DESC_FILE "description"
#define GIT_DESC_MODE 0666
#define GIT_DESC_CONTENT \
"Unnamed repository; edit this file 'description' to name the repository.\n"
typedef struct {
const char *path;
mode_t mode;
const char *content;
} repo_template_item;
static repo_template_item repo_template[] = {
{ GIT_OBJECTS_INFO_DIR, GIT_OBJECT_DIR_MODE, NULL }, /* '/objects/info/' */
{ GIT_OBJECTS_PACK_DIR, GIT_OBJECT_DIR_MODE, NULL }, /* '/objects/pack/' */
{ GIT_REFS_HEADS_DIR, GIT_REFS_DIR_MODE, NULL }, /* '/refs/heads/' */
{ GIT_REFS_TAGS_DIR, GIT_REFS_DIR_MODE, NULL }, /* '/refs/tags/' */
{ GIT_HOOKS_DIR, GIT_HOOKS_DIR_MODE, NULL }, /* '/hooks/' */
{ GIT_INFO_DIR, GIT_INFO_DIR_MODE, NULL }, /* '/info/' */
{ GIT_DESC_FILE, GIT_DESC_MODE, GIT_DESC_CONTENT },
{ GIT_HOOKS_README_FILE, GIT_HOOKS_README_MODE, GIT_HOOKS_README_CONTENT },
{ GIT_INFO_EXCLUDE_FILE, GIT_INFO_EXCLUDE_MODE, GIT_INFO_EXCLUDE_CONTENT },
{ NULL, 0, NULL }
};
#endif
|
0 |
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2
|
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2/src/attr_file.c
|
/*
* Copyright (C) the libgit2 contributors. All rights reserved.
*
* This file is part of libgit2, distributed under the GNU GPL v2 with
* a Linking Exception. For full terms see the included COPYING file.
*/
#include "attr_file.h"
#include "repository.h"
#include "filebuf.h"
#include "attrcache.h"
#include "git2/blob.h"
#include "git2/tree.h"
#include "blob.h"
#include "index.h"
#include "wildmatch.h"
#include <ctype.h>
static void attr_file_free(git_attr_file *file)
{
bool unlock = !git_mutex_lock(&file->lock);
git_attr_file__clear_rules(file, false);
git_pool_clear(&file->pool);
if (unlock)
git_mutex_unlock(&file->lock);
git_mutex_free(&file->lock);
git__memzero(file, sizeof(*file));
git__free(file);
}
int git_attr_file__new(
git_attr_file **out,
git_attr_file_entry *entry,
git_attr_file_source *source)
{
git_attr_file *attrs = git__calloc(1, sizeof(git_attr_file));
GIT_ERROR_CHECK_ALLOC(attrs);
if (git_mutex_init(&attrs->lock) < 0) {
git_error_set(GIT_ERROR_OS, "failed to initialize lock");
goto on_error;
}
if (git_pool_init(&attrs->pool, 1) < 0)
goto on_error;
GIT_REFCOUNT_INC(attrs);
attrs->entry = entry;
memcpy(&attrs->source, source, sizeof(git_attr_file_source));
*out = attrs;
return 0;
on_error:
git__free(attrs);
return -1;
}
int git_attr_file__clear_rules(git_attr_file *file, bool need_lock)
{
unsigned int i;
git_attr_rule *rule;
if (need_lock && git_mutex_lock(&file->lock) < 0) {
git_error_set(GIT_ERROR_OS, "failed to lock attribute file");
return -1;
}
git_vector_foreach(&file->rules, i, rule)
git_attr_rule__free(rule);
git_vector_free(&file->rules);
if (need_lock)
git_mutex_unlock(&file->lock);
return 0;
}
void git_attr_file__free(git_attr_file *file)
{
if (!file)
return;
GIT_REFCOUNT_DEC(file, attr_file_free);
}
static int attr_file_oid_from_index(
git_oid *oid, git_repository *repo, const char *path)
{
int error;
git_index *idx;
size_t pos;
const git_index_entry *entry;
if ((error = git_repository_index__weakptr(&idx, repo)) < 0 ||
(error = git_index__find_pos(&pos, idx, path, 0, 0)) < 0)
return error;
if (!(entry = git_index_get_byindex(idx, pos)))
return GIT_ENOTFOUND;
*oid = entry->id;
return 0;
}
int git_attr_file__load(
git_attr_file **out,
git_repository *repo,
git_attr_session *attr_session,
git_attr_file_entry *entry,
git_attr_file_source *source,
git_attr_file_parser parser,
bool allow_macros)
{
int error = 0;
git_commit *commit = NULL;
git_tree *tree = NULL;
git_tree_entry *tree_entry = NULL;
git_blob *blob = NULL;
git_buf content = GIT_BUF_INIT;
const char *content_str;
git_attr_file *file;
struct stat st;
bool nonexistent = false;
int bom_offset;
git_buf_bom_t bom;
git_oid id;
git_object_size_t blobsize;
*out = NULL;
switch (source->type) {
case GIT_ATTR_FILE_SOURCE_MEMORY:
/* in-memory attribute file doesn't need data */
break;
case GIT_ATTR_FILE_SOURCE_INDEX: {
if ((error = attr_file_oid_from_index(&id, repo, entry->path)) < 0 ||
(error = git_blob_lookup(&blob, repo, &id)) < 0)
return error;
/* Do not assume that data straight from the ODB is NULL-terminated;
* copy the contents of a file to a buffer to work on */
blobsize = git_blob_rawsize(blob);
GIT_ERROR_CHECK_BLOBSIZE(blobsize);
git_buf_put(&content, git_blob_rawcontent(blob), (size_t)blobsize);
break;
}
case GIT_ATTR_FILE_SOURCE_FILE: {
int fd = -1;
/* For open or read errors, pretend that we got ENOTFOUND. */
/* TODO: issue warning when warning API is available */
if (p_stat(entry->fullpath, &st) < 0 ||
S_ISDIR(st.st_mode) ||
(fd = git_futils_open_ro(entry->fullpath)) < 0 ||
(error = git_futils_readbuffer_fd(&content, fd, (size_t)st.st_size)) < 0)
nonexistent = true;
if (fd >= 0)
p_close(fd);
break;
}
case GIT_ATTR_FILE_SOURCE_HEAD:
case GIT_ATTR_FILE_SOURCE_COMMIT: {
if (source->type == GIT_ATTR_FILE_SOURCE_COMMIT) {
if ((error = git_commit_lookup(&commit, repo, source->commit_id)) < 0 ||
(error = git_commit_tree(&tree, commit)) < 0)
goto cleanup;
} else {
if ((error = git_repository_head_tree(&tree, repo)) < 0)
goto cleanup;
}
if ((error = git_tree_entry_bypath(&tree_entry, tree, entry->path)) < 0) {
/*
* If the attributes file does not exist, we can
* cache an empty file for this commit to prevent
* needless future lookups.
*/
if (error == GIT_ENOTFOUND) {
error = 0;
break;
}
goto cleanup;
}
if ((error = git_blob_lookup(&blob, repo, git_tree_entry_id(tree_entry))) < 0)
goto cleanup;
/*
* Do not assume that data straight from the ODB is NULL-terminated;
* copy the contents of a file to a buffer to work on.
*/
blobsize = git_blob_rawsize(blob);
GIT_ERROR_CHECK_BLOBSIZE(blobsize);
if ((error = git_buf_put(&content,
git_blob_rawcontent(blob), (size_t)blobsize)) < 0)
goto cleanup;
break;
}
default:
git_error_set(GIT_ERROR_INVALID, "unknown file source %d", source->type);
return -1;
}
if ((error = git_attr_file__new(&file, entry, source)) < 0)
goto cleanup;
/* advance over a UTF8 BOM */
content_str = git_buf_cstr(&content);
bom_offset = git_buf_detect_bom(&bom, &content);
if (bom == GIT_BUF_BOM_UTF8)
content_str += bom_offset;
/* store the key of the attr_reader; don't bother with cache
* invalidation during the same attr reader session.
*/
if (attr_session)
file->session_key = attr_session->key;
if (parser && (error = parser(repo, file, content_str, allow_macros)) < 0) {
git_attr_file__free(file);
goto cleanup;
}
/* write cache breakers */
if (nonexistent)
file->nonexistent = 1;
else if (source->type == GIT_ATTR_FILE_SOURCE_INDEX)
git_oid_cpy(&file->cache_data.oid, git_blob_id(blob));
else if (source->type == GIT_ATTR_FILE_SOURCE_HEAD)
git_oid_cpy(&file->cache_data.oid, git_tree_id(tree));
else if (source->type == GIT_ATTR_FILE_SOURCE_COMMIT)
git_oid_cpy(&file->cache_data.oid, git_tree_id(tree));
else if (source->type == GIT_ATTR_FILE_SOURCE_FILE)
git_futils_filestamp_set_from_stat(&file->cache_data.stamp, &st);
/* else always cacheable */
*out = file;
cleanup:
git_blob_free(blob);
git_tree_entry_free(tree_entry);
git_tree_free(tree);
git_commit_free(commit);
git_buf_dispose(&content);
return error;
}
int git_attr_file__out_of_date(
git_repository *repo,
git_attr_session *attr_session,
git_attr_file *file,
git_attr_file_source *source)
{
if (!file)
return 1;
/* we are never out of date if we just created this data in the same
* attr_session; otherwise, nonexistent files must be invalidated
*/
if (attr_session && attr_session->key == file->session_key)
return 0;
else if (file->nonexistent)
return 1;
switch (file->source.type) {
case GIT_ATTR_FILE_SOURCE_MEMORY:
return 0;
case GIT_ATTR_FILE_SOURCE_FILE:
return git_futils_filestamp_check(
&file->cache_data.stamp, file->entry->fullpath);
case GIT_ATTR_FILE_SOURCE_INDEX: {
int error;
git_oid id;
if ((error = attr_file_oid_from_index(
&id, repo, file->entry->path)) < 0)
return error;
return (git_oid__cmp(&file->cache_data.oid, &id) != 0);
}
case GIT_ATTR_FILE_SOURCE_HEAD: {
git_tree *tree = NULL;
int error = git_repository_head_tree(&tree, repo);
if (error < 0)
return error;
error = (git_oid__cmp(&file->cache_data.oid, git_tree_id(tree)) != 0);
git_tree_free(tree);
return error;
}
case GIT_ATTR_FILE_SOURCE_COMMIT: {
git_commit *commit = NULL;
git_tree *tree = NULL;
int error;
if ((error = git_commit_lookup(&commit, repo, source->commit_id)) < 0)
return error;
error = git_commit_tree(&tree, commit);
git_commit_free(commit);
if (error < 0)
return error;
error = (git_oid__cmp(&file->cache_data.oid, git_tree_id(tree)) != 0);
git_tree_free(tree);
return error;
}
default:
git_error_set(GIT_ERROR_INVALID, "invalid file type %d", file->source.type);
return -1;
}
}
static int sort_by_hash_and_name(const void *a_raw, const void *b_raw);
static void git_attr_rule__clear(git_attr_rule *rule);
static bool parse_optimized_patterns(
git_attr_fnmatch *spec,
git_pool *pool,
const char *pattern);
int git_attr_file__parse_buffer(
git_repository *repo, git_attr_file *attrs, const char *data, bool allow_macros)
{
const char *scan = data, *context = NULL;
git_attr_rule *rule = NULL;
int error = 0;
/* If subdir file path, convert context for file paths */
if (attrs->entry && git_path_root(attrs->entry->path) < 0 &&
!git__suffixcmp(attrs->entry->path, "/" GIT_ATTR_FILE))
context = attrs->entry->path;
if (git_mutex_lock(&attrs->lock) < 0) {
git_error_set(GIT_ERROR_OS, "failed to lock attribute file");
return -1;
}
while (!error && *scan) {
/* Allocate rule if needed, otherwise re-use previous rule */
if (!rule) {
rule = git__calloc(1, sizeof(*rule));
GIT_ERROR_CHECK_ALLOC(rule);
} else
git_attr_rule__clear(rule);
rule->match.flags = GIT_ATTR_FNMATCH_ALLOWNEG | GIT_ATTR_FNMATCH_ALLOWMACRO;
/* Parse the next "pattern attr attr attr" line */
if ((error = git_attr_fnmatch__parse(&rule->match, &attrs->pool, context, &scan)) < 0 ||
(error = git_attr_assignment__parse(repo, &attrs->pool, &rule->assigns, &scan)) < 0)
{
if (error != GIT_ENOTFOUND)
goto out;
error = 0;
continue;
}
if (rule->match.flags & GIT_ATTR_FNMATCH_MACRO) {
/* TODO: warning if macro found in file below repo root */
if (!allow_macros)
continue;
if ((error = git_attr_cache__insert_macro(repo, rule)) < 0)
goto out;
} else if ((error = git_vector_insert(&attrs->rules, rule)) < 0)
goto out;
rule = NULL;
}
out:
git_mutex_unlock(&attrs->lock);
git_attr_rule__free(rule);
return error;
}
uint32_t git_attr_file__name_hash(const char *name)
{
uint32_t h = 5381;
int c;
GIT_ASSERT_ARG(name);
while ((c = (int)*name++) != 0)
h = ((h << 5) + h) + c;
return h;
}
int git_attr_file__lookup_one(
git_attr_file *file,
git_attr_path *path,
const char *attr,
const char **value)
{
size_t i;
git_attr_name name;
git_attr_rule *rule;
*value = NULL;
name.name = attr;
name.name_hash = git_attr_file__name_hash(attr);
git_attr_file__foreach_matching_rule(file, path, i, rule) {
size_t pos;
if (!git_vector_bsearch(&pos, &rule->assigns, &name)) {
*value = ((git_attr_assignment *)
git_vector_get(&rule->assigns, pos))->value;
break;
}
}
return 0;
}
int git_attr_file__load_standalone(git_attr_file **out, const char *path)
{
git_buf content = GIT_BUF_INIT;
git_attr_file_source source = { GIT_ATTR_FILE_SOURCE_FILE };
git_attr_file *file = NULL;
int error;
if ((error = git_futils_readbuffer(&content, path)) < 0)
goto out;
/*
* Because the cache entry is allocated from the file's own pool, we
* don't have to free it - freeing file+pool will free cache entry, too.
*/
if ((error = git_attr_file__new(&file, NULL, &source)) < 0 ||
(error = git_attr_file__parse_buffer(NULL, file, content.ptr, true)) < 0 ||
(error = git_attr_cache__alloc_file_entry(&file->entry, NULL, NULL, path, &file->pool)) < 0)
goto out;
*out = file;
out:
if (error < 0)
git_attr_file__free(file);
git_buf_dispose(&content);
return error;
}
bool git_attr_fnmatch__match(
git_attr_fnmatch *match,
git_attr_path *path)
{
const char *relpath = path->path;
const char *filename;
int flags = 0;
/*
* If the rule was generated in a subdirectory, we must only
* use it for paths inside that directory. We can thus return
* a non-match if the prefixes don't match.
*/
if (match->containing_dir) {
if (match->flags & GIT_ATTR_FNMATCH_ICASE) {
if (git__strncasecmp(path->path, match->containing_dir, match->containing_dir_length))
return 0;
} else {
if (git__prefixcmp(path->path, match->containing_dir))
return 0;
}
relpath += match->containing_dir_length;
}
if (match->flags & GIT_ATTR_FNMATCH_ICASE)
flags |= WM_CASEFOLD;
if (match->flags & GIT_ATTR_FNMATCH_FULLPATH) {
filename = relpath;
flags |= WM_PATHNAME;
} else {
filename = path->basename;
}
if ((match->flags & GIT_ATTR_FNMATCH_DIRECTORY) && !path->is_dir) {
bool samename;
/*
* for attribute checks or checks at the root of this match's
* containing_dir (or root of the repository if no containing_dir),
* do not match.
*/
if (!(match->flags & GIT_ATTR_FNMATCH_IGNORE) ||
path->basename == relpath)
return false;
/* fail match if this is a file with same name as ignored folder */
samename = (match->flags & GIT_ATTR_FNMATCH_ICASE) ?
!strcasecmp(match->pattern, relpath) :
!strcmp(match->pattern, relpath);
if (samename)
return false;
return (wildmatch(match->pattern, relpath, flags) == WM_MATCH);
}
return (wildmatch(match->pattern, filename, flags) == WM_MATCH);
}
bool git_attr_rule__match(
git_attr_rule *rule,
git_attr_path *path)
{
bool matched = git_attr_fnmatch__match(&rule->match, path);
if (rule->match.flags & GIT_ATTR_FNMATCH_NEGATIVE)
matched = !matched;
return matched;
}
git_attr_assignment *git_attr_rule__lookup_assignment(
git_attr_rule *rule, const char *name)
{
size_t pos;
git_attr_name key;
key.name = name;
key.name_hash = git_attr_file__name_hash(name);
if (git_vector_bsearch(&pos, &rule->assigns, &key))
return NULL;
return git_vector_get(&rule->assigns, pos);
}
int git_attr_path__init(
git_attr_path *info,
const char *path,
const char *base,
git_dir_flag dir_flag)
{
ssize_t root;
/* build full path as best we can */
git_buf_init(&info->full, 0);
if (git_path_join_unrooted(&info->full, path, base, &root) < 0)
return -1;
info->path = info->full.ptr + root;
/* remove trailing slashes */
while (info->full.size > 0) {
if (info->full.ptr[info->full.size - 1] != '/')
break;
info->full.size--;
}
info->full.ptr[info->full.size] = '\0';
/* skip leading slashes in path */
while (*info->path == '/')
info->path++;
/* find trailing basename component */
info->basename = strrchr(info->path, '/');
if (info->basename)
info->basename++;
if (!info->basename || !*info->basename)
info->basename = info->path;
switch (dir_flag)
{
case GIT_DIR_FLAG_FALSE:
info->is_dir = 0;
break;
case GIT_DIR_FLAG_TRUE:
info->is_dir = 1;
break;
case GIT_DIR_FLAG_UNKNOWN:
default:
info->is_dir = (int)git_path_isdir(info->full.ptr);
break;
}
return 0;
}
void git_attr_path__free(git_attr_path *info)
{
git_buf_dispose(&info->full);
info->path = NULL;
info->basename = NULL;
}
/*
* From gitattributes(5):
*
* Patterns have the following format:
*
* - A blank line matches no files, so it can serve as a separator for
* readability.
*
* - A line starting with # serves as a comment.
*
* - An optional prefix ! which negates the pattern; any matching file
* excluded by a previous pattern will become included again. If a negated
* pattern matches, this will override lower precedence patterns sources.
*
* - If the pattern ends with a slash, it is removed for the purpose of the
* following description, but it would only find a match with a directory. In
* other words, foo/ will match a directory foo and paths underneath it, but
* will not match a regular file or a symbolic link foo (this is consistent
* with the way how pathspec works in general in git).
*
* - If the pattern does not contain a slash /, git treats it as a shell glob
* pattern and checks for a match against the pathname without leading
* directories.
*
* - Otherwise, git treats the pattern as a shell glob suitable for consumption
* by fnmatch(3) with the FNM_PATHNAME flag: wildcards in the pattern will
* not match a / in the pathname. For example, "Documentation/\*.html" matches
* "Documentation/git.html" but not "Documentation/ppc/ppc.html". A leading
* slash matches the beginning of the pathname; for example, "/\*.c" matches
* "cat-file.c" but not "mozilla-sha1/sha1.c".
*/
/*
* Determine the length of trailing spaces. Escaped spaces do not count as
* trailing whitespace.
*/
static size_t trailing_space_length(const char *p, size_t len)
{
size_t n, i;
for (n = len; n; n--) {
if (p[n-1] != ' ' && p[n-1] != '\t')
break;
/*
* Count escape-characters before space. In case where it's an
* even number of escape characters, then the escape char itself
* is escaped and the whitespace is an unescaped whitespace.
* Otherwise, the last escape char is not escaped and the
* whitespace in an escaped whitespace.
*/
i = n;
while (i > 1 && p[i-2] == '\\')
i--;
if ((n - i) % 2)
break;
}
return len - n;
}
static size_t unescape_spaces(char *str)
{
char *scan, *pos = str;
bool escaped = false;
if (!str)
return 0;
for (scan = str; *scan; scan++) {
if (!escaped && *scan == '\\') {
escaped = true;
continue;
}
/* Only insert the escape character for escaped non-spaces */
if (escaped && !git__isspace(*scan))
*pos++ = '\\';
*pos++ = *scan;
escaped = false;
}
if (pos != scan)
*pos = '\0';
return (pos - str);
}
/*
* This will return 0 if the spec was filled out,
* GIT_ENOTFOUND if the fnmatch does not require matching, or
* another error code there was an actual problem.
*/
int git_attr_fnmatch__parse(
git_attr_fnmatch *spec,
git_pool *pool,
const char *context,
const char **base)
{
const char *pattern, *scan;
int slash_count, allow_space;
bool escaped;
GIT_ASSERT_ARG(spec);
GIT_ASSERT_ARG(base && *base);
if (parse_optimized_patterns(spec, pool, *base))
return 0;
spec->flags = (spec->flags & GIT_ATTR_FNMATCH__INCOMING);
allow_space = ((spec->flags & GIT_ATTR_FNMATCH_ALLOWSPACE) != 0);
pattern = *base;
while (!allow_space && git__isspace(*pattern))
pattern++;
if (!*pattern || *pattern == '#' || *pattern == '\n' ||
(*pattern == '\r' && *(pattern + 1) == '\n')) {
*base = git__next_line(pattern);
return GIT_ENOTFOUND;
}
if (*pattern == '[' && (spec->flags & GIT_ATTR_FNMATCH_ALLOWMACRO) != 0) {
if (strncmp(pattern, "[attr]", 6) == 0) {
spec->flags = spec->flags | GIT_ATTR_FNMATCH_MACRO;
pattern += 6;
}
/* else a character range like [a-e]* which is accepted */
}
if (*pattern == '!' && (spec->flags & GIT_ATTR_FNMATCH_ALLOWNEG) != 0) {
spec->flags = spec->flags | GIT_ATTR_FNMATCH_NEGATIVE;
pattern++;
}
slash_count = 0;
escaped = false;
/* Scan until a non-escaped whitespace. */
for (scan = pattern; *scan != '\0'; ++scan) {
char c = *scan;
if (c == '\\' && !escaped) {
escaped = true;
continue;
} else if (git__isspace(c) && !escaped) {
if (!allow_space || (c != ' ' && c != '\t' && c != '\r'))
break;
} else if (c == '/') {
spec->flags = spec->flags | GIT_ATTR_FNMATCH_FULLPATH;
slash_count++;
if (slash_count == 1 && pattern == scan)
pattern++;
} else if (git__iswildcard(c) && !escaped) {
/* remember if we see an unescaped wildcard in pattern */
spec->flags = spec->flags | GIT_ATTR_FNMATCH_HASWILD;
}
escaped = false;
}
*base = scan;
if ((spec->length = scan - pattern) == 0)
return GIT_ENOTFOUND;
/*
* Remove one trailing \r in case this is a CRLF delimited
* file, in the case of Icon\r\r\n, we still leave the first
* \r there to match against.
*/
if (pattern[spec->length - 1] == '\r')
if (--spec->length == 0)
return GIT_ENOTFOUND;
/* Remove trailing spaces. */
spec->length -= trailing_space_length(pattern, spec->length);
if (spec->length == 0)
return GIT_ENOTFOUND;
if (pattern[spec->length - 1] == '/') {
spec->length--;
spec->flags = spec->flags | GIT_ATTR_FNMATCH_DIRECTORY;
if (--slash_count <= 0)
spec->flags = spec->flags & ~GIT_ATTR_FNMATCH_FULLPATH;
}
if (context) {
char *slash = strrchr(context, '/');
size_t len;
if (slash) {
/* include the slash for easier matching */
len = slash - context + 1;
spec->containing_dir = git_pool_strndup(pool, context, len);
spec->containing_dir_length = len;
}
}
spec->pattern = git_pool_strndup(pool, pattern, spec->length);
if (!spec->pattern) {
*base = git__next_line(pattern);
return -1;
} else {
/* strip '\' that might have been used for internal whitespace */
spec->length = unescape_spaces(spec->pattern);
}
return 0;
}
static bool parse_optimized_patterns(
git_attr_fnmatch *spec,
git_pool *pool,
const char *pattern)
{
if (!pattern[1] && (pattern[0] == '*' || pattern[0] == '.')) {
spec->flags = GIT_ATTR_FNMATCH_MATCH_ALL;
spec->pattern = git_pool_strndup(pool, pattern, 1);
spec->length = 1;
return true;
}
return false;
}
static int sort_by_hash_and_name(const void *a_raw, const void *b_raw)
{
const git_attr_name *a = a_raw;
const git_attr_name *b = b_raw;
if (b->name_hash < a->name_hash)
return 1;
else if (b->name_hash > a->name_hash)
return -1;
else
return strcmp(b->name, a->name);
}
static void git_attr_assignment__free(git_attr_assignment *assign)
{
/* name and value are stored in a git_pool associated with the
* git_attr_file, so they do not need to be freed here
*/
assign->name = NULL;
assign->value = NULL;
git__free(assign);
}
static int merge_assignments(void **old_raw, void *new_raw)
{
git_attr_assignment **old = (git_attr_assignment **)old_raw;
git_attr_assignment *new = (git_attr_assignment *)new_raw;
GIT_REFCOUNT_DEC(*old, git_attr_assignment__free);
*old = new;
return GIT_EEXISTS;
}
int git_attr_assignment__parse(
git_repository *repo,
git_pool *pool,
git_vector *assigns,
const char **base)
{
int error;
const char *scan = *base;
git_attr_assignment *assign = NULL;
GIT_ASSERT_ARG(assigns && !assigns->length);
git_vector_set_cmp(assigns, sort_by_hash_and_name);
while (*scan && *scan != '\n') {
const char *name_start, *value_start;
/* skip leading blanks */
while (git__isspace(*scan) && *scan != '\n') scan++;
/* allocate assign if needed */
if (!assign) {
assign = git__calloc(1, sizeof(git_attr_assignment));
GIT_ERROR_CHECK_ALLOC(assign);
GIT_REFCOUNT_INC(assign);
}
assign->name_hash = 5381;
assign->value = git_attr__true;
/* look for magic name prefixes */
if (*scan == '-') {
assign->value = git_attr__false;
scan++;
} else if (*scan == '!') {
assign->value = git_attr__unset; /* explicit unspecified state */
scan++;
} else if (*scan == '#') /* comment rest of line */
break;
/* find the name */
name_start = scan;
while (*scan && !git__isspace(*scan) && *scan != '=') {
assign->name_hash =
((assign->name_hash << 5) + assign->name_hash) + *scan;
scan++;
}
if (scan == name_start) {
/* must have found lone prefix (" - ") or leading = ("=foo")
* or end of buffer -- advance until whitespace and continue
*/
while (*scan && !git__isspace(*scan)) scan++;
continue;
}
/* allocate permanent storage for name */
assign->name = git_pool_strndup(pool, name_start, scan - name_start);
GIT_ERROR_CHECK_ALLOC(assign->name);
/* if there is an equals sign, find the value */
if (*scan == '=') {
for (value_start = ++scan; *scan && !git__isspace(*scan); ++scan);
/* if we found a value, allocate permanent storage for it */
if (scan > value_start) {
assign->value = git_pool_strndup(pool, value_start, scan - value_start);
GIT_ERROR_CHECK_ALLOC(assign->value);
}
}
/* expand macros (if given a repo with a macro cache) */
if (repo != NULL && assign->value == git_attr__true) {
git_attr_rule *macro =
git_attr_cache__lookup_macro(repo, assign->name);
if (macro != NULL) {
unsigned int i;
git_attr_assignment *massign;
git_vector_foreach(¯o->assigns, i, massign) {
GIT_REFCOUNT_INC(massign);
error = git_vector_insert_sorted(
assigns, massign, &merge_assignments);
if (error < 0 && error != GIT_EEXISTS) {
git_attr_assignment__free(assign);
return error;
}
}
}
}
/* insert allocated assign into vector */
error = git_vector_insert_sorted(assigns, assign, &merge_assignments);
if (error < 0 && error != GIT_EEXISTS)
return error;
/* clear assign since it is now "owned" by the vector */
assign = NULL;
}
if (assign != NULL)
git_attr_assignment__free(assign);
*base = git__next_line(scan);
return (assigns->length == 0) ? GIT_ENOTFOUND : 0;
}
static void git_attr_rule__clear(git_attr_rule *rule)
{
unsigned int i;
git_attr_assignment *assign;
if (!rule)
return;
if (!(rule->match.flags & GIT_ATTR_FNMATCH_IGNORE)) {
git_vector_foreach(&rule->assigns, i, assign)
GIT_REFCOUNT_DEC(assign, git_attr_assignment__free);
git_vector_free(&rule->assigns);
}
/* match.pattern is stored in a git_pool, so no need to free */
rule->match.pattern = NULL;
rule->match.length = 0;
}
void git_attr_rule__free(git_attr_rule *rule)
{
git_attr_rule__clear(rule);
git__free(rule);
}
int git_attr_session__init(git_attr_session *session, git_repository *repo)
{
GIT_ASSERT_ARG(repo);
memset(session, 0, sizeof(*session));
session->key = git_atomic32_inc(&repo->attr_session_key);
return 0;
}
void git_attr_session__free(git_attr_session *session)
{
if (!session)
return;
git_buf_dispose(&session->sysdir);
git_buf_dispose(&session->tmp);
memset(session, 0, sizeof(git_attr_session));
}
|
0 |
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2
|
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2/src/blob.h
|
/*
* Copyright (C) the libgit2 contributors. All rights reserved.
*
* This file is part of libgit2, distributed under the GNU GPL v2 with
* a Linking Exception. For full terms see the included COPYING file.
*/
#ifndef INCLUDE_blob_h__
#define INCLUDE_blob_h__
#include "common.h"
#include "git2/blob.h"
#include "repository.h"
#include "odb.h"
#include "futils.h"
struct git_blob {
git_object object;
union {
git_odb_object *odb;
struct {
const char *data;
git_object_size_t size;
} raw;
} data;
unsigned int raw:1;
};
#define GIT_ERROR_CHECK_BLOBSIZE(n) \
do { \
if (!git__is_sizet(n)) { \
git_error_set(GIT_ERROR_NOMEMORY, "blob contents too large to fit in memory"); \
return -1; \
} \
} while(0)
void git_blob__free(void *blob);
int git_blob__parse(void *blob, git_odb_object *obj);
int git_blob__parse_raw(void *blob, const char *data, size_t size);
int git_blob__getbuf(git_buf *buffer, git_blob *blob);
extern int git_blob__create_from_paths(
git_oid *out_oid,
struct stat *out_st,
git_repository *repo,
const char *full_path,
const char *hint_path,
mode_t hint_mode,
bool apply_filters);
#endif
|
0 |
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2
|
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2/src/annotated_commit.c
|
/*
* Copyright (C) the libgit2 contributors. All rights reserved.
*
* This file is part of libgit2, distributed under the GNU GPL v2 with
* a Linking Exception. For full terms see the included COPYING file.
*/
#include "annotated_commit.h"
#include "refs.h"
#include "cache.h"
#include "git2/commit.h"
#include "git2/refs.h"
#include "git2/repository.h"
#include "git2/annotated_commit.h"
#include "git2/revparse.h"
#include "git2/tree.h"
#include "git2/index.h"
static int annotated_commit_init(
git_annotated_commit **out,
git_commit *commit,
const char *description)
{
git_annotated_commit *annotated_commit;
int error = 0;
GIT_ASSERT_ARG(out);
GIT_ASSERT_ARG(commit);
*out = NULL;
annotated_commit = git__calloc(1, sizeof(git_annotated_commit));
GIT_ERROR_CHECK_ALLOC(annotated_commit);
annotated_commit->type = GIT_ANNOTATED_COMMIT_REAL;
if ((error = git_commit_dup(&annotated_commit->commit, commit)) < 0)
goto done;
git_oid_fmt(annotated_commit->id_str, git_commit_id(commit));
annotated_commit->id_str[GIT_OID_HEXSZ] = '\0';
if (!description)
description = annotated_commit->id_str;
annotated_commit->description = git__strdup(description);
GIT_ERROR_CHECK_ALLOC(annotated_commit->description);
done:
if (!error)
*out = annotated_commit;
return error;
}
static int annotated_commit_init_from_id(
git_annotated_commit **out,
git_repository *repo,
const git_oid *id,
const char *description)
{
git_commit *commit = NULL;
int error = 0;
GIT_ASSERT_ARG(out);
GIT_ASSERT_ARG(repo);
GIT_ASSERT_ARG(id);
*out = NULL;
if ((error = git_commit_lookup(&commit, repo, id)) < 0)
goto done;
error = annotated_commit_init(out, commit, description);
done:
git_commit_free(commit);
return error;
}
int git_annotated_commit_lookup(
git_annotated_commit **out,
git_repository *repo,
const git_oid *id)
{
return annotated_commit_init_from_id(out, repo, id, NULL);
}
int git_annotated_commit_from_commit(
git_annotated_commit **out,
git_commit *commit)
{
return annotated_commit_init(out, commit, NULL);
}
int git_annotated_commit_from_revspec(
git_annotated_commit **out,
git_repository *repo,
const char *revspec)
{
git_object *obj, *commit;
int error;
GIT_ASSERT_ARG(out);
GIT_ASSERT_ARG(repo);
GIT_ASSERT_ARG(revspec);
if ((error = git_revparse_single(&obj, repo, revspec)) < 0)
return error;
if ((error = git_object_peel(&commit, obj, GIT_OBJECT_COMMIT))) {
git_object_free(obj);
return error;
}
error = annotated_commit_init(out, (git_commit *)commit, revspec);
git_object_free(obj);
git_object_free(commit);
return error;
}
int git_annotated_commit_from_ref(
git_annotated_commit **out,
git_repository *repo,
const git_reference *ref)
{
git_object *peeled;
int error = 0;
GIT_ASSERT_ARG(out);
GIT_ASSERT_ARG(repo);
GIT_ASSERT_ARG(ref);
*out = NULL;
if ((error = git_reference_peel(&peeled, ref, GIT_OBJECT_COMMIT)) < 0)
return error;
error = annotated_commit_init_from_id(out,
repo,
git_object_id(peeled),
git_reference_name(ref));
if (!error) {
(*out)->ref_name = git__strdup(git_reference_name(ref));
GIT_ERROR_CHECK_ALLOC((*out)->ref_name);
}
git_object_free(peeled);
return error;
}
int git_annotated_commit_from_head(
git_annotated_commit **out,
git_repository *repo)
{
git_reference *head;
int error;
GIT_ASSERT_ARG(out);
GIT_ASSERT_ARG(repo);
*out = NULL;
if ((error = git_reference_lookup(&head, repo, GIT_HEAD_FILE)) < 0)
return -1;
error = git_annotated_commit_from_ref(out, repo, head);
git_reference_free(head);
return error;
}
int git_annotated_commit_from_fetchhead(
git_annotated_commit **out,
git_repository *repo,
const char *branch_name,
const char *remote_url,
const git_oid *id)
{
GIT_ASSERT_ARG(out);
GIT_ASSERT_ARG(repo);
GIT_ASSERT_ARG(branch_name);
GIT_ASSERT_ARG(remote_url);
GIT_ASSERT_ARG(id);
if (annotated_commit_init_from_id(out, repo, id, branch_name) < 0)
return -1;
(*out)->ref_name = git__strdup(branch_name);
GIT_ERROR_CHECK_ALLOC((*out)->ref_name);
(*out)->remote_url = git__strdup(remote_url);
GIT_ERROR_CHECK_ALLOC((*out)->remote_url);
return 0;
}
const git_oid *git_annotated_commit_id(
const git_annotated_commit *annotated_commit)
{
GIT_ASSERT_ARG_WITH_RETVAL(annotated_commit, NULL);
return git_commit_id(annotated_commit->commit);
}
const char *git_annotated_commit_ref(
const git_annotated_commit *annotated_commit)
{
GIT_ASSERT_ARG_WITH_RETVAL(annotated_commit, NULL);
return annotated_commit->ref_name;
}
void git_annotated_commit_free(git_annotated_commit *annotated_commit)
{
if (annotated_commit == NULL)
return;
switch (annotated_commit->type) {
case GIT_ANNOTATED_COMMIT_REAL:
git_commit_free(annotated_commit->commit);
git_tree_free(annotated_commit->tree);
git__free((char *)annotated_commit->description);
git__free((char *)annotated_commit->ref_name);
git__free((char *)annotated_commit->remote_url);
break;
case GIT_ANNOTATED_COMMIT_VIRTUAL:
git_index_free(annotated_commit->index);
git_array_clear(annotated_commit->parents);
break;
default:
abort();
}
git__free(annotated_commit);
}
|
0 |
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2
|
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2/src/wildmatch.c
|
/*
* Copyright (C) the libgit2 contributors. All rights reserved.
*
* This file is part of libgit2, distributed under the GNU GPL v2 with
* a Linking Exception. For full terms see the included COPYING file.
*
* Do shell-style pattern matching for ?, \, [], and * characters.
* It is 8bit clean.
*
* Written by Rich $alz, mirror!rs, Wed Nov 26 19:03:17 EST 1986.
* Rich $alz is now <[email protected]>.
*
* Modified by Wayne Davison to special-case '/' matching, to make '**'
* work differently than '*', and to fix the character-class code.
*
* Imported from git.git.
*/
#include "wildmatch.h"
#define GIT_SPACE 0x01
#define GIT_DIGIT 0x02
#define GIT_ALPHA 0x04
#define GIT_GLOB_SPECIAL 0x08
#define GIT_REGEX_SPECIAL 0x10
#define GIT_PATHSPEC_MAGIC 0x20
#define GIT_CNTRL 0x40
#define GIT_PUNCT 0x80
enum {
S = GIT_SPACE,
A = GIT_ALPHA,
D = GIT_DIGIT,
G = GIT_GLOB_SPECIAL, /* *, ?, [, \\ */
R = GIT_REGEX_SPECIAL, /* $, (, ), +, ., ^, {, | */
P = GIT_PATHSPEC_MAGIC, /* other non-alnum, except for ] and } */
X = GIT_CNTRL,
U = GIT_PUNCT,
Z = GIT_CNTRL | GIT_SPACE
};
static const unsigned char sane_ctype[256] = {
X, X, X, X, X, X, X, X, X, Z, Z, X, X, Z, X, X, /* 0.. 15 */
X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, /* 16.. 31 */
S, P, P, P, R, P, P, P, R, R, G, R, P, P, R, P, /* 32.. 47 */
D, D, D, D, D, D, D, D, D, D, P, P, P, P, P, G, /* 48.. 63 */
P, A, A, A, A, A, A, A, A, A, A, A, A, A, A, A, /* 64.. 79 */
A, A, A, A, A, A, A, A, A, A, A, G, G, U, R, P, /* 80.. 95 */
P, A, A, A, A, A, A, A, A, A, A, A, A, A, A, A, /* 96..111 */
A, A, A, A, A, A, A, A, A, A, A, R, R, U, P, X, /* 112..127 */
/* Nothing in the 128.. range */
};
#define sane_istest(x,mask) ((sane_ctype[(unsigned char)(x)] & (mask)) != 0)
#define is_glob_special(x) sane_istest(x,GIT_GLOB_SPECIAL)
typedef unsigned char uchar;
/* What character marks an inverted character class? */
#define NEGATE_CLASS '!'
#define NEGATE_CLASS2 '^'
#define CC_EQ(class, len, litmatch) ((len) == sizeof (litmatch)-1 \
&& *(class) == *(litmatch) \
&& strncmp((char*)class, litmatch, len) == 0)
#if defined STDC_HEADERS || !defined isascii
# define ISASCII(c) 1
#else
# define ISASCII(c) isascii(c)
#endif
#ifdef isblank
# define ISBLANK(c) (ISASCII(c) && isblank(c))
#else
# define ISBLANK(c) ((c) == ' ' || (c) == '\t')
#endif
#ifdef isgraph
# define ISGRAPH(c) (ISASCII(c) && isgraph(c))
#else
# define ISGRAPH(c) (ISASCII(c) && isprint(c) && !isspace(c))
#endif
#define ISPRINT(c) (ISASCII(c) && isprint(c))
#define ISDIGIT(c) (ISASCII(c) && isdigit(c))
#define ISALNUM(c) (ISASCII(c) && isalnum(c))
#define ISALPHA(c) (ISASCII(c) && isalpha(c))
#define ISCNTRL(c) (ISASCII(c) && iscntrl(c))
#define ISLOWER(c) (ISASCII(c) && islower(c))
#define ISPUNCT(c) (ISASCII(c) && ispunct(c))
#define ISSPACE(c) (ISASCII(c) && isspace(c))
#define ISUPPER(c) (ISASCII(c) && isupper(c))
#define ISXDIGIT(c) (ISASCII(c) && isxdigit(c))
/* Match pattern "p" against "text" */
static int dowild(const uchar *p, const uchar *text, unsigned int flags)
{
uchar p_ch;
const uchar *pattern = p;
for ( ; (p_ch = *p) != '\0'; text++, p++) {
int matched, match_slash, negated;
uchar t_ch, prev_ch;
if ((t_ch = *text) == '\0' && p_ch != '*')
return WM_ABORT_ALL;
if ((flags & WM_CASEFOLD) && ISUPPER(t_ch))
t_ch = tolower(t_ch);
if ((flags & WM_CASEFOLD) && ISUPPER(p_ch))
p_ch = tolower(p_ch);
switch (p_ch) {
case '\\':
/* Literal match with following character. Note that the test
* in "default" handles the p[1] == '\0' failure case. */
p_ch = *++p;
/* FALLTHROUGH */
default:
if (t_ch != p_ch)
return WM_NOMATCH;
continue;
case '?':
/* Match anything but '/'. */
if ((flags & WM_PATHNAME) && t_ch == '/')
return WM_NOMATCH;
continue;
case '*':
if (*++p == '*') {
const uchar *prev_p = p - 2;
while (*++p == '*') {}
if (!(flags & WM_PATHNAME))
/* without WM_PATHNAME, '*' == '**' */
match_slash = 1;
else if ((prev_p < pattern || *prev_p == '/') &&
(*p == '\0' || *p == '/' ||
(p[0] == '\\' && p[1] == '/'))) {
/*
* Assuming we already match 'foo/' and are at
* <star star slash>, just assume it matches
* nothing and go ahead match the rest of the
* pattern with the remaining string. This
* helps make foo/<*><*>/bar (<> because
* otherwise it breaks C comment syntax) match
* both foo/bar and foo/a/bar.
*/
if (p[0] == '/' &&
dowild(p + 1, text, flags) == WM_MATCH)
return WM_MATCH;
match_slash = 1;
} else /* WM_PATHNAME is set */
match_slash = 0;
} else
/* without WM_PATHNAME, '*' == '**' */
match_slash = flags & WM_PATHNAME ? 0 : 1;
if (*p == '\0') {
/* Trailing "**" matches everything. Trailing "*" matches
* only if there are no more slash characters. */
if (!match_slash) {
if (strchr((char*)text, '/') != NULL)
return WM_NOMATCH;
}
return WM_MATCH;
} else if (!match_slash && *p == '/') {
/*
* _one_ asterisk followed by a slash
* with WM_PATHNAME matches the next
* directory
*/
const char *slash = strchr((char*)text, '/');
if (!slash)
return WM_NOMATCH;
text = (const uchar*)slash;
/* the slash is consumed by the top-level for loop */
break;
}
while (1) {
if (t_ch == '\0')
break;
/*
* Try to advance faster when an asterisk is
* followed by a literal. We know in this case
* that the string before the literal
* must belong to "*".
* If match_slash is false, do not look past
* the first slash as it cannot belong to '*'.
*/
if (!is_glob_special(*p)) {
p_ch = *p;
if ((flags & WM_CASEFOLD) && ISUPPER(p_ch))
p_ch = tolower(p_ch);
while ((t_ch = *text) != '\0' &&
(match_slash || t_ch != '/')) {
if ((flags & WM_CASEFOLD) && ISUPPER(t_ch))
t_ch = tolower(t_ch);
if (t_ch == p_ch)
break;
text++;
}
if (t_ch != p_ch)
return WM_NOMATCH;
}
if ((matched = dowild(p, text, flags)) != WM_NOMATCH) {
if (!match_slash || matched != WM_ABORT_TO_STARSTAR)
return matched;
} else if (!match_slash && t_ch == '/')
return WM_ABORT_TO_STARSTAR;
t_ch = *++text;
}
return WM_ABORT_ALL;
case '[':
p_ch = *++p;
#ifdef NEGATE_CLASS2
if (p_ch == NEGATE_CLASS2)
p_ch = NEGATE_CLASS;
#endif
/* Assign literal 1/0 because of "matched" comparison. */
negated = p_ch == NEGATE_CLASS ? 1 : 0;
if (negated) {
/* Inverted character class. */
p_ch = *++p;
}
prev_ch = 0;
matched = 0;
do {
if (!p_ch)
return WM_ABORT_ALL;
if (p_ch == '\\') {
p_ch = *++p;
if (!p_ch)
return WM_ABORT_ALL;
if (t_ch == p_ch)
matched = 1;
} else if (p_ch == '-' && prev_ch && p[1] && p[1] != ']') {
p_ch = *++p;
if (p_ch == '\\') {
p_ch = *++p;
if (!p_ch)
return WM_ABORT_ALL;
}
if (t_ch <= p_ch && t_ch >= prev_ch)
matched = 1;
else if ((flags & WM_CASEFOLD) && ISLOWER(t_ch)) {
uchar t_ch_upper = toupper(t_ch);
if (t_ch_upper <= p_ch && t_ch_upper >= prev_ch)
matched = 1;
}
p_ch = 0; /* This makes "prev_ch" get set to 0. */
} else if (p_ch == '[' && p[1] == ':') {
const uchar *s;
int i;
for (s = p += 2; (p_ch = *p) && p_ch != ']'; p++) {} /*SHARED ITERATOR*/
if (!p_ch)
return WM_ABORT_ALL;
i = (int)(p - s - 1);
if (i < 0 || p[-1] != ':') {
/* Didn't find ":]", so treat like a normal set. */
p = s - 2;
p_ch = '[';
if (t_ch == p_ch)
matched = 1;
continue;
}
if (CC_EQ(s,i, "alnum")) {
if (ISALNUM(t_ch))
matched = 1;
} else if (CC_EQ(s,i, "alpha")) {
if (ISALPHA(t_ch))
matched = 1;
} else if (CC_EQ(s,i, "blank")) {
if (ISBLANK(t_ch))
matched = 1;
} else if (CC_EQ(s,i, "cntrl")) {
if (ISCNTRL(t_ch))
matched = 1;
} else if (CC_EQ(s,i, "digit")) {
if (ISDIGIT(t_ch))
matched = 1;
} else if (CC_EQ(s,i, "graph")) {
if (ISGRAPH(t_ch))
matched = 1;
} else if (CC_EQ(s,i, "lower")) {
if (ISLOWER(t_ch))
matched = 1;
} else if (CC_EQ(s,i, "print")) {
if (ISPRINT(t_ch))
matched = 1;
} else if (CC_EQ(s,i, "punct")) {
if (ISPUNCT(t_ch))
matched = 1;
} else if (CC_EQ(s,i, "space")) {
if (ISSPACE(t_ch))
matched = 1;
} else if (CC_EQ(s,i, "upper")) {
if (ISUPPER(t_ch))
matched = 1;
else if ((flags & WM_CASEFOLD) && ISLOWER(t_ch))
matched = 1;
} else if (CC_EQ(s,i, "xdigit")) {
if (ISXDIGIT(t_ch))
matched = 1;
} else /* malformed [:class:] string */
return WM_ABORT_ALL;
p_ch = 0; /* This makes "prev_ch" get set to 0. */
} else if (t_ch == p_ch)
matched = 1;
} while (prev_ch = p_ch, (p_ch = *++p) != ']');
if (matched == negated ||
((flags & WM_PATHNAME) && t_ch == '/'))
return WM_NOMATCH;
continue;
}
}
return *text ? WM_NOMATCH : WM_MATCH;
}
/* Match the "pattern" against the "text" string. */
int wildmatch(const char *pattern, const char *text, unsigned int flags)
{
return dowild((const uchar*)pattern, (const uchar*)text, flags);
}
|
0 |
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2
|
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2/src/remote.h
|
/*
* Copyright (C) the libgit2 contributors. All rights reserved.
*
* This file is part of libgit2, distributed under the GNU GPL v2 with
* a Linking Exception. For full terms see the included COPYING file.
*/
#ifndef INCLUDE_remote_h__
#define INCLUDE_remote_h__
#include "common.h"
#include "git2/remote.h"
#include "git2/transport.h"
#include "git2/sys/transport.h"
#include "refspec.h"
#include "vector.h"
#include "net.h"
#define GIT_REMOTE_ORIGIN "origin"
struct git_remote {
char *name;
char *url;
char *pushurl;
git_vector refs;
git_vector refspecs;
git_vector active_refspecs;
git_vector passive_refspecs;
git_transport *transport;
git_repository *repo;
git_push *push;
git_indexer_progress stats;
unsigned int need_pack;
git_remote_autotag_option_t download_tags;
int prune_refs;
int passed_refspecs;
};
typedef struct git_remote_connection_opts {
const git_strarray *custom_headers;
const git_proxy_options *proxy;
} git_remote_connection_opts;
#define GIT_REMOTE_CONNECTION_OPTIONS_INIT { NULL, NULL }
int git_remote__connect(git_remote *remote, git_direction direction, const git_remote_callbacks *callbacks, const git_remote_connection_opts *conn);
int git_remote__urlfordirection(git_buf *url_out, struct git_remote *remote, int direction, const git_remote_callbacks *callbacks);
int git_remote__http_proxy(char **out, git_remote *remote, git_net_url *url);
git_refspec *git_remote__matching_refspec(git_remote *remote, const char *refname);
git_refspec *git_remote__matching_dst_refspec(git_remote *remote, const char *refname);
#endif
|
0 |
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2
|
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2/src/patch_generate.h
|
/*
* Copyright (C) the libgit2 contributors. All rights reserved.
*
* This file is part of libgit2, distributed under the GNU GPL v2 with
* a Linking Exception. For full terms see the included COPYING file.
*/
#ifndef INCLUDE_patch_generate_h__
#define INCLUDE_patch_generate_h__
#include "common.h"
#include "diff.h"
#include "diff_file.h"
#include "patch.h"
enum {
GIT_PATCH_GENERATED_ALLOCATED = (1 << 0),
GIT_PATCH_GENERATED_INITIALIZED = (1 << 1),
GIT_PATCH_GENERATED_LOADED = (1 << 2),
/* the two sides are different */
GIT_PATCH_GENERATED_DIFFABLE = (1 << 3),
/* the difference between the two sides has been computed */
GIT_PATCH_GENERATED_DIFFED = (1 << 4),
GIT_PATCH_GENERATED_FLATTENED = (1 << 5),
};
struct git_patch_generated {
struct git_patch base;
git_diff *diff; /* for refcount purposes, maybe NULL for blob diffs */
size_t delta_index;
git_diff_file_content ofile;
git_diff_file_content nfile;
uint32_t flags;
git_pool flattened;
};
typedef struct git_patch_generated git_patch_generated;
extern git_diff_driver *git_patch_generated_driver(git_patch_generated *);
extern void git_patch_generated_old_data(
char **, size_t *, git_patch_generated *);
extern void git_patch_generated_new_data(
char **, size_t *, git_patch_generated *);
extern int git_patch_generated_from_diff(
git_patch **, git_diff *, size_t);
typedef struct git_patch_generated_output git_patch_generated_output;
struct git_patch_generated_output {
/* these callbacks are issued with the diff data */
git_diff_file_cb file_cb;
git_diff_binary_cb binary_cb;
git_diff_hunk_cb hunk_cb;
git_diff_line_cb data_cb;
void *payload;
/* this records the actual error in cases where it may be obscured */
int error;
/* this callback is used to do the diff and drive the other callbacks.
* see diff_xdiff.h for how to use this in practice for now.
*/
int (*diff_cb)(git_patch_generated_output *output,
git_patch_generated *patch);
};
#endif
|
0 |
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2
|
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2/src/filter.c
|
/*
* Copyright (C) the libgit2 contributors. All rights reserved.
*
* This file is part of libgit2, distributed under the GNU GPL v2 with
* a Linking Exception. For full terms see the included COPYING file.
*/
#include "filter.h"
#include "common.h"
#include "futils.h"
#include "hash.h"
#include "repository.h"
#include "runtime.h"
#include "git2/sys/filter.h"
#include "git2/config.h"
#include "blob.h"
#include "attr_file.h"
#include "array.h"
struct git_filter_source {
git_repository *repo;
const char *path;
git_oid oid; /* zero if unknown (which is likely) */
uint16_t filemode; /* zero if unknown */
git_filter_mode_t mode;
git_filter_options options;
};
typedef struct {
const char *filter_name;
git_filter *filter;
void *payload;
} git_filter_entry;
struct git_filter_list {
git_array_t(git_filter_entry) filters;
git_filter_source source;
git_buf *temp_buf;
char path[GIT_FLEX_ARRAY];
};
typedef struct {
char *filter_name;
git_filter *filter;
int priority;
int initialized;
size_t nattrs, nmatches;
char *attrdata;
const char *attrs[GIT_FLEX_ARRAY];
} git_filter_def;
static int filter_def_priority_cmp(const void *a, const void *b)
{
int pa = ((const git_filter_def *)a)->priority;
int pb = ((const git_filter_def *)b)->priority;
return (pa < pb) ? -1 : (pa > pb) ? 1 : 0;
}
struct git_filter_registry {
git_rwlock lock;
git_vector filters;
};
static struct git_filter_registry filter_registry;
static void git_filter_global_shutdown(void);
static int filter_def_scan_attrs(
git_buf *attrs, size_t *nattr, size_t *nmatch, const char *attr_str)
{
const char *start, *scan = attr_str;
int has_eq;
*nattr = *nmatch = 0;
if (!scan)
return 0;
while (*scan) {
while (git__isspace(*scan)) scan++;
for (start = scan, has_eq = 0; *scan && !git__isspace(*scan); ++scan) {
if (*scan == '=')
has_eq = 1;
}
if (scan > start) {
(*nattr)++;
if (has_eq || *start == '-' || *start == '+' || *start == '!')
(*nmatch)++;
if (has_eq)
git_buf_putc(attrs, '=');
git_buf_put(attrs, start, scan - start);
git_buf_putc(attrs, '\0');
}
}
return 0;
}
static void filter_def_set_attrs(git_filter_def *fdef)
{
char *scan = fdef->attrdata;
size_t i;
for (i = 0; i < fdef->nattrs; ++i) {
const char *name, *value;
switch (*scan) {
case '=':
name = scan + 1;
for (scan++; *scan != '='; scan++) /* find '=' */;
*scan++ = '\0';
value = scan;
break;
case '-':
name = scan + 1; value = git_attr__false; break;
case '+':
name = scan + 1; value = git_attr__true; break;
case '!':
name = scan + 1; value = git_attr__unset; break;
default:
name = scan; value = NULL; break;
}
fdef->attrs[i] = name;
fdef->attrs[i + fdef->nattrs] = value;
scan += strlen(scan) + 1;
}
}
static int filter_def_name_key_check(const void *key, const void *fdef)
{
const char *name =
fdef ? ((const git_filter_def *)fdef)->filter_name : NULL;
return name ? git__strcmp(key, name) : -1;
}
static int filter_def_filter_key_check(const void *key, const void *fdef)
{
const void *filter = fdef ? ((const git_filter_def *)fdef)->filter : NULL;
return (key == filter) ? 0 : -1;
}
/* Note: callers must lock the registry before calling this function */
static int filter_registry_insert(
const char *name, git_filter *filter, int priority)
{
git_filter_def *fdef;
size_t nattr = 0, nmatch = 0, alloc_len;
git_buf attrs = GIT_BUF_INIT;
if (filter_def_scan_attrs(&attrs, &nattr, &nmatch, filter->attributes) < 0)
return -1;
GIT_ERROR_CHECK_ALLOC_MULTIPLY(&alloc_len, nattr, 2);
GIT_ERROR_CHECK_ALLOC_MULTIPLY(&alloc_len, alloc_len, sizeof(char *));
GIT_ERROR_CHECK_ALLOC_ADD(&alloc_len, alloc_len, sizeof(git_filter_def));
fdef = git__calloc(1, alloc_len);
GIT_ERROR_CHECK_ALLOC(fdef);
fdef->filter_name = git__strdup(name);
GIT_ERROR_CHECK_ALLOC(fdef->filter_name);
fdef->filter = filter;
fdef->priority = priority;
fdef->nattrs = nattr;
fdef->nmatches = nmatch;
fdef->attrdata = git_buf_detach(&attrs);
filter_def_set_attrs(fdef);
if (git_vector_insert(&filter_registry.filters, fdef) < 0) {
git__free(fdef->filter_name);
git__free(fdef->attrdata);
git__free(fdef);
return -1;
}
git_vector_sort(&filter_registry.filters);
return 0;
}
int git_filter_global_init(void)
{
git_filter *crlf = NULL, *ident = NULL;
int error = 0;
if (git_rwlock_init(&filter_registry.lock) < 0)
return -1;
if ((error = git_vector_init(&filter_registry.filters, 2,
filter_def_priority_cmp)) < 0)
goto done;
if ((crlf = git_crlf_filter_new()) == NULL ||
filter_registry_insert(
GIT_FILTER_CRLF, crlf, GIT_FILTER_CRLF_PRIORITY) < 0 ||
(ident = git_ident_filter_new()) == NULL ||
filter_registry_insert(
GIT_FILTER_IDENT, ident, GIT_FILTER_IDENT_PRIORITY) < 0)
error = -1;
if (!error)
error = git_runtime_shutdown_register(git_filter_global_shutdown);
done:
if (error) {
git_filter_free(crlf);
git_filter_free(ident);
}
return error;
}
static void git_filter_global_shutdown(void)
{
size_t pos;
git_filter_def *fdef;
if (git_rwlock_wrlock(&filter_registry.lock) < 0)
return;
git_vector_foreach(&filter_registry.filters, pos, fdef) {
if (fdef->filter && fdef->filter->shutdown) {
fdef->filter->shutdown(fdef->filter);
fdef->initialized = false;
}
git__free(fdef->filter_name);
git__free(fdef->attrdata);
git__free(fdef);
}
git_vector_free(&filter_registry.filters);
git_rwlock_wrunlock(&filter_registry.lock);
git_rwlock_free(&filter_registry.lock);
}
/* Note: callers must lock the registry before calling this function */
static int filter_registry_find(size_t *pos, const char *name)
{
return git_vector_search2(
pos, &filter_registry.filters, filter_def_name_key_check, name);
}
/* Note: callers must lock the registry before calling this function */
static git_filter_def *filter_registry_lookup(size_t *pos, const char *name)
{
git_filter_def *fdef = NULL;
if (!filter_registry_find(pos, name))
fdef = git_vector_get(&filter_registry.filters, *pos);
return fdef;
}
int git_filter_register(
const char *name, git_filter *filter, int priority)
{
int error;
GIT_ASSERT_ARG(name);
GIT_ASSERT_ARG(filter);
if (git_rwlock_wrlock(&filter_registry.lock) < 0) {
git_error_set(GIT_ERROR_OS, "failed to lock filter registry");
return -1;
}
if (!filter_registry_find(NULL, name)) {
git_error_set(
GIT_ERROR_FILTER, "attempt to reregister existing filter '%s'", name);
error = GIT_EEXISTS;
goto done;
}
error = filter_registry_insert(name, filter, priority);
done:
git_rwlock_wrunlock(&filter_registry.lock);
return error;
}
int git_filter_unregister(const char *name)
{
size_t pos;
git_filter_def *fdef;
int error = 0;
GIT_ASSERT_ARG(name);
/* cannot unregister default filters */
if (!strcmp(GIT_FILTER_CRLF, name) || !strcmp(GIT_FILTER_IDENT, name)) {
git_error_set(GIT_ERROR_FILTER, "cannot unregister filter '%s'", name);
return -1;
}
if (git_rwlock_wrlock(&filter_registry.lock) < 0) {
git_error_set(GIT_ERROR_OS, "failed to lock filter registry");
return -1;
}
if ((fdef = filter_registry_lookup(&pos, name)) == NULL) {
git_error_set(GIT_ERROR_FILTER, "cannot find filter '%s' to unregister", name);
error = GIT_ENOTFOUND;
goto done;
}
git_vector_remove(&filter_registry.filters, pos);
if (fdef->initialized && fdef->filter && fdef->filter->shutdown) {
fdef->filter->shutdown(fdef->filter);
fdef->initialized = false;
}
git__free(fdef->filter_name);
git__free(fdef->attrdata);
git__free(fdef);
done:
git_rwlock_wrunlock(&filter_registry.lock);
return error;
}
static int filter_initialize(git_filter_def *fdef)
{
int error = 0;
if (!fdef->initialized && fdef->filter && fdef->filter->initialize) {
if ((error = fdef->filter->initialize(fdef->filter)) < 0)
return error;
}
fdef->initialized = true;
return 0;
}
git_filter *git_filter_lookup(const char *name)
{
size_t pos;
git_filter_def *fdef;
git_filter *filter = NULL;
if (git_rwlock_rdlock(&filter_registry.lock) < 0) {
git_error_set(GIT_ERROR_OS, "failed to lock filter registry");
return NULL;
}
if ((fdef = filter_registry_lookup(&pos, name)) == NULL ||
(!fdef->initialized && filter_initialize(fdef) < 0))
goto done;
filter = fdef->filter;
done:
git_rwlock_rdunlock(&filter_registry.lock);
return filter;
}
void git_filter_free(git_filter *filter)
{
git__free(filter);
}
git_repository *git_filter_source_repo(const git_filter_source *src)
{
return src->repo;
}
const char *git_filter_source_path(const git_filter_source *src)
{
return src->path;
}
uint16_t git_filter_source_filemode(const git_filter_source *src)
{
return src->filemode;
}
const git_oid *git_filter_source_id(const git_filter_source *src)
{
return git_oid_is_zero(&src->oid) ? NULL : &src->oid;
}
git_filter_mode_t git_filter_source_mode(const git_filter_source *src)
{
return src->mode;
}
uint32_t git_filter_source_flags(const git_filter_source *src)
{
return src->options.flags;
}
static int filter_list_new(
git_filter_list **out, const git_filter_source *src)
{
git_filter_list *fl = NULL;
size_t pathlen = src->path ? strlen(src->path) : 0, alloclen;
GIT_ERROR_CHECK_ALLOC_ADD(&alloclen, sizeof(git_filter_list), pathlen);
GIT_ERROR_CHECK_ALLOC_ADD(&alloclen, alloclen, 1);
fl = git__calloc(1, alloclen);
GIT_ERROR_CHECK_ALLOC(fl);
if (src->path)
memcpy(fl->path, src->path, pathlen);
fl->source.repo = src->repo;
fl->source.path = fl->path;
fl->source.mode = src->mode;
memcpy(&fl->source.options, &src->options, sizeof(git_filter_options));
*out = fl;
return 0;
}
static int filter_list_check_attributes(
const char ***out,
git_repository *repo,
git_filter_session *filter_session,
git_filter_def *fdef,
const git_filter_source *src)
{
const char **strs = git__calloc(fdef->nattrs, sizeof(const char *));
git_attr_options attr_opts = GIT_ATTR_OPTIONS_INIT;
size_t i;
int error;
GIT_ERROR_CHECK_ALLOC(strs);
if ((src->options.flags & GIT_FILTER_NO_SYSTEM_ATTRIBUTES) != 0)
attr_opts.flags |= GIT_ATTR_CHECK_NO_SYSTEM;
if ((src->options.flags & GIT_FILTER_ATTRIBUTES_FROM_HEAD) != 0)
attr_opts.flags |= GIT_ATTR_CHECK_INCLUDE_HEAD;
if ((src->options.flags & GIT_FILTER_ATTRIBUTES_FROM_COMMIT) != 0) {
attr_opts.flags |= GIT_ATTR_CHECK_INCLUDE_COMMIT;
#ifndef GIT_DEPRECATE_HARD
if (src->options.commit_id)
git_oid_cpy(&attr_opts.attr_commit_id, src->options.commit_id);
else
#endif
git_oid_cpy(&attr_opts.attr_commit_id, &src->options.attr_commit_id);
}
error = git_attr_get_many_with_session(
strs, repo, filter_session->attr_session, &attr_opts, src->path, fdef->nattrs, fdef->attrs);
/* if no values were found but no matches are needed, it's okay! */
if (error == GIT_ENOTFOUND && !fdef->nmatches) {
git_error_clear();
git__free((void *)strs);
return 0;
}
for (i = 0; !error && i < fdef->nattrs; ++i) {
const char *want = fdef->attrs[fdef->nattrs + i];
git_attr_value_t want_type, found_type;
if (!want)
continue;
want_type = git_attr_value(want);
found_type = git_attr_value(strs[i]);
if (want_type != found_type)
error = GIT_ENOTFOUND;
else if (want_type == GIT_ATTR_VALUE_STRING &&
strcmp(want, strs[i]) &&
strcmp(want, "*"))
error = GIT_ENOTFOUND;
}
if (error)
git__free((void *)strs);
else
*out = strs;
return error;
}
int git_filter_list_new(
git_filter_list **out,
git_repository *repo,
git_filter_mode_t mode,
uint32_t flags)
{
git_filter_source src = { 0 };
src.repo = repo;
src.path = NULL;
src.mode = mode;
src.options.flags = flags;
return filter_list_new(out, &src);
}
int git_filter_list__load(
git_filter_list **filters,
git_repository *repo,
git_blob *blob, /* can be NULL */
const char *path,
git_filter_mode_t mode,
git_filter_session *filter_session)
{
int error = 0;
git_filter_list *fl = NULL;
git_filter_source src = { 0 };
git_filter_entry *fe;
size_t idx;
git_filter_def *fdef;
if (git_rwlock_rdlock(&filter_registry.lock) < 0) {
git_error_set(GIT_ERROR_OS, "failed to lock filter registry");
return -1;
}
src.repo = repo;
src.path = path;
src.mode = mode;
memcpy(&src.options, &filter_session->options, sizeof(git_filter_options));
if (blob)
git_oid_cpy(&src.oid, git_blob_id(blob));
git_vector_foreach(&filter_registry.filters, idx, fdef) {
const char **values = NULL;
void *payload = NULL;
if (!fdef || !fdef->filter)
continue;
if (fdef->nattrs > 0) {
error = filter_list_check_attributes(
&values, repo,
filter_session, fdef, &src);
if (error == GIT_ENOTFOUND) {
error = 0;
continue;
} else if (error < 0)
break;
}
if (!fdef->initialized && (error = filter_initialize(fdef)) < 0)
break;
if (fdef->filter->check)
error = fdef->filter->check(
fdef->filter, &payload, &src, values);
git__free((void *)values);
if (error == GIT_PASSTHROUGH)
error = 0;
else if (error < 0)
break;
else {
if (!fl) {
if ((error = filter_list_new(&fl, &src)) < 0)
break;
fl->temp_buf = filter_session->temp_buf;
}
fe = git_array_alloc(fl->filters);
GIT_ERROR_CHECK_ALLOC(fe);
fe->filter = fdef->filter;
fe->filter_name = fdef->filter_name;
fe->payload = payload;
}
}
git_rwlock_rdunlock(&filter_registry.lock);
if (error && fl != NULL) {
git_array_clear(fl->filters);
git__free(fl);
fl = NULL;
}
*filters = fl;
return error;
}
int git_filter_list_load_ext(
git_filter_list **filters,
git_repository *repo,
git_blob *blob, /* can be NULL */
const char *path,
git_filter_mode_t mode,
git_filter_options *opts)
{
git_filter_session filter_session = GIT_FILTER_SESSION_INIT;
if (opts)
memcpy(&filter_session.options, opts, sizeof(git_filter_options));
return git_filter_list__load(
filters, repo, blob, path, mode, &filter_session);
}
int git_filter_list_load(
git_filter_list **filters,
git_repository *repo,
git_blob *blob, /* can be NULL */
const char *path,
git_filter_mode_t mode,
uint32_t flags)
{
git_filter_session filter_session = GIT_FILTER_SESSION_INIT;
filter_session.options.flags = flags;
return git_filter_list__load(
filters, repo, blob, path, mode, &filter_session);
}
void git_filter_list_free(git_filter_list *fl)
{
uint32_t i;
if (!fl)
return;
for (i = 0; i < git_array_size(fl->filters); ++i) {
git_filter_entry *fe = git_array_get(fl->filters, i);
if (fe->filter->cleanup)
fe->filter->cleanup(fe->filter, fe->payload);
}
git_array_clear(fl->filters);
git__free(fl);
}
int git_filter_list_contains(
git_filter_list *fl,
const char *name)
{
size_t i;
GIT_ASSERT_ARG(name);
if (!fl)
return 0;
for (i = 0; i < fl->filters.size; i++) {
if (strcmp(fl->filters.ptr[i].filter_name, name) == 0)
return 1;
}
return 0;
}
int git_filter_list_push(
git_filter_list *fl, git_filter *filter, void *payload)
{
int error = 0;
size_t pos;
git_filter_def *fdef = NULL;
git_filter_entry *fe;
GIT_ASSERT_ARG(fl);
GIT_ASSERT_ARG(filter);
if (git_rwlock_rdlock(&filter_registry.lock) < 0) {
git_error_set(GIT_ERROR_OS, "failed to lock filter registry");
return -1;
}
if (git_vector_search2(
&pos, &filter_registry.filters,
filter_def_filter_key_check, filter) == 0)
fdef = git_vector_get(&filter_registry.filters, pos);
git_rwlock_rdunlock(&filter_registry.lock);
if (fdef == NULL) {
git_error_set(GIT_ERROR_FILTER, "cannot use an unregistered filter");
return -1;
}
if (!fdef->initialized && (error = filter_initialize(fdef)) < 0)
return error;
fe = git_array_alloc(fl->filters);
GIT_ERROR_CHECK_ALLOC(fe);
fe->filter = filter;
fe->payload = payload;
return 0;
}
size_t git_filter_list_length(const git_filter_list *fl)
{
return fl ? git_array_size(fl->filters) : 0;
}
struct buf_stream {
git_writestream parent;
git_buf *target;
bool complete;
};
static int buf_stream_write(
git_writestream *s, const char *buffer, size_t len)
{
struct buf_stream *buf_stream = (struct buf_stream *)s;
GIT_ASSERT_ARG(buf_stream);
GIT_ASSERT(buf_stream->complete == 0);
return git_buf_put(buf_stream->target, buffer, len);
}
static int buf_stream_close(git_writestream *s)
{
struct buf_stream *buf_stream = (struct buf_stream *)s;
GIT_ASSERT_ARG(buf_stream);
GIT_ASSERT(buf_stream->complete == 0);
buf_stream->complete = 1;
return 0;
}
static void buf_stream_free(git_writestream *s)
{
GIT_UNUSED(s);
}
static void buf_stream_init(struct buf_stream *writer, git_buf *target)
{
memset(writer, 0, sizeof(struct buf_stream));
writer->parent.write = buf_stream_write;
writer->parent.close = buf_stream_close;
writer->parent.free = buf_stream_free;
writer->target = target;
git_buf_clear(target);
}
int git_filter_list_apply_to_buffer(
git_buf *out,
git_filter_list *filters,
const char *in,
size_t in_len)
{
struct buf_stream writer;
int error;
if ((error = git_buf_sanitize(out)) < 0)
return error;
buf_stream_init(&writer, out);
if ((error = git_filter_list_stream_buffer(filters,
in, in_len, &writer.parent)) < 0)
return error;
GIT_ASSERT(writer.complete);
return error;
}
int git_filter_list__convert_buf(
git_buf *out,
git_filter_list *filters,
git_buf *in)
{
int error;
if (!filters || git_filter_list_length(filters) == 0) {
git_buf_swap(out, in);
git_buf_dispose(in);
return 0;
}
error = git_filter_list_apply_to_buffer(out, filters,
in->ptr, in->size);
if (!error)
git_buf_dispose(in);
return error;
}
int git_filter_list_apply_to_file(
git_buf *out,
git_filter_list *filters,
git_repository *repo,
const char *path)
{
struct buf_stream writer;
int error;
buf_stream_init(&writer, out);
if ((error = git_filter_list_stream_file(
filters, repo, path, &writer.parent)) < 0)
return error;
GIT_ASSERT(writer.complete);
return error;
}
static int buf_from_blob(git_buf *out, git_blob *blob)
{
git_object_size_t rawsize = git_blob_rawsize(blob);
if (!git__is_sizet(rawsize)) {
git_error_set(GIT_ERROR_OS, "blob is too large to filter");
return -1;
}
git_buf_attach_notowned(out, git_blob_rawcontent(blob), (size_t)rawsize);
return 0;
}
int git_filter_list_apply_to_blob(
git_buf *out,
git_filter_list *filters,
git_blob *blob)
{
struct buf_stream writer;
int error;
buf_stream_init(&writer, out);
if ((error = git_filter_list_stream_blob(
filters, blob, &writer.parent)) < 0)
return error;
GIT_ASSERT(writer.complete);
return error;
}
struct buffered_stream {
git_writestream parent;
git_filter *filter;
int (*write_fn)(git_filter *, void **, git_buf *, const git_buf *, const git_filter_source *);
const git_filter_source *source;
void **payload;
git_buf input;
git_buf temp_buf;
git_buf *output;
git_writestream *target;
};
static int buffered_stream_write(
git_writestream *s, const char *buffer, size_t len)
{
struct buffered_stream *buffered_stream = (struct buffered_stream *)s;
GIT_ASSERT_ARG(buffered_stream);
return git_buf_put(&buffered_stream->input, buffer, len);
}
static int buffered_stream_close(git_writestream *s)
{
struct buffered_stream *buffered_stream = (struct buffered_stream *)s;
git_buf *writebuf;
git_error_state error_state = {0};
int error;
GIT_ASSERT_ARG(buffered_stream);
error = buffered_stream->write_fn(
buffered_stream->filter,
buffered_stream->payload,
buffered_stream->output,
&buffered_stream->input,
buffered_stream->source);
if (error == GIT_PASSTHROUGH) {
writebuf = &buffered_stream->input;
} else if (error == 0) {
if ((error = git_buf_sanitize(buffered_stream->output)) < 0)
return error;
writebuf = buffered_stream->output;
} else {
/* close stream before erroring out taking care
* to preserve the original error */
git_error_state_capture(&error_state, error);
buffered_stream->target->close(buffered_stream->target);
git_error_state_restore(&error_state);
return error;
}
if ((error = buffered_stream->target->write(
buffered_stream->target, writebuf->ptr, writebuf->size)) == 0)
error = buffered_stream->target->close(buffered_stream->target);
return error;
}
static void buffered_stream_free(git_writestream *s)
{
struct buffered_stream *buffered_stream = (struct buffered_stream *)s;
if (buffered_stream) {
git_buf_dispose(&buffered_stream->input);
git_buf_dispose(&buffered_stream->temp_buf);
git__free(buffered_stream);
}
}
int git_filter_buffered_stream_new(
git_writestream **out,
git_filter *filter,
int (*write_fn)(git_filter *, void **, git_buf *, const git_buf *, const git_filter_source *),
git_buf *temp_buf,
void **payload,
const git_filter_source *source,
git_writestream *target)
{
struct buffered_stream *buffered_stream = git__calloc(1, sizeof(struct buffered_stream));
GIT_ERROR_CHECK_ALLOC(buffered_stream);
buffered_stream->parent.write = buffered_stream_write;
buffered_stream->parent.close = buffered_stream_close;
buffered_stream->parent.free = buffered_stream_free;
buffered_stream->filter = filter;
buffered_stream->write_fn = write_fn;
buffered_stream->output = temp_buf ? temp_buf : &buffered_stream->temp_buf;
buffered_stream->payload = payload;
buffered_stream->source = source;
buffered_stream->target = target;
if (temp_buf)
git_buf_clear(temp_buf);
*out = (git_writestream *)buffered_stream;
return 0;
}
static int setup_stream(
git_writestream **out,
git_filter_entry *fe,
git_filter_list *filters,
git_writestream *last_stream)
{
#ifndef GIT_DEPRECATE_HARD
GIT_ASSERT(fe->filter->stream || fe->filter->apply);
/*
* If necessary, create a stream that proxies the traditional
* application.
*/
if (!fe->filter->stream) {
/* Create a stream that proxies the one-shot apply */
return git_filter_buffered_stream_new(out,
fe->filter, fe->filter->apply, filters->temp_buf,
&fe->payload, &filters->source, last_stream);
}
#endif
GIT_ASSERT(fe->filter->stream);
return fe->filter->stream(out, fe->filter,
&fe->payload, &filters->source, last_stream);
}
static int stream_list_init(
git_writestream **out,
git_vector *streams,
git_filter_list *filters,
git_writestream *target)
{
git_writestream *last_stream = target;
size_t i;
int error = 0;
*out = NULL;
if (!filters) {
*out = target;
return 0;
}
/* Create filters last to first to get the chaining direction */
for (i = 0; i < git_array_size(filters->filters); ++i) {
size_t filter_idx = (filters->source.mode == GIT_FILTER_TO_WORKTREE) ?
git_array_size(filters->filters) - 1 - i : i;
git_filter_entry *fe = git_array_get(filters->filters, filter_idx);
git_writestream *filter_stream;
error = setup_stream(&filter_stream, fe, filters, last_stream);
if (error < 0)
goto out;
git_vector_insert(streams, filter_stream);
last_stream = filter_stream;
}
out:
if (error)
last_stream->close(last_stream);
else
*out = last_stream;
return error;
}
static void filter_streams_free(git_vector *streams)
{
git_writestream *stream;
size_t i;
git_vector_foreach(streams, i, stream)
stream->free(stream);
git_vector_free(streams);
}
int git_filter_list_stream_file(
git_filter_list *filters,
git_repository *repo,
const char *path,
git_writestream *target)
{
char buf[FILTERIO_BUFSIZE];
git_buf abspath = GIT_BUF_INIT;
const char *base = repo ? git_repository_workdir(repo) : NULL;
git_vector filter_streams = GIT_VECTOR_INIT;
git_writestream *stream_start;
ssize_t readlen;
int fd = -1, error, initialized = 0;
if ((error = stream_list_init(
&stream_start, &filter_streams, filters, target)) < 0 ||
(error = git_path_join_unrooted(&abspath, path, base, NULL)) < 0 ||
(error = git_path_validate_workdir_buf(repo, &abspath)) < 0)
goto done;
initialized = 1;
if ((fd = git_futils_open_ro(abspath.ptr)) < 0) {
error = fd;
goto done;
}
while ((readlen = p_read(fd, buf, sizeof(buf))) > 0) {
if ((error = stream_start->write(stream_start, buf, readlen)) < 0)
goto done;
}
if (readlen < 0)
error = -1;
done:
if (initialized)
error |= stream_start->close(stream_start);
if (fd >= 0)
p_close(fd);
filter_streams_free(&filter_streams);
git_buf_dispose(&abspath);
return error;
}
int git_filter_list_stream_buffer(
git_filter_list *filters,
const char *buffer,
size_t len,
git_writestream *target)
{
git_vector filter_streams = GIT_VECTOR_INIT;
git_writestream *stream_start;
int error, initialized = 0;
if ((error = stream_list_init(&stream_start, &filter_streams, filters, target)) < 0)
goto out;
initialized = 1;
if ((error = stream_start->write(stream_start, buffer, len)) < 0)
goto out;
out:
if (initialized)
error |= stream_start->close(stream_start);
filter_streams_free(&filter_streams);
return error;
}
int git_filter_list_stream_blob(
git_filter_list *filters,
git_blob *blob,
git_writestream *target)
{
git_buf in = GIT_BUF_INIT;
if (buf_from_blob(&in, blob) < 0)
return -1;
if (filters)
git_oid_cpy(&filters->source.oid, git_blob_id(blob));
return git_filter_list_stream_buffer(filters, in.ptr, in.size, target);
}
int git_filter_init(git_filter *filter, unsigned int version)
{
GIT_INIT_STRUCTURE_FROM_TEMPLATE(filter, version, git_filter, GIT_FILTER_INIT);
return 0;
}
#ifndef GIT_DEPRECATE_HARD
int git_filter_list_stream_data(
git_filter_list *filters,
git_buf *data,
git_writestream *target)
{
int error;
if ((error = git_buf_sanitize(data)) < 0)
return error;
return git_filter_list_stream_buffer(filters, data->ptr, data->size, target);
}
int git_filter_list_apply_to_data(
git_buf *tgt, git_filter_list *filters, git_buf *src)
{
int error;
if ((error = git_buf_sanitize(src)) < 0)
return error;
return git_filter_list_apply_to_buffer(tgt, filters, src->ptr, src->size);
}
#endif
|
0 |
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2
|
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2/src/diff_stats.c
|
/*
* Copyright (C) the libgit2 contributors. All rights reserved.
*
* This file is part of libgit2, distributed under the GNU GPL v2 with
* a Linking Exception. For full terms see the included COPYING file.
*/
#include "common.h"
#include "vector.h"
#include "diff.h"
#include "patch_generate.h"
#define DIFF_RENAME_FILE_SEPARATOR " => "
#define STATS_FULL_MIN_SCALE 7
typedef struct {
size_t insertions;
size_t deletions;
} diff_file_stats;
struct git_diff_stats {
git_diff *diff;
diff_file_stats *filestats;
size_t files_changed;
size_t insertions;
size_t deletions;
size_t renames;
size_t max_name;
size_t max_filestat;
int max_digits;
};
static int digits_for_value(size_t val)
{
int count = 1;
size_t placevalue = 10;
while (val >= placevalue) {
++count;
placevalue *= 10;
}
return count;
}
static int diff_file_stats_full_to_buf(
git_buf *out,
const git_diff_delta *delta,
const diff_file_stats *filestat,
const git_diff_stats *stats,
size_t width)
{
const char *old_path = NULL, *new_path = NULL, *adddel_path = NULL;
size_t padding;
git_object_size_t old_size, new_size;
old_path = delta->old_file.path;
new_path = delta->new_file.path;
old_size = delta->old_file.size;
new_size = delta->new_file.size;
if (old_path && new_path && strcmp(old_path, new_path) != 0) {
size_t common_dirlen;
int error;
padding = stats->max_name - strlen(old_path) - strlen(new_path);
if ((common_dirlen = git_path_common_dirlen(old_path, new_path)) &&
common_dirlen <= INT_MAX) {
error = git_buf_printf(out, " %.*s{%s"DIFF_RENAME_FILE_SEPARATOR"%s}",
(int) common_dirlen, old_path,
old_path + common_dirlen,
new_path + common_dirlen);
} else {
error = git_buf_printf(out, " %s" DIFF_RENAME_FILE_SEPARATOR "%s",
old_path, new_path);
}
if (error < 0)
goto on_error;
} else {
adddel_path = new_path ? new_path : old_path;
if (git_buf_printf(out, " %s", adddel_path) < 0)
goto on_error;
padding = stats->max_name - strlen(adddel_path);
if (stats->renames > 0)
padding += strlen(DIFF_RENAME_FILE_SEPARATOR);
}
if (git_buf_putcn(out, ' ', padding) < 0 ||
git_buf_puts(out, " | ") < 0)
goto on_error;
if (delta->flags & GIT_DIFF_FLAG_BINARY) {
if (git_buf_printf(out,
"Bin %" PRId64 " -> %" PRId64 " bytes", old_size, new_size) < 0)
goto on_error;
}
else {
if (git_buf_printf(out,
"%*" PRIuZ, stats->max_digits,
filestat->insertions + filestat->deletions) < 0)
goto on_error;
if (filestat->insertions || filestat->deletions) {
if (git_buf_putc(out, ' ') < 0)
goto on_error;
if (!width) {
if (git_buf_putcn(out, '+', filestat->insertions) < 0 ||
git_buf_putcn(out, '-', filestat->deletions) < 0)
goto on_error;
} else {
size_t total = filestat->insertions + filestat->deletions;
size_t full = (total * width + stats->max_filestat / 2) /
stats->max_filestat;
size_t plus = full * filestat->insertions / total;
size_t minus = full - plus;
if (git_buf_putcn(out, '+', max(plus, 1)) < 0 ||
git_buf_putcn(out, '-', max(minus, 1)) < 0)
goto on_error;
}
}
}
git_buf_putc(out, '\n');
on_error:
return (git_buf_oom(out) ? -1 : 0);
}
static int diff_file_stats_number_to_buf(
git_buf *out,
const git_diff_delta *delta,
const diff_file_stats *filestats)
{
int error;
const char *path = delta->new_file.path;
if (delta->flags & GIT_DIFF_FLAG_BINARY)
error = git_buf_printf(out, "%-8c" "%-8c" "%s\n", '-', '-', path);
else
error = git_buf_printf(out, "%-8" PRIuZ "%-8" PRIuZ "%s\n",
filestats->insertions, filestats->deletions, path);
return error;
}
static int diff_file_stats_summary_to_buf(
git_buf *out,
const git_diff_delta *delta)
{
if (delta->old_file.mode != delta->new_file.mode) {
if (delta->old_file.mode == 0) {
git_buf_printf(out, " create mode %06o %s\n",
delta->new_file.mode, delta->new_file.path);
}
else if (delta->new_file.mode == 0) {
git_buf_printf(out, " delete mode %06o %s\n",
delta->old_file.mode, delta->old_file.path);
}
else {
git_buf_printf(out, " mode change %06o => %06o %s\n",
delta->old_file.mode, delta->new_file.mode, delta->new_file.path);
}
}
return 0;
}
int git_diff_get_stats(
git_diff_stats **out,
git_diff *diff)
{
size_t i, deltas;
size_t total_insertions = 0, total_deletions = 0;
git_diff_stats *stats = NULL;
int error = 0;
GIT_ASSERT_ARG(out);
GIT_ASSERT_ARG(diff);
stats = git__calloc(1, sizeof(git_diff_stats));
GIT_ERROR_CHECK_ALLOC(stats);
deltas = git_diff_num_deltas(diff);
stats->filestats = git__calloc(deltas, sizeof(diff_file_stats));
if (!stats->filestats) {
git__free(stats);
return -1;
}
stats->diff = diff;
GIT_REFCOUNT_INC(diff);
for (i = 0; i < deltas && !error; ++i) {
git_patch *patch = NULL;
size_t add = 0, remove = 0, namelen;
const git_diff_delta *delta;
if ((error = git_patch_from_diff(&patch, diff, i)) < 0)
break;
/* keep a count of renames because it will affect formatting */
delta = patch->delta;
/* TODO ugh */
namelen = strlen(delta->new_file.path);
if (delta->old_file.path && strcmp(delta->old_file.path, delta->new_file.path) != 0) {
namelen += strlen(delta->old_file.path);
stats->renames++;
}
/* and, of course, count the line stats */
error = git_patch_line_stats(NULL, &add, &remove, patch);
git_patch_free(patch);
stats->filestats[i].insertions = add;
stats->filestats[i].deletions = remove;
total_insertions += add;
total_deletions += remove;
if (stats->max_name < namelen)
stats->max_name = namelen;
if (stats->max_filestat < add + remove)
stats->max_filestat = add + remove;
}
stats->files_changed = deltas;
stats->insertions = total_insertions;
stats->deletions = total_deletions;
stats->max_digits = digits_for_value(stats->max_filestat + 1);
if (error < 0) {
git_diff_stats_free(stats);
stats = NULL;
}
*out = stats;
return error;
}
size_t git_diff_stats_files_changed(
const git_diff_stats *stats)
{
GIT_ASSERT_ARG(stats);
return stats->files_changed;
}
size_t git_diff_stats_insertions(
const git_diff_stats *stats)
{
GIT_ASSERT_ARG(stats);
return stats->insertions;
}
size_t git_diff_stats_deletions(
const git_diff_stats *stats)
{
GIT_ASSERT_ARG(stats);
return stats->deletions;
}
int git_diff_stats_to_buf(
git_buf *out,
const git_diff_stats *stats,
git_diff_stats_format_t format,
size_t width)
{
int error = 0;
size_t i;
const git_diff_delta *delta;
GIT_ASSERT_ARG(out);
GIT_ASSERT_ARG(stats);
if (format & GIT_DIFF_STATS_NUMBER) {
for (i = 0; i < stats->files_changed; ++i) {
if ((delta = git_diff_get_delta(stats->diff, i)) == NULL)
continue;
error = diff_file_stats_number_to_buf(
out, delta, &stats->filestats[i]);
if (error < 0)
return error;
}
}
if (format & GIT_DIFF_STATS_FULL) {
if (width > 0) {
if (width > stats->max_name + stats->max_digits + 5)
width -= (stats->max_name + stats->max_digits + 5);
if (width < STATS_FULL_MIN_SCALE)
width = STATS_FULL_MIN_SCALE;
}
if (width > stats->max_filestat)
width = 0;
for (i = 0; i < stats->files_changed; ++i) {
if ((delta = git_diff_get_delta(stats->diff, i)) == NULL)
continue;
error = diff_file_stats_full_to_buf(
out, delta, &stats->filestats[i], stats, width);
if (error < 0)
return error;
}
}
if (format & GIT_DIFF_STATS_FULL || format & GIT_DIFF_STATS_SHORT) {
git_buf_printf(
out, " %" PRIuZ " file%s changed",
stats->files_changed, stats->files_changed != 1 ? "s" : "");
if (stats->insertions || stats->deletions == 0)
git_buf_printf(
out, ", %" PRIuZ " insertion%s(+)",
stats->insertions, stats->insertions != 1 ? "s" : "");
if (stats->deletions || stats->insertions == 0)
git_buf_printf(
out, ", %" PRIuZ " deletion%s(-)",
stats->deletions, stats->deletions != 1 ? "s" : "");
git_buf_putc(out, '\n');
if (git_buf_oom(out))
return -1;
}
if (format & GIT_DIFF_STATS_INCLUDE_SUMMARY) {
for (i = 0; i < stats->files_changed; ++i) {
if ((delta = git_diff_get_delta(stats->diff, i)) == NULL)
continue;
error = diff_file_stats_summary_to_buf(out, delta);
if (error < 0)
return error;
}
}
return error;
}
void git_diff_stats_free(git_diff_stats *stats)
{
if (stats == NULL)
return;
git_diff_free(stats->diff); /* bumped refcount in constructor */
git__free(stats->filestats);
git__free(stats);
}
|
0 |
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2
|
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2/src/oid.h
|
/*
* Copyright (C) the libgit2 contributors. All rights reserved.
*
* This file is part of libgit2, distributed under the GNU GPL v2 with
* a Linking Exception. For full terms see the included COPYING file.
*/
#ifndef INCLUDE_oid_h__
#define INCLUDE_oid_h__
#include "common.h"
#include "git2/oid.h"
/**
* Format a git_oid into a newly allocated c-string.
*
* The c-string is owned by the caller and needs to be manually freed.
*
* @param id the oid structure to format
* @return the c-string; NULL if memory is exhausted. Caller must
* deallocate the string with git__free().
*/
char *git_oid_allocfmt(const git_oid *id);
GIT_INLINE(int) git_oid__hashcmp(const unsigned char *sha1, const unsigned char *sha2)
{
return memcmp(sha1, sha2, GIT_OID_RAWSZ);
}
/*
* Compare two oid structures.
*
* @param a first oid structure.
* @param b second oid structure.
* @return <0, 0, >0 if a < b, a == b, a > b.
*/
GIT_INLINE(int) git_oid__cmp(const git_oid *a, const git_oid *b)
{
return git_oid__hashcmp(a->id, b->id);
}
GIT_INLINE(void) git_oid__cpy_prefix(
git_oid *out, const git_oid *id, size_t len)
{
memcpy(&out->id, id->id, (len + 1) / 2);
if (len & 1)
out->id[len / 2] &= 0xF0;
}
#endif
|
0 |
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2
|
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2/src/notes.h
|
/*
* Copyright (C) the libgit2 contributors. All rights reserved.
*
* This file is part of libgit2, distributed under the GNU GPL v2 with
* a Linking Exception. For full terms see the included COPYING file.
*/
#ifndef INCLUDE_note_h__
#define INCLUDE_note_h__
#include "common.h"
#include "git2/oid.h"
#include "git2/types.h"
#define GIT_NOTES_DEFAULT_REF "refs/notes/commits"
#define GIT_NOTES_DEFAULT_MSG_ADD \
"Notes added by 'git_note_create' from libgit2"
#define GIT_NOTES_DEFAULT_MSG_RM \
"Notes removed by 'git_note_remove' from libgit2"
struct git_note {
git_oid id;
git_signature *author;
git_signature *committer;
char *message;
};
#endif
|
0 |
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2
|
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2/src/oid.c
|
/*
* Copyright (C) the libgit2 contributors. All rights reserved.
*
* This file is part of libgit2, distributed under the GNU GPL v2 with
* a Linking Exception. For full terms see the included COPYING file.
*/
#include "oid.h"
#include "git2/oid.h"
#include "repository.h"
#include "threadstate.h"
#include <string.h>
#include <limits.h>
static char to_hex[] = "0123456789abcdef";
static int oid_error_invalid(const char *msg)
{
git_error_set(GIT_ERROR_INVALID, "unable to parse OID - %s", msg);
return -1;
}
int git_oid_fromstrn(git_oid *out, const char *str, size_t length)
{
size_t p;
int v;
GIT_ASSERT_ARG(out);
GIT_ASSERT_ARG(str);
if (!length)
return oid_error_invalid("too short");
if (length > GIT_OID_HEXSZ)
return oid_error_invalid("too long");
memset(out->id, 0, GIT_OID_RAWSZ);
for (p = 0; p < length; p++) {
v = git__fromhex(str[p]);
if (v < 0)
return oid_error_invalid("contains invalid characters");
out->id[p / 2] |= (unsigned char)(v << (p % 2 ? 0 : 4));
}
return 0;
}
int git_oid_fromstrp(git_oid *out, const char *str)
{
return git_oid_fromstrn(out, str, strlen(str));
}
int git_oid_fromstr(git_oid *out, const char *str)
{
return git_oid_fromstrn(out, str, GIT_OID_HEXSZ);
}
GIT_INLINE(char) *fmt_one(char *str, unsigned int val)
{
*str++ = to_hex[val >> 4];
*str++ = to_hex[val & 0xf];
return str;
}
int git_oid_nfmt(char *str, size_t n, const git_oid *oid)
{
size_t i, max_i;
if (!oid) {
memset(str, 0, n);
return 0;
}
if (n > GIT_OID_HEXSZ) {
memset(&str[GIT_OID_HEXSZ], 0, n - GIT_OID_HEXSZ);
n = GIT_OID_HEXSZ;
}
max_i = n / 2;
for (i = 0; i < max_i; i++)
str = fmt_one(str, oid->id[i]);
if (n & 1)
*str++ = to_hex[oid->id[i] >> 4];
return 0;
}
int git_oid_fmt(char *str, const git_oid *oid)
{
return git_oid_nfmt(str, GIT_OID_HEXSZ, oid);
}
int git_oid_pathfmt(char *str, const git_oid *oid)
{
size_t i;
str = fmt_one(str, oid->id[0]);
*str++ = '/';
for (i = 1; i < sizeof(oid->id); i++)
str = fmt_one(str, oid->id[i]);
return 0;
}
char *git_oid_tostr_s(const git_oid *oid)
{
char *str = GIT_THREADSTATE->oid_fmt;
git_oid_nfmt(str, GIT_OID_HEXSZ + 1, oid);
return str;
}
char *git_oid_allocfmt(const git_oid *oid)
{
char *str = git__malloc(GIT_OID_HEXSZ + 1);
if (!str)
return NULL;
git_oid_nfmt(str, GIT_OID_HEXSZ + 1, oid);
return str;
}
char *git_oid_tostr(char *out, size_t n, const git_oid *oid)
{
if (!out || n == 0)
return "";
if (n > GIT_OID_HEXSZ + 1)
n = GIT_OID_HEXSZ + 1;
git_oid_nfmt(out, n - 1, oid); /* allow room for terminating NUL */
out[n - 1] = '\0';
return out;
}
int git_oid__parse(
git_oid *oid, const char **buffer_out,
const char *buffer_end, const char *header)
{
const size_t sha_len = GIT_OID_HEXSZ;
const size_t header_len = strlen(header);
const char *buffer = *buffer_out;
if (buffer + (header_len + sha_len + 1) > buffer_end)
return -1;
if (memcmp(buffer, header, header_len) != 0)
return -1;
if (buffer[header_len + sha_len] != '\n')
return -1;
if (git_oid_fromstr(oid, buffer + header_len) < 0)
return -1;
*buffer_out = buffer + (header_len + sha_len + 1);
return 0;
}
void git_oid__writebuf(git_buf *buf, const char *header, const git_oid *oid)
{
char hex_oid[GIT_OID_HEXSZ];
git_oid_fmt(hex_oid, oid);
git_buf_puts(buf, header);
git_buf_put(buf, hex_oid, GIT_OID_HEXSZ);
git_buf_putc(buf, '\n');
}
int git_oid_fromraw(git_oid *out, const unsigned char *raw)
{
memcpy(out->id, raw, sizeof(out->id));
return 0;
}
int git_oid_cpy(git_oid *out, const git_oid *src)
{
memcpy(out->id, src->id, sizeof(out->id));
return 0;
}
int git_oid_cmp(const git_oid *a, const git_oid *b)
{
return git_oid__cmp(a, b);
}
int git_oid_equal(const git_oid *a, const git_oid *b)
{
return (git_oid__cmp(a, b) == 0);
}
int git_oid_ncmp(const git_oid *oid_a, const git_oid *oid_b, size_t len)
{
const unsigned char *a = oid_a->id;
const unsigned char *b = oid_b->id;
if (len > GIT_OID_HEXSZ)
len = GIT_OID_HEXSZ;
while (len > 1) {
if (*a != *b)
return 1;
a++;
b++;
len -= 2;
};
if (len)
if ((*a ^ *b) & 0xf0)
return 1;
return 0;
}
int git_oid_strcmp(const git_oid *oid_a, const char *str)
{
const unsigned char *a;
unsigned char strval;
int hexval;
for (a = oid_a->id; *str && (a - oid_a->id) < GIT_OID_RAWSZ; ++a) {
if ((hexval = git__fromhex(*str++)) < 0)
return -1;
strval = (unsigned char)(hexval << 4);
if (*str) {
if ((hexval = git__fromhex(*str++)) < 0)
return -1;
strval |= hexval;
}
if (*a != strval)
return (*a - strval);
}
return 0;
}
int git_oid_streq(const git_oid *oid_a, const char *str)
{
return git_oid_strcmp(oid_a, str) == 0 ? 0 : -1;
}
int git_oid_is_zero(const git_oid *oid_a)
{
const unsigned char *a = oid_a->id;
unsigned int i;
for (i = 0; i < GIT_OID_RAWSZ; ++i, ++a)
if (*a != 0)
return 0;
return 1;
}
#ifndef GIT_DEPRECATE_HARD
int git_oid_iszero(const git_oid *oid_a)
{
return git_oid_is_zero(oid_a);
}
#endif
typedef short node_index;
typedef union {
const char *tail;
node_index children[16];
} trie_node;
struct git_oid_shorten {
trie_node *nodes;
size_t node_count, size;
int min_length, full;
};
static int resize_trie(git_oid_shorten *self, size_t new_size)
{
self->nodes = git__reallocarray(self->nodes, new_size, sizeof(trie_node));
GIT_ERROR_CHECK_ALLOC(self->nodes);
if (new_size > self->size) {
memset(&self->nodes[self->size], 0x0, (new_size - self->size) * sizeof(trie_node));
}
self->size = new_size;
return 0;
}
static trie_node *push_leaf(git_oid_shorten *os, node_index idx, int push_at, const char *oid)
{
trie_node *node, *leaf;
node_index idx_leaf;
if (os->node_count >= os->size) {
if (resize_trie(os, os->size * 2) < 0)
return NULL;
}
idx_leaf = (node_index)os->node_count++;
if (os->node_count == SHRT_MAX) {
os->full = 1;
return NULL;
}
node = &os->nodes[idx];
node->children[push_at] = -idx_leaf;
leaf = &os->nodes[idx_leaf];
leaf->tail = oid;
return node;
}
git_oid_shorten *git_oid_shorten_new(size_t min_length)
{
git_oid_shorten *os;
GIT_ASSERT_ARG_WITH_RETVAL((size_t)((int)min_length) == min_length, NULL);
os = git__calloc(1, sizeof(git_oid_shorten));
if (os == NULL)
return NULL;
if (resize_trie(os, 16) < 0) {
git__free(os);
return NULL;
}
os->node_count = 1;
os->min_length = (int)min_length;
return os;
}
void git_oid_shorten_free(git_oid_shorten *os)
{
if (os == NULL)
return;
git__free(os->nodes);
git__free(os);
}
/*
* What wizardry is this?
*
* This is just a memory-optimized trie: basically a very fancy
* 16-ary tree, which is used to store the prefixes of the OID
* strings.
*
* Read more: http://en.wikipedia.org/wiki/Trie
*
* Magic that happens in this method:
*
* - Each node in the trie is an union, so it can work both as
* a normal node, or as a leaf.
*
* - Each normal node points to 16 children (one for each possible
* character in the oid). This is *not* stored in an array of
* pointers, because in a 64-bit arch this would be sucking
* 16*sizeof(void*) = 128 bytes of memory per node, which is
* insane. What we do is store Node Indexes, and use these indexes
* to look up each node in the om->index array. These indexes are
* signed shorts, so this limits the amount of unique OIDs that
* fit in the structure to about 20000 (assuming a more or less uniform
* distribution).
*
* - All the nodes in om->index array are stored contiguously in
* memory, and each of them is 32 bytes, so we fit 2x nodes per
* cache line. Convenient for speed.
*
* - To differentiate the leafs from the normal nodes, we store all
* the indexes towards a leaf as a negative index (indexes to normal
* nodes are positives). When we find that one of the children for
* a node has a negative value, that means it's going to be a leaf.
* This reduces the amount of indexes we have by two, but also reduces
* the size of each node by 1-4 bytes (the amount we would need to
* add a `is_leaf` field): this is good because it allows the nodes
* to fit cleanly in cache lines.
*
* - Once we reach an empty children, instead of continuing to insert
* new nodes for each remaining character of the OID, we store a pointer
* to the tail in the leaf; if the leaf is reached again, we turn it
* into a normal node and use the tail to create a new leaf.
*
* This is a pretty good balance between performance and memory usage.
*/
int git_oid_shorten_add(git_oid_shorten *os, const char *text_oid)
{
int i;
bool is_leaf;
node_index idx;
if (os->full) {
git_error_set(GIT_ERROR_INVALID, "unable to shorten OID - OID set full");
return -1;
}
if (text_oid == NULL)
return os->min_length;
idx = 0;
is_leaf = false;
for (i = 0; i < GIT_OID_HEXSZ; ++i) {
int c = git__fromhex(text_oid[i]);
trie_node *node;
if (c == -1) {
git_error_set(GIT_ERROR_INVALID, "unable to shorten OID - invalid hex value");
return -1;
}
node = &os->nodes[idx];
if (is_leaf) {
const char *tail;
tail = node->tail;
node->tail = NULL;
node = push_leaf(os, idx, git__fromhex(tail[0]), &tail[1]);
if (node == NULL) {
if (os->full)
git_error_set(GIT_ERROR_INVALID, "unable to shorten OID - OID set full");
return -1;
}
}
if (node->children[c] == 0) {
if (push_leaf(os, idx, c, &text_oid[i + 1]) == NULL) {
if (os->full)
git_error_set(GIT_ERROR_INVALID, "unable to shorten OID - OID set full");
return -1;
}
break;
}
idx = node->children[c];
is_leaf = false;
if (idx < 0) {
node->children[c] = idx = -idx;
is_leaf = true;
}
}
if (++i > os->min_length)
os->min_length = i;
return os->min_length;
}
|
0 |
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2
|
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2/src/pack.h
|
/*
* Copyright (C) the libgit2 contributors. All rights reserved.
*
* This file is part of libgit2, distributed under the GNU GPL v2 with
* a Linking Exception. For full terms see the included COPYING file.
*/
#ifndef INCLUDE_pack_h__
#define INCLUDE_pack_h__
#include "common.h"
#include "git2/oid.h"
#include "array.h"
#include "map.h"
#include "mwindow.h"
#include "odb.h"
#include "offmap.h"
#include "oidmap.h"
#include "zstream.h"
/**
* Function type for callbacks from git_pack_foreach_entry_offset.
*/
typedef int git_pack_foreach_entry_offset_cb(
const git_oid *id,
off64_t offset,
void *payload);
#define GIT_PACK_FILE_MODE 0444
#define PACK_SIGNATURE 0x5041434b /* "PACK" */
#define PACK_VERSION 2
#define pack_version_ok(v) ((v) == htonl(2) || (v) == htonl(3))
struct git_pack_header {
uint32_t hdr_signature;
uint32_t hdr_version;
uint32_t hdr_entries;
};
/*
* The first four bytes of index formats later than version 1 should
* start with this signature, as all older git binaries would find this
* value illegal and abort reading the file.
*
* This is the case because the number of objects in a packfile
* cannot exceed 1,431,660,000 as every object would need at least
* 3 bytes of data and the overall packfile cannot exceed 4 GiB with
* version 1 of the index file due to the offsets limited to 32 bits.
* Clearly the signature exceeds this maximum.
*
* Very old git binaries will also compare the first 4 bytes to the
* next 4 bytes in the index and abort with a "non-monotonic index"
* error if the second 4 byte word is smaller than the first 4
* byte word. This would be true in the proposed future index
* format as idx_signature would be greater than idx_version.
*/
#define PACK_IDX_SIGNATURE 0xff744f63 /* "\377tOc" */
struct git_pack_idx_header {
uint32_t idx_signature;
uint32_t idx_version;
};
typedef struct git_pack_cache_entry {
size_t last_usage; /* enough? */
git_atomic32 refcount;
git_rawobj raw;
} git_pack_cache_entry;
struct pack_chain_elem {
off64_t base_key;
off64_t offset;
size_t size;
git_object_t type;
};
typedef git_array_t(struct pack_chain_elem) git_dependency_chain;
#define GIT_PACK_CACHE_MEMORY_LIMIT 16 * 1024 * 1024
#define GIT_PACK_CACHE_SIZE_LIMIT 1024 * 1024 /* don't bother caching anything over 1MB */
typedef struct {
size_t memory_used;
size_t memory_limit;
size_t use_ctr;
git_mutex lock;
git_offmap *entries;
} git_pack_cache;
struct git_pack_file {
git_mwindow_file mwf;
git_map index_map;
git_mutex lock; /* protect updates to index_map */
git_atomic32 refcount;
uint32_t num_objects;
uint32_t num_bad_objects;
git_oid *bad_object_sha1; /* array of git_oid */
int index_version;
git_time_t mtime;
unsigned pack_local:1, pack_keep:1, has_cache:1;
git_oidmap *idx_cache;
git_oid **oids;
git_pack_cache bases; /* delta base cache */
time_t last_freshen; /* last time the packfile was freshened */
/* something like ".git/objects/pack/xxxxx.pack" */
char pack_name[GIT_FLEX_ARRAY]; /* more */
};
/**
* Return the position where an OID (or a prefix) would be inserted within the
* OID Lookup Table of an .idx file. This performs binary search between the lo
* and hi indices.
*
* The stride parameter is provided because .idx files version 1 store the OIDs
* interleaved with the 4-byte file offsets of the objects within the .pack
* file (stride = 24), whereas files with version 2 store them in a contiguous
* flat array (stride = 20).
*/
int git_pack__lookup_sha1(const void *oid_lookup_table, size_t stride, unsigned lo,
unsigned hi, const unsigned char *oid_prefix);
struct git_pack_entry {
off64_t offset;
git_oid sha1;
struct git_pack_file *p;
};
typedef struct git_packfile_stream {
off64_t curpos;
int done;
git_zstream zstream;
struct git_pack_file *p;
git_mwindow *mw;
} git_packfile_stream;
int git_packfile__object_header(size_t *out, unsigned char *hdr, size_t size, git_object_t type);
int git_packfile__name(char **out, const char *path);
int git_packfile_unpack_header(
size_t *size_p,
git_object_t *type_p,
struct git_pack_file *p,
git_mwindow **w_curs,
off64_t *curpos);
int git_packfile_resolve_header(
size_t *size_p,
git_object_t *type_p,
struct git_pack_file *p,
off64_t offset);
int git_packfile_unpack(git_rawobj *obj, struct git_pack_file *p, off64_t *obj_offset);
int git_packfile_stream_open(git_packfile_stream *obj, struct git_pack_file *p, off64_t curpos);
ssize_t git_packfile_stream_read(git_packfile_stream *obj, void *buffer, size_t len);
void git_packfile_stream_dispose(git_packfile_stream *obj);
int get_delta_base(
off64_t *delta_base_out,
struct git_pack_file *p,
git_mwindow **w_curs,
off64_t *curpos,
git_object_t type,
off64_t delta_obj_offset);
void git_packfile_free(struct git_pack_file *p, bool unlink_packfile);
int git_packfile_alloc(struct git_pack_file **pack_out, const char *path);
int git_pack_entry_find(
struct git_pack_entry *e,
struct git_pack_file *p,
const git_oid *short_oid,
size_t len);
int git_pack_foreach_entry(
struct git_pack_file *p,
git_odb_foreach_cb cb,
void *data);
/**
* Similar to git_pack_foreach_entry, but:
* - It also provides the offset of the object within the
* packfile.
* - It does not sort the objects in any order.
* - It retains the lock while invoking the callback.
*/
int git_pack_foreach_entry_offset(
struct git_pack_file *p,
git_pack_foreach_entry_offset_cb cb,
void *data);
#endif
|
0 |
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2
|
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2/src/signature.h
|
/*
* Copyright (C) the libgit2 contributors. All rights reserved.
*
* This file is part of libgit2, distributed under the GNU GPL v2 with
* a Linking Exception. For full terms see the included COPYING file.
*/
#ifndef INCLUDE_signature_h__
#define INCLUDE_signature_h__
#include "common.h"
#include "git2/common.h"
#include "git2/signature.h"
#include "repository.h"
#include <time.h>
int git_signature__parse(git_signature *sig, const char **buffer_out, const char *buffer_end, const char *header, char ender);
void git_signature__writebuf(git_buf *buf, const char *header, const git_signature *sig);
bool git_signature__equal(const git_signature *one, const git_signature *two);
int git_signature__pdup(git_signature **dest, const git_signature *source, git_pool *pool);
#endif
|
0 |
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2
|
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2/src/sysdir.h
|
/*
* Copyright (C) the libgit2 contributors. All rights reserved.
*
* This file is part of libgit2, distributed under the GNU GPL v2 with
* a Linking Exception. For full terms see the included COPYING file.
*/
#ifndef INCLUDE_sysdir_h__
#define INCLUDE_sysdir_h__
#include "common.h"
#include "posix.h"
#include "buffer.h"
/**
* Find a "global" file (i.e. one in a user's home directory).
*
* @param path buffer to write the full path into
* @param filename name of file to find in the home directory
* @return 0 if found, GIT_ENOTFOUND if not found, or -1 on other OS error
*/
extern int git_sysdir_find_global_file(git_buf *path, const char *filename);
/**
* Find an "XDG" file (i.e. one in user's XDG config path).
*
* @param path buffer to write the full path into
* @param filename name of file to find in the home directory
* @return 0 if found, GIT_ENOTFOUND if not found, or -1 on other OS error
*/
extern int git_sysdir_find_xdg_file(git_buf *path, const char *filename);
/**
* Find a "system" file (i.e. one shared for all users of the system).
*
* @param path buffer to write the full path into
* @param filename name of file to find in the home directory
* @return 0 if found, GIT_ENOTFOUND if not found, or -1 on other OS error
*/
extern int git_sysdir_find_system_file(git_buf *path, const char *filename);
/**
* Find a "ProgramData" file (i.e. one in %PROGRAMDATA%)
*
* @param path buffer to write the full path into
* @param filename name of file to find in the ProgramData directory
* @return 0 if found, GIT_ENOTFOUND if not found, or -1 on other OS error
*/
extern int git_sysdir_find_programdata_file(git_buf *path, const char *filename);
/**
* Find template directory.
*
* @param path buffer to write the full path into
* @return 0 if found, GIT_ENOTFOUND if not found, or -1 on other OS error
*/
extern int git_sysdir_find_template_dir(git_buf *path);
/**
* Expand the name of a "global" file (i.e. one in a user's home
* directory). Unlike `find_global_file` (above), this makes no
* attempt to check for the existence of the file, and is useful if
* you want the full path regardless of existence.
*
* @param path buffer to write the full path into
* @param filename name of file in the home directory
* @return 0 on success or -1 on error
*/
extern int git_sysdir_expand_global_file(git_buf *path, const char *filename);
typedef enum {
GIT_SYSDIR_SYSTEM = 0,
GIT_SYSDIR_GLOBAL = 1,
GIT_SYSDIR_XDG = 2,
GIT_SYSDIR_PROGRAMDATA = 3,
GIT_SYSDIR_TEMPLATE = 4,
GIT_SYSDIR__MAX = 5,
} git_sysdir_t;
/**
* Configures global data for configuration file search paths.
*
* @return 0 on success, <0 on failure
*/
extern int git_sysdir_global_init(void);
/**
* Get the search path for global/system/xdg files
*
* @param out pointer to git_buf containing search path
* @param which which list of paths to return
* @return 0 on success, <0 on failure
*/
extern int git_sysdir_get(const git_buf **out, git_sysdir_t which);
/**
* Set search paths for global/system/xdg files
*
* The first occurrence of the magic string "$PATH" in the new value will
* be replaced with the old value of the search path.
*
* @param which Which search path to modify
* @param paths New search path (separated by GIT_PATH_LIST_SEPARATOR)
* @return 0 on success, <0 on failure (allocation error)
*/
extern int git_sysdir_set(git_sysdir_t which, const char *paths);
#endif
|
0 |
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2
|
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2/src/email.h
|
/*
* Copyright (C) the libgit2 contributors. All rights reserved.
*
* This file is part of libgit2, distributed under the GNU GPL v2 with
* a Linking Exception. For full terms see the included COPYING file.
*/
#ifndef INCLUDE_email_h__
#define INCLUDE_email_h__
#include "common.h"
#include "git2/email.h"
extern int git_email__append_from_diff(
git_buf *out,
git_diff *diff,
size_t patch_idx,
size_t patch_count,
const git_oid *commit_id,
const char *summary,
const char *body,
const git_signature *author,
const git_email_create_options *given_opts);
#endif
|
0 |
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2
|
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2/src/merge.c
|
/*
* Copyright (C) the libgit2 contributors. All rights reserved.
*
* This file is part of libgit2, distributed under the GNU GPL v2 with
* a Linking Exception. For full terms see the included COPYING file.
*/
#include "merge.h"
#include "posix.h"
#include "buffer.h"
#include "repository.h"
#include "revwalk.h"
#include "commit_list.h"
#include "path.h"
#include "refs.h"
#include "object.h"
#include "iterator.h"
#include "refs.h"
#include "diff.h"
#include "diff_generate.h"
#include "diff_tform.h"
#include "checkout.h"
#include "tree.h"
#include "blob.h"
#include "oid.h"
#include "index.h"
#include "filebuf.h"
#include "config.h"
#include "oidarray.h"
#include "annotated_commit.h"
#include "commit.h"
#include "oidarray.h"
#include "merge_driver.h"
#include "oidmap.h"
#include "array.h"
#include "git2/types.h"
#include "git2/repository.h"
#include "git2/object.h"
#include "git2/commit.h"
#include "git2/merge.h"
#include "git2/refs.h"
#include "git2/reset.h"
#include "git2/checkout.h"
#include "git2/signature.h"
#include "git2/config.h"
#include "git2/tree.h"
#include "git2/oidarray.h"
#include "git2/annotated_commit.h"
#include "git2/sys/index.h"
#include "git2/sys/hashsig.h"
#define GIT_MERGE_INDEX_ENTRY_EXISTS(X) ((X).mode != 0)
#define GIT_MERGE_INDEX_ENTRY_ISFILE(X) S_ISREG((X).mode)
typedef enum {
TREE_IDX_ANCESTOR = 0,
TREE_IDX_OURS = 1,
TREE_IDX_THEIRS = 2
} merge_tree_index_t;
/* Tracks D/F conflicts */
struct merge_diff_df_data {
const char *df_path;
const char *prev_path;
git_merge_diff *prev_conflict;
};
/*
* This acts as a negative cache entry marker. In case we've tried to calculate
* similarity metrics for a given blob already but `git_hashsig` determined
* that it's too small in order to have a meaningful hash signature, we will
* insert the address of this marker instead of `NULL`. Like this, we can
* easily check whether we have checked a gien entry already and skip doing the
* calculation again and again.
*/
static int cache_invalid_marker;
/* Merge base computation */
static int merge_bases_many(git_commit_list **out, git_revwalk **walk_out, git_repository *repo, size_t length, const git_oid input_array[])
{
git_revwalk *walk = NULL;
git_vector list;
git_commit_list *result = NULL;
git_commit_list_node *commit;
int error = -1;
unsigned int i;
if (length < 2) {
git_error_set(GIT_ERROR_INVALID, "at least two commits are required to find an ancestor");
return -1;
}
if (git_vector_init(&list, length - 1, NULL) < 0)
return -1;
if (git_revwalk_new(&walk, repo) < 0)
goto on_error;
for (i = 1; i < length; i++) {
commit = git_revwalk__commit_lookup(walk, &input_array[i]);
if (commit == NULL)
goto on_error;
git_vector_insert(&list, commit);
}
commit = git_revwalk__commit_lookup(walk, &input_array[0]);
if (commit == NULL)
goto on_error;
if (git_merge__bases_many(&result, walk, commit, &list, 0) < 0)
goto on_error;
if (!result) {
git_error_set(GIT_ERROR_MERGE, "no merge base found");
error = GIT_ENOTFOUND;
goto on_error;
}
*out = result;
*walk_out = walk;
git_vector_free(&list);
return 0;
on_error:
git_vector_free(&list);
git_revwalk_free(walk);
return error;
}
int git_merge_base_many(git_oid *out, git_repository *repo, size_t length, const git_oid input_array[])
{
git_revwalk *walk;
git_commit_list *result = NULL;
int error = 0;
GIT_ASSERT_ARG(out);
GIT_ASSERT_ARG(repo);
GIT_ASSERT_ARG(input_array);
if ((error = merge_bases_many(&result, &walk, repo, length, input_array)) < 0)
return error;
git_oid_cpy(out, &result->item->oid);
git_commit_list_free(&result);
git_revwalk_free(walk);
return 0;
}
int git_merge_bases_many(git_oidarray *out, git_repository *repo, size_t length, const git_oid input_array[])
{
git_revwalk *walk;
git_commit_list *list, *result = NULL;
int error = 0;
git_array_oid_t array;
GIT_ASSERT_ARG(out);
GIT_ASSERT_ARG(repo);
GIT_ASSERT_ARG(input_array);
if ((error = merge_bases_many(&result, &walk, repo, length, input_array)) < 0)
return error;
git_array_init(array);
list = result;
while (list) {
git_oid *id = git_array_alloc(array);
if (id == NULL) {
error = -1;
goto cleanup;
}
git_oid_cpy(id, &list->item->oid);
list = list->next;
}
git_oidarray__from_array(out, &array);
cleanup:
git_commit_list_free(&result);
git_revwalk_free(walk);
return error;
}
int git_merge_base_octopus(git_oid *out, git_repository *repo, size_t length, const git_oid input_array[])
{
git_oid result;
unsigned int i;
int error = -1;
GIT_ASSERT_ARG(out);
GIT_ASSERT_ARG(repo);
GIT_ASSERT_ARG(input_array);
if (length < 2) {
git_error_set(GIT_ERROR_INVALID, "at least two commits are required to find an ancestor");
return -1;
}
result = input_array[0];
for (i = 1; i < length; i++) {
error = git_merge_base(&result, repo, &result, &input_array[i]);
if (error < 0)
return error;
}
*out = result;
return 0;
}
static int merge_bases(git_commit_list **out, git_revwalk **walk_out, git_repository *repo, const git_oid *one, const git_oid *two)
{
git_revwalk *walk;
git_vector list;
git_commit_list *result = NULL;
git_commit_list_node *commit;
void *contents[1];
if (git_revwalk_new(&walk, repo) < 0)
return -1;
commit = git_revwalk__commit_lookup(walk, two);
if (commit == NULL)
goto on_error;
/* This is just one value, so we can do it on the stack */
memset(&list, 0x0, sizeof(git_vector));
contents[0] = commit;
list.length = 1;
list.contents = contents;
commit = git_revwalk__commit_lookup(walk, one);
if (commit == NULL)
goto on_error;
if (git_merge__bases_many(&result, walk, commit, &list, 0) < 0)
goto on_error;
if (!result) {
git_revwalk_free(walk);
git_error_set(GIT_ERROR_MERGE, "no merge base found");
return GIT_ENOTFOUND;
}
*out = result;
*walk_out = walk;
return 0;
on_error:
git_revwalk_free(walk);
return -1;
}
int git_merge_base(git_oid *out, git_repository *repo, const git_oid *one, const git_oid *two)
{
int error;
git_revwalk *walk;
git_commit_list *result;
if ((error = merge_bases(&result, &walk, repo, one, two)) < 0)
return error;
git_oid_cpy(out, &result->item->oid);
git_commit_list_free(&result);
git_revwalk_free(walk);
return 0;
}
int git_merge_bases(git_oidarray *out, git_repository *repo, const git_oid *one, const git_oid *two)
{
int error;
git_revwalk *walk;
git_commit_list *result, *list;
git_array_oid_t array;
git_array_init(array);
if ((error = merge_bases(&result, &walk, repo, one, two)) < 0)
return error;
list = result;
while (list) {
git_oid *id = git_array_alloc(array);
if (id == NULL)
goto on_error;
git_oid_cpy(id, &list->item->oid);
list = list->next;
}
git_oidarray__from_array(out, &array);
git_commit_list_free(&result);
git_revwalk_free(walk);
return 0;
on_error:
git_commit_list_free(&result);
git_revwalk_free(walk);
return -1;
}
static int interesting(git_pqueue *list)
{
size_t i;
for (i = 0; i < git_pqueue_size(list); i++) {
git_commit_list_node *commit = git_pqueue_get(list, i);
if ((commit->flags & STALE) == 0)
return 1;
}
return 0;
}
static int clear_commit_marks_1(git_commit_list **plist,
git_commit_list_node *commit, unsigned int mark)
{
while (commit) {
unsigned int i;
if (!(mark & commit->flags))
return 0;
commit->flags &= ~mark;
for (i = 1; i < commit->out_degree; i++) {
git_commit_list_node *p = commit->parents[i];
if (git_commit_list_insert(p, plist) == NULL)
return -1;
}
commit = commit->out_degree ? commit->parents[0] : NULL;
}
return 0;
}
static int clear_commit_marks_many(git_vector *commits, unsigned int mark)
{
git_commit_list *list = NULL;
git_commit_list_node *c;
unsigned int i;
git_vector_foreach(commits, i, c) {
if (git_commit_list_insert(c, &list) == NULL)
return -1;
}
while (list)
if (clear_commit_marks_1(&list, git_commit_list_pop(&list), mark) < 0)
return -1;
return 0;
}
static int clear_commit_marks(git_commit_list_node *commit, unsigned int mark)
{
git_commit_list *list = NULL;
if (git_commit_list_insert(commit, &list) == NULL)
return -1;
while (list)
if (clear_commit_marks_1(&list, git_commit_list_pop(&list), mark) < 0)
return -1;
return 0;
}
static int paint_down_to_common(
git_commit_list **out,
git_revwalk *walk,
git_commit_list_node *one,
git_vector *twos,
uint32_t minimum_generation)
{
git_pqueue list;
git_commit_list *result = NULL;
git_commit_list_node *two;
int error;
unsigned int i;
if (git_pqueue_init(&list, 0, twos->length * 2, git_commit_list_generation_cmp) < 0)
return -1;
one->flags |= PARENT1;
if (git_pqueue_insert(&list, one) < 0)
return -1;
git_vector_foreach(twos, i, two) {
if (git_commit_list_parse(walk, two) < 0)
return -1;
two->flags |= PARENT2;
if (git_pqueue_insert(&list, two) < 0)
return -1;
}
/* as long as there are non-STALE commits */
while (interesting(&list)) {
git_commit_list_node *commit = git_pqueue_pop(&list);
int flags;
if (commit == NULL)
break;
flags = commit->flags & (PARENT1 | PARENT2 | STALE);
if (flags == (PARENT1 | PARENT2)) {
if (!(commit->flags & RESULT)) {
commit->flags |= RESULT;
if (git_commit_list_insert(commit, &result) == NULL)
return -1;
}
/* we mark the parents of a merge stale */
flags |= STALE;
}
for (i = 0; i < commit->out_degree; i++) {
git_commit_list_node *p = commit->parents[i];
if ((p->flags & flags) == flags)
continue;
if (p->generation < minimum_generation)
continue;
if ((error = git_commit_list_parse(walk, p)) < 0)
return error;
p->flags |= flags;
if (git_pqueue_insert(&list, p) < 0)
return -1;
}
}
git_pqueue_free(&list);
*out = result;
return 0;
}
static int remove_redundant(git_revwalk *walk, git_vector *commits, uint32_t minimum_generation)
{
git_vector work = GIT_VECTOR_INIT;
unsigned char *redundant;
unsigned int *filled_index;
unsigned int i, j;
int error = 0;
redundant = git__calloc(commits->length, 1);
GIT_ERROR_CHECK_ALLOC(redundant);
filled_index = git__calloc((commits->length - 1), sizeof(unsigned int));
GIT_ERROR_CHECK_ALLOC(filled_index);
for (i = 0; i < commits->length; ++i) {
if ((error = git_commit_list_parse(walk, commits->contents[i])) < 0)
goto done;
}
for (i = 0; i < commits->length; ++i) {
git_commit_list *common = NULL;
git_commit_list_node *commit = commits->contents[i];
if (redundant[i])
continue;
git_vector_clear(&work);
for (j = 0; j < commits->length; j++) {
if (i == j || redundant[j])
continue;
filled_index[work.length] = j;
if ((error = git_vector_insert(&work, commits->contents[j])) < 0)
goto done;
}
error = paint_down_to_common(&common, walk, commit, &work, minimum_generation);
if (error < 0)
goto done;
if (commit->flags & PARENT2)
redundant[i] = 1;
for (j = 0; j < work.length; j++) {
git_commit_list_node *w = work.contents[j];
if (w->flags & PARENT1)
redundant[filled_index[j]] = 1;
}
git_commit_list_free(&common);
if ((error = clear_commit_marks(commit, ALL_FLAGS)) < 0 ||
(error = clear_commit_marks_many(&work, ALL_FLAGS)) < 0)
goto done;
}
for (i = 0; i < commits->length; ++i) {
if (redundant[i])
commits->contents[i] = NULL;
}
done:
git__free(redundant);
git__free(filled_index);
git_vector_free(&work);
return error;
}
int git_merge__bases_many(
git_commit_list **out,
git_revwalk *walk,
git_commit_list_node *one,
git_vector *twos,
uint32_t minimum_generation)
{
int error;
unsigned int i;
git_commit_list_node *two;
git_commit_list *result = NULL, *tmp = NULL;
/* If there's only the one commit, there can be no merge bases */
if (twos->length == 0) {
*out = NULL;
return 0;
}
/* if the commit is repeated, we have a our merge base already */
git_vector_foreach(twos, i, two) {
if (one == two)
return git_commit_list_insert(one, out) ? 0 : -1;
}
if (git_commit_list_parse(walk, one) < 0)
return -1;
error = paint_down_to_common(&result, walk, one, twos, minimum_generation);
if (error < 0)
return error;
/* filter out any stale commits in the results */
tmp = result;
result = NULL;
while (tmp) {
git_commit_list_node *c = git_commit_list_pop(&tmp);
if (!(c->flags & STALE))
if (git_commit_list_insert_by_date(c, &result) == NULL)
return -1;
}
/*
* more than one merge base -- see if there are redundant merge
* bases and remove them
*/
if (result && result->next) {
git_vector redundant = GIT_VECTOR_INIT;
while (result)
git_vector_insert(&redundant, git_commit_list_pop(&result));
if ((error = clear_commit_marks(one, ALL_FLAGS)) < 0 ||
(error = clear_commit_marks_many(twos, ALL_FLAGS)) < 0 ||
(error = remove_redundant(walk, &redundant, minimum_generation)) < 0) {
git_vector_free(&redundant);
return error;
}
git_vector_foreach(&redundant, i, two) {
if (two != NULL)
git_commit_list_insert_by_date(two, &result);
}
git_vector_free(&redundant);
}
*out = result;
return 0;
}
int git_repository_mergehead_foreach(
git_repository *repo,
git_repository_mergehead_foreach_cb cb,
void *payload)
{
git_buf merge_head_path = GIT_BUF_INIT, merge_head_file = GIT_BUF_INIT;
char *buffer, *line;
size_t line_num = 1;
git_oid oid;
int error = 0;
GIT_ASSERT_ARG(repo);
GIT_ASSERT_ARG(cb);
if ((error = git_buf_joinpath(&merge_head_path, repo->gitdir,
GIT_MERGE_HEAD_FILE)) < 0)
return error;
if ((error = git_futils_readbuffer(&merge_head_file,
git_buf_cstr(&merge_head_path))) < 0)
goto cleanup;
buffer = merge_head_file.ptr;
while ((line = git__strsep(&buffer, "\n")) != NULL) {
if (strlen(line) != GIT_OID_HEXSZ) {
git_error_set(GIT_ERROR_INVALID, "unable to parse OID - invalid length");
error = -1;
goto cleanup;
}
if ((error = git_oid_fromstr(&oid, line)) < 0)
goto cleanup;
if ((error = cb(&oid, payload)) != 0) {
git_error_set_after_callback(error);
goto cleanup;
}
++line_num;
}
if (*buffer) {
git_error_set(GIT_ERROR_MERGE, "no EOL at line %"PRIuZ, line_num);
error = -1;
goto cleanup;
}
cleanup:
git_buf_dispose(&merge_head_path);
git_buf_dispose(&merge_head_file);
return error;
}
GIT_INLINE(int) index_entry_cmp(const git_index_entry *a, const git_index_entry *b)
{
int value = 0;
if (a->path == NULL)
return (b->path == NULL) ? 0 : 1;
if ((value = a->mode - b->mode) == 0 &&
(value = git_oid__cmp(&a->id, &b->id)) == 0)
value = strcmp(a->path, b->path);
return value;
}
/* Conflict resolution */
static int merge_conflict_resolve_trivial(
int *resolved,
git_merge_diff_list *diff_list,
const git_merge_diff *conflict)
{
int ours_empty, theirs_empty;
int ours_changed, theirs_changed, ours_theirs_differ;
git_index_entry const *result = NULL;
int error = 0;
GIT_ASSERT_ARG(resolved);
GIT_ASSERT_ARG(diff_list);
GIT_ASSERT_ARG(conflict);
*resolved = 0;
if (conflict->type == GIT_MERGE_DIFF_DIRECTORY_FILE ||
conflict->type == GIT_MERGE_DIFF_RENAMED_ADDED)
return 0;
if (conflict->our_status == GIT_DELTA_RENAMED ||
conflict->their_status == GIT_DELTA_RENAMED)
return 0;
ours_empty = !GIT_MERGE_INDEX_ENTRY_EXISTS(conflict->our_entry);
theirs_empty = !GIT_MERGE_INDEX_ENTRY_EXISTS(conflict->their_entry);
ours_changed = (conflict->our_status != GIT_DELTA_UNMODIFIED);
theirs_changed = (conflict->their_status != GIT_DELTA_UNMODIFIED);
ours_theirs_differ = ours_changed && theirs_changed &&
index_entry_cmp(&conflict->our_entry, &conflict->their_entry);
/*
* Note: with only one ancestor, some cases are not distinct:
*
* 16: ancest:anc1/anc2, head:anc1, remote:anc2 = result:no merge
* 3: ancest:(empty)^, head:head, remote:(empty) = result:no merge
* 2: ancest:(empty)^, head:(empty), remote:remote = result:no merge
*
* Note that the two cases that take D/F conflicts into account
* specifically do not need to be explicitly tested, as D/F conflicts
* would fail the *empty* test:
*
* 3ALT: ancest:(empty)+, head:head, remote:*empty* = result:head
* 2ALT: ancest:(empty)+, head:*empty*, remote:remote = result:remote
*
* Note that many of these cases need not be explicitly tested, as
* they simply degrade to "all different" cases (eg, 11):
*
* 4: ancest:(empty)^, head:head, remote:remote = result:no merge
* 7: ancest:ancest+, head:(empty), remote:remote = result:no merge
* 9: ancest:ancest+, head:head, remote:(empty) = result:no merge
* 11: ancest:ancest+, head:head, remote:remote = result:no merge
*/
/* 5ALT: ancest:*, head:head, remote:head = result:head */
if (ours_changed && !ours_empty && !ours_theirs_differ)
result = &conflict->our_entry;
/* 6: ancest:ancest+, head:(empty), remote:(empty) = result:no merge */
else if (ours_changed && ours_empty && theirs_empty)
*resolved = 0;
/* 8: ancest:ancest^, head:(empty), remote:ancest = result:no merge */
else if (ours_empty && !theirs_changed)
*resolved = 0;
/* 10: ancest:ancest^, head:ancest, remote:(empty) = result:no merge */
else if (!ours_changed && theirs_empty)
*resolved = 0;
/* 13: ancest:ancest+, head:head, remote:ancest = result:head */
else if (ours_changed && !theirs_changed)
result = &conflict->our_entry;
/* 14: ancest:ancest+, head:ancest, remote:remote = result:remote */
else if (!ours_changed && theirs_changed)
result = &conflict->their_entry;
else
*resolved = 0;
if (result != NULL &&
GIT_MERGE_INDEX_ENTRY_EXISTS(*result) &&
(error = git_vector_insert(&diff_list->staged, (void *)result)) >= 0)
*resolved = 1;
/* Note: trivial resolution does not update the REUC. */
return error;
}
static int merge_conflict_resolve_one_removed(
int *resolved,
git_merge_diff_list *diff_list,
const git_merge_diff *conflict)
{
int ours_empty, theirs_empty;
int ours_changed, theirs_changed;
int error = 0;
GIT_ASSERT_ARG(resolved);
GIT_ASSERT_ARG(diff_list);
GIT_ASSERT_ARG(conflict);
*resolved = 0;
if (conflict->type == GIT_MERGE_DIFF_DIRECTORY_FILE ||
conflict->type == GIT_MERGE_DIFF_RENAMED_ADDED)
return 0;
ours_empty = !GIT_MERGE_INDEX_ENTRY_EXISTS(conflict->our_entry);
theirs_empty = !GIT_MERGE_INDEX_ENTRY_EXISTS(conflict->their_entry);
ours_changed = (conflict->our_status != GIT_DELTA_UNMODIFIED);
theirs_changed = (conflict->their_status != GIT_DELTA_UNMODIFIED);
/* Removed in both */
if (ours_changed && ours_empty && theirs_empty)
*resolved = 1;
/* Removed in ours */
else if (ours_empty && !theirs_changed)
*resolved = 1;
/* Removed in theirs */
else if (!ours_changed && theirs_empty)
*resolved = 1;
if (*resolved)
git_vector_insert(&diff_list->resolved, (git_merge_diff *)conflict);
return error;
}
static int merge_conflict_resolve_one_renamed(
int *resolved,
git_merge_diff_list *diff_list,
const git_merge_diff *conflict)
{
int ours_renamed, theirs_renamed;
int ours_changed, theirs_changed;
git_index_entry *merged;
int error = 0;
GIT_ASSERT_ARG(resolved);
GIT_ASSERT_ARG(diff_list);
GIT_ASSERT_ARG(conflict);
*resolved = 0;
if (!GIT_MERGE_INDEX_ENTRY_EXISTS(conflict->our_entry) ||
!GIT_MERGE_INDEX_ENTRY_EXISTS(conflict->their_entry))
return 0;
ours_renamed = (conflict->our_status == GIT_DELTA_RENAMED);
theirs_renamed = (conflict->their_status == GIT_DELTA_RENAMED);
if (!ours_renamed && !theirs_renamed)
return 0;
/* Reject one file in a 2->1 conflict */
if (conflict->type == GIT_MERGE_DIFF_BOTH_RENAMED_2_TO_1 ||
conflict->type == GIT_MERGE_DIFF_BOTH_RENAMED_1_TO_2 ||
conflict->type == GIT_MERGE_DIFF_RENAMED_ADDED)
return 0;
ours_changed = (git_oid__cmp(&conflict->ancestor_entry.id, &conflict->our_entry.id) != 0) ||
(conflict->ancestor_entry.mode != conflict->our_entry.mode);
theirs_changed = (git_oid__cmp(&conflict->ancestor_entry.id, &conflict->their_entry.id) != 0) ||
(conflict->ancestor_entry.mode != conflict->their_entry.mode);
/* if both are modified (and not to a common target) require a merge */
if (ours_changed && theirs_changed &&
git_oid__cmp(&conflict->our_entry.id, &conflict->their_entry.id) != 0)
return 0;
if ((merged = git_pool_malloc(&diff_list->pool, sizeof(git_index_entry))) == NULL)
return -1;
if (ours_changed)
memcpy(merged, &conflict->our_entry, sizeof(git_index_entry));
else
memcpy(merged, &conflict->their_entry, sizeof(git_index_entry));
if (ours_renamed)
merged->path = conflict->our_entry.path;
else
merged->path = conflict->their_entry.path;
*resolved = 1;
git_vector_insert(&diff_list->staged, merged);
git_vector_insert(&diff_list->resolved, (git_merge_diff *)conflict);
return error;
}
static bool merge_conflict_can_resolve_contents(
const git_merge_diff *conflict)
{
if (!GIT_MERGE_INDEX_ENTRY_EXISTS(conflict->our_entry) ||
!GIT_MERGE_INDEX_ENTRY_EXISTS(conflict->their_entry))
return false;
/* Reject D/F conflicts */
if (conflict->type == GIT_MERGE_DIFF_DIRECTORY_FILE)
return false;
/* Reject submodules. */
if (S_ISGITLINK(conflict->ancestor_entry.mode) ||
S_ISGITLINK(conflict->our_entry.mode) ||
S_ISGITLINK(conflict->their_entry.mode))
return false;
/* Reject link/file conflicts. */
if ((S_ISLNK(conflict->ancestor_entry.mode) ^
S_ISLNK(conflict->our_entry.mode)) ||
(S_ISLNK(conflict->ancestor_entry.mode) ^
S_ISLNK(conflict->their_entry.mode)))
return false;
/* Reject name conflicts */
if (conflict->type == GIT_MERGE_DIFF_BOTH_RENAMED_2_TO_1 ||
conflict->type == GIT_MERGE_DIFF_RENAMED_ADDED)
return false;
if ((conflict->our_status & GIT_DELTA_RENAMED) == GIT_DELTA_RENAMED &&
(conflict->their_status & GIT_DELTA_RENAMED) == GIT_DELTA_RENAMED &&
strcmp(conflict->ancestor_entry.path, conflict->their_entry.path) != 0)
return false;
return true;
}
static int merge_conflict_invoke_driver(
git_index_entry **out,
const char *name,
git_merge_driver *driver,
git_merge_diff_list *diff_list,
git_merge_driver_source *src)
{
git_index_entry *result;
git_buf buf = GIT_BUF_INIT;
const char *path;
uint32_t mode;
git_odb *odb = NULL;
git_oid oid;
int error;
*out = NULL;
if ((error = driver->apply(driver, &path, &mode, &buf, name, src)) < 0 ||
(error = git_repository_odb(&odb, src->repo)) < 0 ||
(error = git_odb_write(&oid, odb, buf.ptr, buf.size, GIT_OBJECT_BLOB)) < 0)
goto done;
result = git_pool_mallocz(&diff_list->pool, sizeof(git_index_entry));
GIT_ERROR_CHECK_ALLOC(result);
git_oid_cpy(&result->id, &oid);
result->mode = mode;
result->file_size = (uint32_t)buf.size;
result->path = git_pool_strdup(&diff_list->pool, path);
GIT_ERROR_CHECK_ALLOC(result->path);
*out = result;
done:
git_buf_dispose(&buf);
git_odb_free(odb);
return error;
}
static int merge_conflict_resolve_contents(
int *resolved,
git_merge_diff_list *diff_list,
const git_merge_diff *conflict,
const git_merge_options *merge_opts,
const git_merge_file_options *file_opts)
{
git_merge_driver_source source = {0};
git_merge_file_result result = {0};
git_merge_driver *driver;
git_merge_driver__builtin builtin = {{0}};
git_index_entry *merge_result;
git_odb *odb = NULL;
const char *name;
bool fallback = false;
int error;
GIT_ASSERT_ARG(resolved);
GIT_ASSERT_ARG(diff_list);
GIT_ASSERT_ARG(conflict);
*resolved = 0;
if (!merge_conflict_can_resolve_contents(conflict))
return 0;
source.repo = diff_list->repo;
source.default_driver = merge_opts->default_driver;
source.file_opts = file_opts;
source.ancestor = GIT_MERGE_INDEX_ENTRY_EXISTS(conflict->ancestor_entry) ?
&conflict->ancestor_entry : NULL;
source.ours = GIT_MERGE_INDEX_ENTRY_EXISTS(conflict->our_entry) ?
&conflict->our_entry : NULL;
source.theirs = GIT_MERGE_INDEX_ENTRY_EXISTS(conflict->their_entry) ?
&conflict->their_entry : NULL;
if (file_opts->favor != GIT_MERGE_FILE_FAVOR_NORMAL) {
/* if the user requested a particular type of resolution (via the
* favor flag) then let that override the gitattributes and use
* the builtin driver.
*/
name = "text";
builtin.base.apply = git_merge_driver__builtin_apply;
builtin.favor = file_opts->favor;
driver = &builtin.base;
} else {
/* find the merge driver for this file */
if ((error = git_merge_driver_for_source(&name, &driver, &source)) < 0)
goto done;
if (driver == NULL)
fallback = true;
}
if (driver) {
error = merge_conflict_invoke_driver(&merge_result, name, driver,
diff_list, &source);
if (error == GIT_PASSTHROUGH)
fallback = true;
}
if (fallback) {
error = merge_conflict_invoke_driver(&merge_result, "text",
&git_merge_driver__text.base, diff_list, &source);
}
if (error < 0) {
if (error == GIT_EMERGECONFLICT)
error = 0;
goto done;
}
git_vector_insert(&diff_list->staged, merge_result);
git_vector_insert(&diff_list->resolved, (git_merge_diff *)conflict);
*resolved = 1;
done:
git_merge_file_result_free(&result);
git_odb_free(odb);
return error;
}
static int merge_conflict_resolve(
int *out,
git_merge_diff_list *diff_list,
const git_merge_diff *conflict,
const git_merge_options *merge_opts,
const git_merge_file_options *file_opts)
{
int resolved = 0;
int error = 0;
*out = 0;
if ((error = merge_conflict_resolve_trivial(
&resolved, diff_list, conflict)) < 0)
goto done;
if (!resolved && (error = merge_conflict_resolve_one_removed(
&resolved, diff_list, conflict)) < 0)
goto done;
if (!resolved && (error = merge_conflict_resolve_one_renamed(
&resolved, diff_list, conflict)) < 0)
goto done;
if (!resolved && (error = merge_conflict_resolve_contents(
&resolved, diff_list, conflict, merge_opts, file_opts)) < 0)
goto done;
*out = resolved;
done:
return error;
}
/* Rename detection and coalescing */
struct merge_diff_similarity {
unsigned char similarity;
size_t other_idx;
};
static int index_entry_similarity_calc(
void **out,
git_repository *repo,
git_index_entry *entry,
const git_merge_options *opts)
{
git_blob *blob;
git_diff_file diff_file = {{{0}}};
git_object_size_t blobsize;
int error;
if (*out || *out == &cache_invalid_marker)
return 0;
*out = NULL;
if ((error = git_blob_lookup(&blob, repo, &entry->id)) < 0)
return error;
git_oid_cpy(&diff_file.id, &entry->id);
diff_file.path = entry->path;
diff_file.size = entry->file_size;
diff_file.mode = entry->mode;
diff_file.flags = 0;
blobsize = git_blob_rawsize(blob);
/* file too big for rename processing */
if (!git__is_sizet(blobsize))
return 0;
error = opts->metric->buffer_signature(out, &diff_file,
git_blob_rawcontent(blob), (size_t)blobsize,
opts->metric->payload);
if (error == GIT_EBUFS)
*out = &cache_invalid_marker;
git_blob_free(blob);
return error;
}
static int index_entry_similarity_inexact(
git_repository *repo,
git_index_entry *a,
size_t a_idx,
git_index_entry *b,
size_t b_idx,
void **cache,
const git_merge_options *opts)
{
int score = 0;
int error = 0;
if (!GIT_MODE_ISBLOB(a->mode) || !GIT_MODE_ISBLOB(b->mode))
return 0;
/* update signature cache if needed */
if ((error = index_entry_similarity_calc(&cache[a_idx], repo, a, opts)) < 0 ||
(error = index_entry_similarity_calc(&cache[b_idx], repo, b, opts)) < 0)
return error;
/* some metrics may not wish to process this file (too big / too small) */
if (cache[a_idx] == &cache_invalid_marker || cache[b_idx] == &cache_invalid_marker)
return 0;
/* compare signatures */
if (opts->metric->similarity(&score, cache[a_idx], cache[b_idx], opts->metric->payload) < 0)
return -1;
/* clip score */
if (score < 0)
score = 0;
else if (score > 100)
score = 100;
return score;
}
/* Tracks deletes by oid for merge_diff_mark_similarity_exact(). This is a
* non-shrinking queue where next_pos is the next position to dequeue.
*/
typedef struct {
git_array_t(size_t) arr;
size_t next_pos;
size_t first_entry;
} deletes_by_oid_queue;
static void deletes_by_oid_free(git_oidmap *map) {
deletes_by_oid_queue *queue;
if (!map)
return;
git_oidmap_foreach_value(map, queue, {
git_array_clear(queue->arr);
});
git_oidmap_free(map);
}
static int deletes_by_oid_enqueue(git_oidmap *map, git_pool *pool, const git_oid *id, size_t idx)
{
deletes_by_oid_queue *queue;
size_t *array_entry;
if ((queue = git_oidmap_get(map, id)) == NULL) {
queue = git_pool_malloc(pool, sizeof(deletes_by_oid_queue));
GIT_ERROR_CHECK_ALLOC(queue);
git_array_init(queue->arr);
queue->next_pos = 0;
queue->first_entry = idx;
if (git_oidmap_set(map, id, queue) < 0)
return -1;
} else {
array_entry = git_array_alloc(queue->arr);
GIT_ERROR_CHECK_ALLOC(array_entry);
*array_entry = idx;
}
return 0;
}
static int deletes_by_oid_dequeue(size_t *idx, git_oidmap *map, const git_oid *id)
{
deletes_by_oid_queue *queue;
size_t *array_entry;
if ((queue = git_oidmap_get(map, id)) == NULL)
return GIT_ENOTFOUND;
if (queue->next_pos == 0) {
*idx = queue->first_entry;
} else {
array_entry = git_array_get(queue->arr, queue->next_pos - 1);
if (array_entry == NULL)
return GIT_ENOTFOUND;
*idx = *array_entry;
}
queue->next_pos++;
return 0;
}
static int merge_diff_mark_similarity_exact(
git_merge_diff_list *diff_list,
struct merge_diff_similarity *similarity_ours,
struct merge_diff_similarity *similarity_theirs)
{
size_t i, j;
git_merge_diff *conflict_src, *conflict_tgt;
git_oidmap *ours_deletes_by_oid = NULL, *theirs_deletes_by_oid = NULL;
int error = 0;
if (git_oidmap_new(&ours_deletes_by_oid) < 0 ||
git_oidmap_new(&theirs_deletes_by_oid) < 0) {
error = -1;
goto done;
}
/* Build a map of object ids to conflicts */
git_vector_foreach(&diff_list->conflicts, i, conflict_src) {
/* Items can be the source of a rename iff they have an item in the
* ancestor slot and lack an item in the ours or theirs slot. */
if (!GIT_MERGE_INDEX_ENTRY_EXISTS(conflict_src->ancestor_entry))
continue;
if (!GIT_MERGE_INDEX_ENTRY_EXISTS(conflict_src->our_entry)) {
error = deletes_by_oid_enqueue(ours_deletes_by_oid, &diff_list->pool, &conflict_src->ancestor_entry.id, i);
if (error < 0)
goto done;
}
if (!GIT_MERGE_INDEX_ENTRY_EXISTS(conflict_src->their_entry)) {
error = deletes_by_oid_enqueue(theirs_deletes_by_oid, &diff_list->pool, &conflict_src->ancestor_entry.id, i);
if (error < 0)
goto done;
}
}
git_vector_foreach(&diff_list->conflicts, j, conflict_tgt) {
if (GIT_MERGE_INDEX_ENTRY_EXISTS(conflict_tgt->ancestor_entry))
continue;
if (GIT_MERGE_INDEX_ENTRY_EXISTS(conflict_tgt->our_entry)) {
if (deletes_by_oid_dequeue(&i, ours_deletes_by_oid, &conflict_tgt->our_entry.id) == 0) {
similarity_ours[i].similarity = 100;
similarity_ours[i].other_idx = j;
similarity_ours[j].similarity = 100;
similarity_ours[j].other_idx = i;
}
}
if (GIT_MERGE_INDEX_ENTRY_EXISTS(conflict_tgt->their_entry)) {
if (deletes_by_oid_dequeue(&i, theirs_deletes_by_oid, &conflict_tgt->their_entry.id) == 0) {
similarity_theirs[i].similarity = 100;
similarity_theirs[i].other_idx = j;
similarity_theirs[j].similarity = 100;
similarity_theirs[j].other_idx = i;
}
}
}
done:
deletes_by_oid_free(ours_deletes_by_oid);
deletes_by_oid_free(theirs_deletes_by_oid);
return error;
}
static int merge_diff_mark_similarity_inexact(
git_repository *repo,
git_merge_diff_list *diff_list,
struct merge_diff_similarity *similarity_ours,
struct merge_diff_similarity *similarity_theirs,
void **cache,
const git_merge_options *opts)
{
size_t i, j;
git_merge_diff *conflict_src, *conflict_tgt;
int similarity;
git_vector_foreach(&diff_list->conflicts, i, conflict_src) {
/* Items can be the source of a rename iff they have an item in the
* ancestor slot and lack an item in the ours or theirs slot. */
if (!GIT_MERGE_INDEX_ENTRY_EXISTS(conflict_src->ancestor_entry) ||
(GIT_MERGE_INDEX_ENTRY_EXISTS(conflict_src->our_entry) &&
GIT_MERGE_INDEX_ENTRY_EXISTS(conflict_src->their_entry)))
continue;
git_vector_foreach(&diff_list->conflicts, j, conflict_tgt) {
size_t our_idx = diff_list->conflicts.length + j;
size_t their_idx = (diff_list->conflicts.length * 2) + j;
if (GIT_MERGE_INDEX_ENTRY_EXISTS(conflict_tgt->ancestor_entry))
continue;
if (GIT_MERGE_INDEX_ENTRY_EXISTS(conflict_tgt->our_entry) &&
!GIT_MERGE_INDEX_ENTRY_EXISTS(conflict_src->our_entry)) {
similarity = index_entry_similarity_inexact(repo, &conflict_src->ancestor_entry, i, &conflict_tgt->our_entry, our_idx, cache, opts);
if (similarity == GIT_EBUFS)
continue;
else if (similarity < 0)
return similarity;
if (similarity > similarity_ours[i].similarity &&
similarity > similarity_ours[j].similarity) {
/* Clear previous best similarity */
if (similarity_ours[i].similarity > 0)
similarity_ours[similarity_ours[i].other_idx].similarity = 0;
if (similarity_ours[j].similarity > 0)
similarity_ours[similarity_ours[j].other_idx].similarity = 0;
similarity_ours[i].similarity = similarity;
similarity_ours[i].other_idx = j;
similarity_ours[j].similarity = similarity;
similarity_ours[j].other_idx = i;
}
}
if (GIT_MERGE_INDEX_ENTRY_EXISTS(conflict_tgt->their_entry) &&
!GIT_MERGE_INDEX_ENTRY_EXISTS(conflict_src->their_entry)) {
similarity = index_entry_similarity_inexact(repo, &conflict_src->ancestor_entry, i, &conflict_tgt->their_entry, their_idx, cache, opts);
if (similarity > similarity_theirs[i].similarity &&
similarity > similarity_theirs[j].similarity) {
/* Clear previous best similarity */
if (similarity_theirs[i].similarity > 0)
similarity_theirs[similarity_theirs[i].other_idx].similarity = 0;
if (similarity_theirs[j].similarity > 0)
similarity_theirs[similarity_theirs[j].other_idx].similarity = 0;
similarity_theirs[i].similarity = similarity;
similarity_theirs[i].other_idx = j;
similarity_theirs[j].similarity = similarity;
similarity_theirs[j].other_idx = i;
}
}
}
}
return 0;
}
/*
* Rename conflicts:
*
* Ancestor Ours Theirs
*
* 0a A A A No rename
* b A A* A No rename (ours was rewritten)
* c A A A* No rename (theirs rewritten)
* 1a A A B[A] Rename or rename/edit
* b A B[A] A (automergeable)
* 2 A B[A] B[A] Both renamed (automergeable)
* 3a A B[A] Rename/delete
* b A B[A] (same)
* 4a A B[A] B Rename/add [B~ours B~theirs]
* b A B B[A] (same)
* 5 A B[A] C[A] Both renamed ("1 -> 2")
* 6 A C[A] Both renamed ("2 -> 1")
* B C[B] [C~ours C~theirs] (automergeable)
*/
static void merge_diff_mark_rename_conflict(
git_merge_diff_list *diff_list,
struct merge_diff_similarity *similarity_ours,
bool ours_renamed,
size_t ours_source_idx,
struct merge_diff_similarity *similarity_theirs,
bool theirs_renamed,
size_t theirs_source_idx,
git_merge_diff *target,
const git_merge_options *opts)
{
git_merge_diff *ours_source = NULL, *theirs_source = NULL;
if (ours_renamed)
ours_source = diff_list->conflicts.contents[ours_source_idx];
if (theirs_renamed)
theirs_source = diff_list->conflicts.contents[theirs_source_idx];
/* Detect 2->1 conflicts */
if (ours_renamed && theirs_renamed) {
/* Both renamed to the same target name. */
if (ours_source_idx == theirs_source_idx)
ours_source->type = GIT_MERGE_DIFF_BOTH_RENAMED;
else {
ours_source->type = GIT_MERGE_DIFF_BOTH_RENAMED_2_TO_1;
theirs_source->type = GIT_MERGE_DIFF_BOTH_RENAMED_2_TO_1;
}
} else if (ours_renamed) {
/* If our source was also renamed in theirs, this is a 1->2 */
if (similarity_theirs[ours_source_idx].similarity >= opts->rename_threshold)
ours_source->type = GIT_MERGE_DIFF_BOTH_RENAMED_1_TO_2;
else if (GIT_MERGE_INDEX_ENTRY_EXISTS(target->their_entry)) {
ours_source->type = GIT_MERGE_DIFF_RENAMED_ADDED;
target->type = GIT_MERGE_DIFF_RENAMED_ADDED;
}
else if (!GIT_MERGE_INDEX_ENTRY_EXISTS(ours_source->their_entry))
ours_source->type = GIT_MERGE_DIFF_RENAMED_DELETED;
else if (ours_source->type == GIT_MERGE_DIFF_MODIFIED_DELETED)
ours_source->type = GIT_MERGE_DIFF_RENAMED_MODIFIED;
} else if (theirs_renamed) {
/* If their source was also renamed in ours, this is a 1->2 */
if (similarity_ours[theirs_source_idx].similarity >= opts->rename_threshold)
theirs_source->type = GIT_MERGE_DIFF_BOTH_RENAMED_1_TO_2;
else if (GIT_MERGE_INDEX_ENTRY_EXISTS(target->our_entry)) {
theirs_source->type = GIT_MERGE_DIFF_RENAMED_ADDED;
target->type = GIT_MERGE_DIFF_RENAMED_ADDED;
}
else if (!GIT_MERGE_INDEX_ENTRY_EXISTS(theirs_source->our_entry))
theirs_source->type = GIT_MERGE_DIFF_RENAMED_DELETED;
else if (theirs_source->type == GIT_MERGE_DIFF_MODIFIED_DELETED)
theirs_source->type = GIT_MERGE_DIFF_RENAMED_MODIFIED;
}
}
GIT_INLINE(void) merge_diff_coalesce_rename(
git_index_entry *source_entry,
git_delta_t *source_status,
git_index_entry *target_entry,
git_delta_t *target_status)
{
/* Coalesce the rename target into the rename source. */
memcpy(source_entry, target_entry, sizeof(git_index_entry));
*source_status = GIT_DELTA_RENAMED;
memset(target_entry, 0x0, sizeof(git_index_entry));
*target_status = GIT_DELTA_UNMODIFIED;
}
static void merge_diff_list_coalesce_renames(
git_merge_diff_list *diff_list,
struct merge_diff_similarity *similarity_ours,
struct merge_diff_similarity *similarity_theirs,
const git_merge_options *opts)
{
size_t i;
bool ours_renamed = 0, theirs_renamed = 0;
size_t ours_source_idx = 0, theirs_source_idx = 0;
git_merge_diff *ours_source, *theirs_source, *target;
for (i = 0; i < diff_list->conflicts.length; i++) {
target = diff_list->conflicts.contents[i];
ours_renamed = 0;
theirs_renamed = 0;
if (GIT_MERGE_INDEX_ENTRY_EXISTS(target->our_entry) &&
similarity_ours[i].similarity >= opts->rename_threshold) {
ours_source_idx = similarity_ours[i].other_idx;
ours_source = diff_list->conflicts.contents[ours_source_idx];
merge_diff_coalesce_rename(
&ours_source->our_entry,
&ours_source->our_status,
&target->our_entry,
&target->our_status);
similarity_ours[ours_source_idx].similarity = 0;
similarity_ours[i].similarity = 0;
ours_renamed = 1;
}
/* insufficient to determine direction */
if (GIT_MERGE_INDEX_ENTRY_EXISTS(target->their_entry) &&
similarity_theirs[i].similarity >= opts->rename_threshold) {
theirs_source_idx = similarity_theirs[i].other_idx;
theirs_source = diff_list->conflicts.contents[theirs_source_idx];
merge_diff_coalesce_rename(
&theirs_source->their_entry,
&theirs_source->their_status,
&target->their_entry,
&target->their_status);
similarity_theirs[theirs_source_idx].similarity = 0;
similarity_theirs[i].similarity = 0;
theirs_renamed = 1;
}
merge_diff_mark_rename_conflict(diff_list,
similarity_ours, ours_renamed, ours_source_idx,
similarity_theirs, theirs_renamed, theirs_source_idx,
target, opts);
}
}
static int merge_diff_empty(const git_vector *conflicts, size_t idx, void *p)
{
git_merge_diff *conflict = conflicts->contents[idx];
GIT_UNUSED(p);
return (!GIT_MERGE_INDEX_ENTRY_EXISTS(conflict->ancestor_entry) &&
!GIT_MERGE_INDEX_ENTRY_EXISTS(conflict->our_entry) &&
!GIT_MERGE_INDEX_ENTRY_EXISTS(conflict->their_entry));
}
static void merge_diff_list_count_candidates(
git_merge_diff_list *diff_list,
size_t *src_count,
size_t *tgt_count)
{
git_merge_diff *entry;
size_t i;
*src_count = 0;
*tgt_count = 0;
git_vector_foreach(&diff_list->conflicts, i, entry) {
if (GIT_MERGE_INDEX_ENTRY_EXISTS(entry->ancestor_entry) &&
(!GIT_MERGE_INDEX_ENTRY_EXISTS(entry->our_entry) ||
!GIT_MERGE_INDEX_ENTRY_EXISTS(entry->their_entry)))
(*src_count)++;
else if (!GIT_MERGE_INDEX_ENTRY_EXISTS(entry->ancestor_entry))
(*tgt_count)++;
}
}
int git_merge_diff_list__find_renames(
git_repository *repo,
git_merge_diff_list *diff_list,
const git_merge_options *opts)
{
struct merge_diff_similarity *similarity_ours, *similarity_theirs;
void **cache = NULL;
size_t cache_size = 0;
size_t src_count, tgt_count, i;
int error = 0;
GIT_ASSERT_ARG(diff_list);
GIT_ASSERT_ARG(opts);
if ((opts->flags & GIT_MERGE_FIND_RENAMES) == 0 ||
!diff_list->conflicts.length)
return 0;
similarity_ours = git__calloc(diff_list->conflicts.length,
sizeof(struct merge_diff_similarity));
GIT_ERROR_CHECK_ALLOC(similarity_ours);
similarity_theirs = git__calloc(diff_list->conflicts.length,
sizeof(struct merge_diff_similarity));
GIT_ERROR_CHECK_ALLOC(similarity_theirs);
/* Calculate similarity between items that were deleted from the ancestor
* and added in the other branch.
*/
if ((error = merge_diff_mark_similarity_exact(diff_list, similarity_ours, similarity_theirs)) < 0)
goto done;
if (opts->rename_threshold < 100 && diff_list->conflicts.length <= opts->target_limit) {
GIT_ERROR_CHECK_ALLOC_MULTIPLY(&cache_size, diff_list->conflicts.length, 3);
cache = git__calloc(cache_size, sizeof(void *));
GIT_ERROR_CHECK_ALLOC(cache);
merge_diff_list_count_candidates(diff_list, &src_count, &tgt_count);
if (src_count > opts->target_limit || tgt_count > opts->target_limit) {
/* TODO: report! */
} else {
if ((error = merge_diff_mark_similarity_inexact(
repo, diff_list, similarity_ours, similarity_theirs, cache, opts)) < 0)
goto done;
}
}
/* For entries that are appropriately similar, merge the new name's entry
* into the old name.
*/
merge_diff_list_coalesce_renames(diff_list, similarity_ours, similarity_theirs, opts);
/* And remove any entries that were merged and are now empty. */
git_vector_remove_matching(&diff_list->conflicts, merge_diff_empty, NULL);
done:
if (cache != NULL) {
for (i = 0; i < cache_size; ++i) {
if (cache[i] != NULL && cache[i] != &cache_invalid_marker)
opts->metric->free_signature(cache[i], opts->metric->payload);
}
git__free(cache);
}
git__free(similarity_ours);
git__free(similarity_theirs);
return error;
}
/* Directory/file conflict handling */
GIT_INLINE(const char *) merge_diff_path(
const git_merge_diff *conflict)
{
if (GIT_MERGE_INDEX_ENTRY_EXISTS(conflict->ancestor_entry))
return conflict->ancestor_entry.path;
else if (GIT_MERGE_INDEX_ENTRY_EXISTS(conflict->our_entry))
return conflict->our_entry.path;
else if (GIT_MERGE_INDEX_ENTRY_EXISTS(conflict->their_entry))
return conflict->their_entry.path;
return NULL;
}
GIT_INLINE(bool) merge_diff_any_side_added_or_modified(
const git_merge_diff *conflict)
{
if (conflict->our_status == GIT_DELTA_ADDED ||
conflict->our_status == GIT_DELTA_MODIFIED ||
conflict->their_status == GIT_DELTA_ADDED ||
conflict->their_status == GIT_DELTA_MODIFIED)
return true;
return false;
}
GIT_INLINE(bool) path_is_prefixed(const char *parent, const char *child)
{
size_t child_len = strlen(child);
size_t parent_len = strlen(parent);
if (child_len < parent_len ||
strncmp(parent, child, parent_len) != 0)
return 0;
return (child[parent_len] == '/');
}
GIT_INLINE(int) merge_diff_detect_df_conflict(
struct merge_diff_df_data *df_data,
git_merge_diff *conflict)
{
const char *cur_path = merge_diff_path(conflict);
/* Determine if this is a D/F conflict or the child of one */
if (df_data->df_path &&
path_is_prefixed(df_data->df_path, cur_path))
conflict->type = GIT_MERGE_DIFF_DF_CHILD;
else if(df_data->df_path)
df_data->df_path = NULL;
else if (df_data->prev_path &&
merge_diff_any_side_added_or_modified(df_data->prev_conflict) &&
merge_diff_any_side_added_or_modified(conflict) &&
path_is_prefixed(df_data->prev_path, cur_path)) {
conflict->type = GIT_MERGE_DIFF_DF_CHILD;
df_data->prev_conflict->type = GIT_MERGE_DIFF_DIRECTORY_FILE;
df_data->df_path = df_data->prev_path;
}
df_data->prev_path = cur_path;
df_data->prev_conflict = conflict;
return 0;
}
/* Conflict handling */
GIT_INLINE(int) merge_diff_detect_type(
git_merge_diff *conflict)
{
if (conflict->our_status == GIT_DELTA_ADDED &&
conflict->their_status == GIT_DELTA_ADDED)
conflict->type = GIT_MERGE_DIFF_BOTH_ADDED;
else if (conflict->our_status == GIT_DELTA_MODIFIED &&
conflict->their_status == GIT_DELTA_MODIFIED)
conflict->type = GIT_MERGE_DIFF_BOTH_MODIFIED;
else if (conflict->our_status == GIT_DELTA_DELETED &&
conflict->their_status == GIT_DELTA_DELETED)
conflict->type = GIT_MERGE_DIFF_BOTH_DELETED;
else if (conflict->our_status == GIT_DELTA_MODIFIED &&
conflict->their_status == GIT_DELTA_DELETED)
conflict->type = GIT_MERGE_DIFF_MODIFIED_DELETED;
else if (conflict->our_status == GIT_DELTA_DELETED &&
conflict->their_status == GIT_DELTA_MODIFIED)
conflict->type = GIT_MERGE_DIFF_MODIFIED_DELETED;
else
conflict->type = GIT_MERGE_DIFF_NONE;
return 0;
}
GIT_INLINE(int) index_entry_dup_pool(
git_index_entry *out,
git_pool *pool,
const git_index_entry *src)
{
if (src != NULL) {
memcpy(out, src, sizeof(git_index_entry));
if ((out->path = git_pool_strdup(pool, src->path)) == NULL)
return -1;
}
return 0;
}
GIT_INLINE(int) merge_delta_type_from_index_entries(
const git_index_entry *ancestor,
const git_index_entry *other)
{
if (ancestor == NULL && other == NULL)
return GIT_DELTA_UNMODIFIED;
else if (ancestor == NULL && other != NULL)
return GIT_DELTA_ADDED;
else if (ancestor != NULL && other == NULL)
return GIT_DELTA_DELETED;
else if (S_ISDIR(ancestor->mode) ^ S_ISDIR(other->mode))
return GIT_DELTA_TYPECHANGE;
else if(S_ISLNK(ancestor->mode) ^ S_ISLNK(other->mode))
return GIT_DELTA_TYPECHANGE;
else if (git_oid__cmp(&ancestor->id, &other->id) ||
ancestor->mode != other->mode)
return GIT_DELTA_MODIFIED;
return GIT_DELTA_UNMODIFIED;
}
static git_merge_diff *merge_diff_from_index_entries(
git_merge_diff_list *diff_list,
const git_index_entry **entries)
{
git_merge_diff *conflict;
git_pool *pool = &diff_list->pool;
if ((conflict = git_pool_mallocz(pool, sizeof(git_merge_diff))) == NULL)
return NULL;
if (index_entry_dup_pool(&conflict->ancestor_entry, pool, entries[TREE_IDX_ANCESTOR]) < 0 ||
index_entry_dup_pool(&conflict->our_entry, pool, entries[TREE_IDX_OURS]) < 0 ||
index_entry_dup_pool(&conflict->their_entry, pool, entries[TREE_IDX_THEIRS]) < 0)
return NULL;
conflict->our_status = merge_delta_type_from_index_entries(
entries[TREE_IDX_ANCESTOR], entries[TREE_IDX_OURS]);
conflict->their_status = merge_delta_type_from_index_entries(
entries[TREE_IDX_ANCESTOR], entries[TREE_IDX_THEIRS]);
return conflict;
}
/* Merge trees */
static int merge_diff_list_insert_conflict(
git_merge_diff_list *diff_list,
struct merge_diff_df_data *merge_df_data,
const git_index_entry *tree_items[3])
{
git_merge_diff *conflict;
if ((conflict = merge_diff_from_index_entries(diff_list, tree_items)) == NULL ||
merge_diff_detect_type(conflict) < 0 ||
merge_diff_detect_df_conflict(merge_df_data, conflict) < 0 ||
git_vector_insert(&diff_list->conflicts, conflict) < 0)
return -1;
return 0;
}
static int merge_diff_list_insert_unmodified(
git_merge_diff_list *diff_list,
const git_index_entry *tree_items[3])
{
int error = 0;
git_index_entry *entry;
entry = git_pool_malloc(&diff_list->pool, sizeof(git_index_entry));
GIT_ERROR_CHECK_ALLOC(entry);
if ((error = index_entry_dup_pool(entry, &diff_list->pool, tree_items[0])) >= 0)
error = git_vector_insert(&diff_list->staged, entry);
return error;
}
struct merge_diff_find_data {
git_merge_diff_list *diff_list;
struct merge_diff_df_data df_data;
};
static int queue_difference(const git_index_entry **entries, void *data)
{
struct merge_diff_find_data *find_data = data;
bool item_modified = false;
size_t i;
if (!entries[0] || !entries[1] || !entries[2]) {
item_modified = true;
} else {
for (i = 1; i < 3; i++) {
if (index_entry_cmp(entries[0], entries[i]) != 0) {
item_modified = true;
break;
}
}
}
return item_modified ?
merge_diff_list_insert_conflict(
find_data->diff_list, &find_data->df_data, entries) :
merge_diff_list_insert_unmodified(find_data->diff_list, entries);
}
int git_merge_diff_list__find_differences(
git_merge_diff_list *diff_list,
git_iterator *ancestor_iter,
git_iterator *our_iter,
git_iterator *their_iter)
{
git_iterator *iterators[3] = { ancestor_iter, our_iter, their_iter };
struct merge_diff_find_data find_data = { diff_list };
return git_iterator_walk(iterators, 3, queue_difference, &find_data);
}
git_merge_diff_list *git_merge_diff_list__alloc(git_repository *repo)
{
git_merge_diff_list *diff_list = git__calloc(1, sizeof(git_merge_diff_list));
if (diff_list == NULL)
return NULL;
diff_list->repo = repo;
if (git_pool_init(&diff_list->pool, 1) < 0 ||
git_vector_init(&diff_list->staged, 0, NULL) < 0 ||
git_vector_init(&diff_list->conflicts, 0, NULL) < 0 ||
git_vector_init(&diff_list->resolved, 0, NULL) < 0) {
git_merge_diff_list__free(diff_list);
return NULL;
}
return diff_list;
}
void git_merge_diff_list__free(git_merge_diff_list *diff_list)
{
if (!diff_list)
return;
git_vector_free(&diff_list->staged);
git_vector_free(&diff_list->conflicts);
git_vector_free(&diff_list->resolved);
git_pool_clear(&diff_list->pool);
git__free(diff_list);
}
static int merge_normalize_opts(
git_repository *repo,
git_merge_options *opts,
const git_merge_options *given)
{
git_config *cfg = NULL;
git_config_entry *entry = NULL;
int error = 0;
GIT_ASSERT_ARG(repo);
GIT_ASSERT_ARG(opts);
if ((error = git_repository_config__weakptr(&cfg, repo)) < 0)
return error;
if (given != NULL) {
memcpy(opts, given, sizeof(git_merge_options));
} else {
git_merge_options init = GIT_MERGE_OPTIONS_INIT;
memcpy(opts, &init, sizeof(init));
}
if ((opts->flags & GIT_MERGE_FIND_RENAMES) && !opts->rename_threshold)
opts->rename_threshold = GIT_MERGE_DEFAULT_RENAME_THRESHOLD;
if (given && given->default_driver) {
opts->default_driver = git__strdup(given->default_driver);
GIT_ERROR_CHECK_ALLOC(opts->default_driver);
} else {
error = git_config_get_entry(&entry, cfg, "merge.default");
if (error == 0) {
opts->default_driver = git__strdup(entry->value);
GIT_ERROR_CHECK_ALLOC(opts->default_driver);
} else if (error == GIT_ENOTFOUND) {
error = 0;
} else {
goto done;
}
}
if (!opts->target_limit) {
int limit = git_config__get_int_force(cfg, "merge.renamelimit", 0);
if (!limit)
limit = git_config__get_int_force(cfg, "diff.renamelimit", 0);
opts->target_limit = (limit <= 0) ?
GIT_MERGE_DEFAULT_TARGET_LIMIT : (unsigned int)limit;
}
/* assign the internal metric with whitespace flag as payload */
if (!opts->metric) {
opts->metric = git__malloc(sizeof(git_diff_similarity_metric));
GIT_ERROR_CHECK_ALLOC(opts->metric);
opts->metric->file_signature = git_diff_find_similar__hashsig_for_file;
opts->metric->buffer_signature = git_diff_find_similar__hashsig_for_buf;
opts->metric->free_signature = git_diff_find_similar__hashsig_free;
opts->metric->similarity = git_diff_find_similar__calc_similarity;
opts->metric->payload = (void *)GIT_HASHSIG_SMART_WHITESPACE;
}
done:
git_config_entry_free(entry);
return error;
}
static int merge_index_insert_reuc(
git_index *index,
size_t idx,
const git_index_entry *entry)
{
const git_index_reuc_entry *reuc;
int mode[3] = { 0, 0, 0 };
git_oid const *oid[3] = { NULL, NULL, NULL };
size_t i;
if (!GIT_MERGE_INDEX_ENTRY_EXISTS(*entry))
return 0;
if ((reuc = git_index_reuc_get_bypath(index, entry->path)) != NULL) {
for (i = 0; i < 3; i++) {
mode[i] = reuc->mode[i];
oid[i] = &reuc->oid[i];
}
}
mode[idx] = entry->mode;
oid[idx] = &entry->id;
return git_index_reuc_add(index, entry->path,
mode[0], oid[0], mode[1], oid[1], mode[2], oid[2]);
}
static int index_update_reuc(git_index *index, git_merge_diff_list *diff_list)
{
int error;
size_t i;
git_merge_diff *conflict;
/* Add each entry in the resolved conflict to the REUC independently, since
* the paths may differ due to renames. */
git_vector_foreach(&diff_list->resolved, i, conflict) {
const git_index_entry *ancestor =
GIT_MERGE_INDEX_ENTRY_EXISTS(conflict->ancestor_entry) ?
&conflict->ancestor_entry : NULL;
const git_index_entry *ours =
GIT_MERGE_INDEX_ENTRY_EXISTS(conflict->our_entry) ?
&conflict->our_entry : NULL;
const git_index_entry *theirs =
GIT_MERGE_INDEX_ENTRY_EXISTS(conflict->their_entry) ?
&conflict->their_entry : NULL;
if (ancestor != NULL &&
(error = merge_index_insert_reuc(index, TREE_IDX_ANCESTOR, ancestor)) < 0)
return error;
if (ours != NULL &&
(error = merge_index_insert_reuc(index, TREE_IDX_OURS, ours)) < 0)
return error;
if (theirs != NULL &&
(error = merge_index_insert_reuc(index, TREE_IDX_THEIRS, theirs)) < 0)
return error;
}
return 0;
}
static int index_from_diff_list(git_index **out,
git_merge_diff_list *diff_list, bool skip_reuc)
{
git_index *index;
size_t i;
git_merge_diff *conflict;
int error = 0;
*out = NULL;
if ((error = git_index_new(&index)) < 0)
return error;
if ((error = git_index__fill(index, &diff_list->staged)) < 0)
goto on_error;
git_vector_foreach(&diff_list->conflicts, i, conflict) {
const git_index_entry *ancestor =
GIT_MERGE_INDEX_ENTRY_EXISTS(conflict->ancestor_entry) ?
&conflict->ancestor_entry : NULL;
const git_index_entry *ours =
GIT_MERGE_INDEX_ENTRY_EXISTS(conflict->our_entry) ?
&conflict->our_entry : NULL;
const git_index_entry *theirs =
GIT_MERGE_INDEX_ENTRY_EXISTS(conflict->their_entry) ?
&conflict->their_entry : NULL;
if ((error = git_index_conflict_add(index, ancestor, ours, theirs)) < 0)
goto on_error;
}
/* Add each rename entry to the rename portion of the index. */
git_vector_foreach(&diff_list->conflicts, i, conflict) {
const char *ancestor_path, *our_path, *their_path;
if (!GIT_MERGE_INDEX_ENTRY_EXISTS(conflict->ancestor_entry))
continue;
ancestor_path = conflict->ancestor_entry.path;
our_path =
GIT_MERGE_INDEX_ENTRY_EXISTS(conflict->our_entry) ?
conflict->our_entry.path : NULL;
their_path =
GIT_MERGE_INDEX_ENTRY_EXISTS(conflict->their_entry) ?
conflict->their_entry.path : NULL;
if ((our_path && strcmp(ancestor_path, our_path) != 0) ||
(their_path && strcmp(ancestor_path, their_path) != 0)) {
if ((error = git_index_name_add(index, ancestor_path, our_path, their_path)) < 0)
goto on_error;
}
}
if (!skip_reuc) {
if ((error = index_update_reuc(index, diff_list)) < 0)
goto on_error;
}
*out = index;
return 0;
on_error:
git_index_free(index);
return error;
}
static git_iterator *iterator_given_or_empty(git_iterator **empty, git_iterator *given)
{
git_iterator_options opts = GIT_ITERATOR_OPTIONS_INIT;
if (given)
return given;
opts.flags = GIT_ITERATOR_DONT_IGNORE_CASE;
if (git_iterator_for_nothing(empty, &opts) < 0)
return NULL;
return *empty;
}
int git_merge__iterators(
git_index **out,
git_repository *repo,
git_iterator *ancestor_iter,
git_iterator *our_iter,
git_iterator *theirs_iter,
const git_merge_options *given_opts)
{
git_iterator *empty_ancestor = NULL,
*empty_ours = NULL,
*empty_theirs = NULL;
git_merge_diff_list *diff_list;
git_merge_options opts;
git_merge_file_options file_opts = GIT_MERGE_FILE_OPTIONS_INIT;
git_merge_diff *conflict;
git_vector changes;
size_t i;
int error = 0;
GIT_ASSERT_ARG(out);
GIT_ASSERT_ARG(repo);
*out = NULL;
GIT_ERROR_CHECK_VERSION(
given_opts, GIT_MERGE_OPTIONS_VERSION, "git_merge_options");
if ((error = merge_normalize_opts(repo, &opts, given_opts)) < 0)
return error;
file_opts.favor = opts.file_favor;
file_opts.flags = opts.file_flags;
/* use the git-inspired labels when virtual base building */
if (opts.flags & GIT_MERGE__VIRTUAL_BASE) {
file_opts.ancestor_label = "merged common ancestors";
file_opts.our_label = "Temporary merge branch 1";
file_opts.their_label = "Temporary merge branch 2";
file_opts.flags |= GIT_MERGE_FILE_FAVOR__CONFLICTED;
file_opts.marker_size = GIT_MERGE_CONFLICT_MARKER_SIZE + 2;
}
diff_list = git_merge_diff_list__alloc(repo);
GIT_ERROR_CHECK_ALLOC(diff_list);
ancestor_iter = iterator_given_or_empty(&empty_ancestor, ancestor_iter);
our_iter = iterator_given_or_empty(&empty_ours, our_iter);
theirs_iter = iterator_given_or_empty(&empty_theirs, theirs_iter);
if ((error = git_merge_diff_list__find_differences(
diff_list, ancestor_iter, our_iter, theirs_iter)) < 0 ||
(error = git_merge_diff_list__find_renames(repo, diff_list, &opts)) < 0)
goto done;
memcpy(&changes, &diff_list->conflicts, sizeof(git_vector));
git_vector_clear(&diff_list->conflicts);
git_vector_foreach(&changes, i, conflict) {
int resolved = 0;
if ((error = merge_conflict_resolve(
&resolved, diff_list, conflict, &opts, &file_opts)) < 0)
goto done;
if (!resolved) {
if ((opts.flags & GIT_MERGE_FAIL_ON_CONFLICT)) {
git_error_set(GIT_ERROR_MERGE, "merge conflicts exist");
error = GIT_EMERGECONFLICT;
goto done;
}
git_vector_insert(&diff_list->conflicts, conflict);
}
}
error = index_from_diff_list(out, diff_list,
(opts.flags & GIT_MERGE_SKIP_REUC));
done:
if (!given_opts || !given_opts->metric)
git__free(opts.metric);
git__free((char *)opts.default_driver);
git_merge_diff_list__free(diff_list);
git_iterator_free(empty_ancestor);
git_iterator_free(empty_ours);
git_iterator_free(empty_theirs);
return error;
}
int git_merge_trees(
git_index **out,
git_repository *repo,
const git_tree *ancestor_tree,
const git_tree *our_tree,
const git_tree *their_tree,
const git_merge_options *merge_opts)
{
git_iterator *ancestor_iter = NULL, *our_iter = NULL, *their_iter = NULL;
git_iterator_options iter_opts = GIT_ITERATOR_OPTIONS_INIT;
int error;
GIT_ASSERT_ARG(out);
GIT_ASSERT_ARG(repo);
/* if one side is treesame to the ancestor, take the other side */
if (ancestor_tree && merge_opts && (merge_opts->flags & GIT_MERGE_SKIP_REUC)) {
const git_tree *result = NULL;
const git_oid *ancestor_tree_id = git_tree_id(ancestor_tree);
if (our_tree && !git_oid_cmp(ancestor_tree_id, git_tree_id(our_tree)))
result = their_tree;
else if (their_tree && !git_oid_cmp(ancestor_tree_id, git_tree_id(their_tree)))
result = our_tree;
if (result) {
if ((error = git_index_new(out)) == 0)
error = git_index_read_tree(*out, result);
return error;
}
}
iter_opts.flags = GIT_ITERATOR_DONT_IGNORE_CASE;
if ((error = git_iterator_for_tree(
&ancestor_iter, (git_tree *)ancestor_tree, &iter_opts)) < 0 ||
(error = git_iterator_for_tree(
&our_iter, (git_tree *)our_tree, &iter_opts)) < 0 ||
(error = git_iterator_for_tree(
&their_iter, (git_tree *)their_tree, &iter_opts)) < 0)
goto done;
error = git_merge__iterators(
out, repo, ancestor_iter, our_iter, their_iter, merge_opts);
done:
git_iterator_free(ancestor_iter);
git_iterator_free(our_iter);
git_iterator_free(their_iter);
return error;
}
static int merge_annotated_commits(
git_index **index_out,
git_annotated_commit **base_out,
git_repository *repo,
git_annotated_commit *our_commit,
git_annotated_commit *their_commit,
size_t recursion_level,
const git_merge_options *opts);
GIT_INLINE(int) insert_head_ids(
git_array_oid_t *ids,
const git_annotated_commit *annotated_commit)
{
git_oid *id;
size_t i;
if (annotated_commit->type == GIT_ANNOTATED_COMMIT_REAL) {
id = git_array_alloc(*ids);
GIT_ERROR_CHECK_ALLOC(id);
git_oid_cpy(id, git_commit_id(annotated_commit->commit));
} else {
for (i = 0; i < annotated_commit->parents.size; i++) {
id = git_array_alloc(*ids);
GIT_ERROR_CHECK_ALLOC(id);
git_oid_cpy(id, &annotated_commit->parents.ptr[i]);
}
}
return 0;
}
static int create_virtual_base(
git_annotated_commit **out,
git_repository *repo,
git_annotated_commit *one,
git_annotated_commit *two,
const git_merge_options *opts,
size_t recursion_level)
{
git_annotated_commit *result = NULL;
git_index *index = NULL;
git_merge_options virtual_opts = GIT_MERGE_OPTIONS_INIT;
/* Conflicts in the merge base creation do not propagate to conflicts
* in the result; the conflicted base will act as the common ancestor.
*/
if (opts)
memcpy(&virtual_opts, opts, sizeof(git_merge_options));
virtual_opts.flags &= ~GIT_MERGE_FAIL_ON_CONFLICT;
virtual_opts.flags |= GIT_MERGE__VIRTUAL_BASE;
if ((merge_annotated_commits(&index, NULL, repo, one, two,
recursion_level + 1, &virtual_opts)) < 0)
return -1;
result = git__calloc(1, sizeof(git_annotated_commit));
GIT_ERROR_CHECK_ALLOC(result);
result->type = GIT_ANNOTATED_COMMIT_VIRTUAL;
result->index = index;
if (insert_head_ids(&result->parents, one) < 0 ||
insert_head_ids(&result->parents, two) < 0) {
git_annotated_commit_free(result);
return -1;
}
*out = result;
return 0;
}
static int compute_base(
git_annotated_commit **out,
git_repository *repo,
const git_annotated_commit *one,
const git_annotated_commit *two,
const git_merge_options *given_opts,
size_t recursion_level)
{
git_array_oid_t head_ids = GIT_ARRAY_INIT;
git_oidarray bases = {0};
git_annotated_commit *base = NULL, *other = NULL, *new_base = NULL;
git_merge_options opts = GIT_MERGE_OPTIONS_INIT;
size_t i, base_count;
int error;
*out = NULL;
if (given_opts)
memcpy(&opts, given_opts, sizeof(git_merge_options));
/* With more than two commits, merge_bases_many finds the base of
* the first commit and a hypothetical merge of the others. Since
* "one" may itself be a virtual commit, which insert_head_ids
* substitutes multiple ancestors for, it needs to be added
* after "two" which is always a single real commit.
*/
if ((error = insert_head_ids(&head_ids, two)) < 0 ||
(error = insert_head_ids(&head_ids, one)) < 0 ||
(error = git_merge_bases_many(&bases, repo,
head_ids.size, head_ids.ptr)) < 0)
goto done;
base_count = (opts.flags & GIT_MERGE_NO_RECURSIVE) ? 0 : bases.count;
if (base_count)
git_oidarray__reverse(&bases);
if ((error = git_annotated_commit_lookup(&base, repo, &bases.ids[0])) < 0)
goto done;
for (i = 1; i < base_count; i++) {
recursion_level++;
if (opts.recursion_limit && recursion_level > opts.recursion_limit)
break;
if ((error = git_annotated_commit_lookup(&other, repo,
&bases.ids[i])) < 0 ||
(error = create_virtual_base(&new_base, repo, base, other, &opts,
recursion_level)) < 0)
goto done;
git_annotated_commit_free(base);
git_annotated_commit_free(other);
base = new_base;
new_base = NULL;
other = NULL;
}
done:
if (error == 0)
*out = base;
else
git_annotated_commit_free(base);
git_annotated_commit_free(other);
git_annotated_commit_free(new_base);
git_oidarray_dispose(&bases);
git_array_clear(head_ids);
return error;
}
static int iterator_for_annotated_commit(
git_iterator **out,
git_annotated_commit *commit)
{
git_iterator_options opts = GIT_ITERATOR_OPTIONS_INIT;
int error;
opts.flags = GIT_ITERATOR_DONT_IGNORE_CASE;
if (commit == NULL) {
error = git_iterator_for_nothing(out, &opts);
} else if (commit->type == GIT_ANNOTATED_COMMIT_VIRTUAL) {
error = git_iterator_for_index(out, git_index_owner(commit->index), commit->index, &opts);
} else {
if (!commit->tree &&
(error = git_commit_tree(&commit->tree, commit->commit)) < 0)
goto done;
error = git_iterator_for_tree(out, commit->tree, &opts);
}
done:
return error;
}
static int merge_annotated_commits(
git_index **index_out,
git_annotated_commit **base_out,
git_repository *repo,
git_annotated_commit *ours,
git_annotated_commit *theirs,
size_t recursion_level,
const git_merge_options *opts)
{
git_annotated_commit *base = NULL;
git_iterator *base_iter = NULL, *our_iter = NULL, *their_iter = NULL;
int error;
if ((error = compute_base(&base, repo, ours, theirs, opts,
recursion_level)) < 0) {
if (error != GIT_ENOTFOUND)
goto done;
git_error_clear();
}
if ((error = iterator_for_annotated_commit(&base_iter, base)) < 0 ||
(error = iterator_for_annotated_commit(&our_iter, ours)) < 0 ||
(error = iterator_for_annotated_commit(&their_iter, theirs)) < 0 ||
(error = git_merge__iterators(index_out, repo, base_iter, our_iter,
their_iter, opts)) < 0)
goto done;
if (base_out) {
*base_out = base;
base = NULL;
}
done:
git_annotated_commit_free(base);
git_iterator_free(base_iter);
git_iterator_free(our_iter);
git_iterator_free(their_iter);
return error;
}
int git_merge_commits(
git_index **out,
git_repository *repo,
const git_commit *our_commit,
const git_commit *their_commit,
const git_merge_options *opts)
{
git_annotated_commit *ours = NULL, *theirs = NULL, *base = NULL;
int error = 0;
if ((error = git_annotated_commit_from_commit(&ours, (git_commit *)our_commit)) < 0 ||
(error = git_annotated_commit_from_commit(&theirs, (git_commit *)their_commit)) < 0)
goto done;
error = merge_annotated_commits(out, &base, repo, ours, theirs, 0, opts);
done:
git_annotated_commit_free(ours);
git_annotated_commit_free(theirs);
git_annotated_commit_free(base);
return error;
}
/* Merge setup / cleanup */
static int write_merge_head(
git_repository *repo,
const git_annotated_commit *heads[],
size_t heads_len)
{
git_filebuf file = GIT_FILEBUF_INIT;
git_buf file_path = GIT_BUF_INIT;
size_t i;
int error = 0;
GIT_ASSERT_ARG(repo);
GIT_ASSERT_ARG(heads);
if ((error = git_buf_joinpath(&file_path, repo->gitdir, GIT_MERGE_HEAD_FILE)) < 0 ||
(error = git_filebuf_open(&file, file_path.ptr, GIT_FILEBUF_CREATE_LEADING_DIRS, GIT_MERGE_FILE_MODE)) < 0)
goto cleanup;
for (i = 0; i < heads_len; i++) {
if ((error = git_filebuf_printf(&file, "%s\n", heads[i]->id_str)) < 0)
goto cleanup;
}
error = git_filebuf_commit(&file);
cleanup:
if (error < 0)
git_filebuf_cleanup(&file);
git_buf_dispose(&file_path);
return error;
}
static int write_merge_mode(git_repository *repo)
{
git_filebuf file = GIT_FILEBUF_INIT;
git_buf file_path = GIT_BUF_INIT;
int error = 0;
GIT_ASSERT_ARG(repo);
if ((error = git_buf_joinpath(&file_path, repo->gitdir, GIT_MERGE_MODE_FILE)) < 0 ||
(error = git_filebuf_open(&file, file_path.ptr, GIT_FILEBUF_CREATE_LEADING_DIRS, GIT_MERGE_FILE_MODE)) < 0)
goto cleanup;
if ((error = git_filebuf_write(&file, "no-ff", 5)) < 0)
goto cleanup;
error = git_filebuf_commit(&file);
cleanup:
if (error < 0)
git_filebuf_cleanup(&file);
git_buf_dispose(&file_path);
return error;
}
struct merge_msg_entry {
const git_annotated_commit *merge_head;
bool written;
};
static int msg_entry_is_branch(
const struct merge_msg_entry *entry,
git_vector *entries)
{
GIT_UNUSED(entries);
return (entry->written == 0 &&
entry->merge_head->remote_url == NULL &&
entry->merge_head->ref_name != NULL &&
git__strncmp(GIT_REFS_HEADS_DIR, entry->merge_head->ref_name, strlen(GIT_REFS_HEADS_DIR)) == 0);
}
static int msg_entry_is_tracking(
const struct merge_msg_entry *entry,
git_vector *entries)
{
GIT_UNUSED(entries);
return (entry->written == 0 &&
entry->merge_head->remote_url == NULL &&
entry->merge_head->ref_name != NULL &&
git__strncmp(GIT_REFS_REMOTES_DIR, entry->merge_head->ref_name, strlen(GIT_REFS_REMOTES_DIR)) == 0);
}
static int msg_entry_is_tag(
const struct merge_msg_entry *entry,
git_vector *entries)
{
GIT_UNUSED(entries);
return (entry->written == 0 &&
entry->merge_head->remote_url == NULL &&
entry->merge_head->ref_name != NULL &&
git__strncmp(GIT_REFS_TAGS_DIR, entry->merge_head->ref_name, strlen(GIT_REFS_TAGS_DIR)) == 0);
}
static int msg_entry_is_remote(
const struct merge_msg_entry *entry,
git_vector *entries)
{
if (entry->written == 0 &&
entry->merge_head->remote_url != NULL &&
entry->merge_head->ref_name != NULL &&
git__strncmp(GIT_REFS_HEADS_DIR, entry->merge_head->ref_name, strlen(GIT_REFS_HEADS_DIR)) == 0)
{
struct merge_msg_entry *existing;
/* Match only branches from the same remote */
if (entries->length == 0)
return 1;
existing = git_vector_get(entries, 0);
return (git__strcmp(existing->merge_head->remote_url,
entry->merge_head->remote_url) == 0);
}
return 0;
}
static int msg_entry_is_oid(
const struct merge_msg_entry *merge_msg_entry)
{
return (merge_msg_entry->written == 0 &&
merge_msg_entry->merge_head->ref_name == NULL &&
merge_msg_entry->merge_head->remote_url == NULL);
}
static int merge_msg_entry_written(
const struct merge_msg_entry *merge_msg_entry)
{
return (merge_msg_entry->written == 1);
}
static int merge_msg_entries(
git_vector *v,
const struct merge_msg_entry *entries,
size_t len,
int (*match)(const struct merge_msg_entry *entry, git_vector *entries))
{
size_t i;
int matches, total = 0;
git_vector_clear(v);
for (i = 0; i < len; i++) {
if ((matches = match(&entries[i], v)) < 0)
return matches;
else if (!matches)
continue;
git_vector_insert(v, (struct merge_msg_entry *)&entries[i]);
total++;
}
return total;
}
static int merge_msg_write_entries(
git_filebuf *file,
git_vector *entries,
const char *item_name,
const char *item_plural_name,
size_t ref_name_skip,
const char *source,
char sep)
{
struct merge_msg_entry *entry;
size_t i;
int error = 0;
if (entries->length == 0)
return 0;
if (sep && (error = git_filebuf_printf(file, "%c ", sep)) < 0)
goto done;
if ((error = git_filebuf_printf(file, "%s ",
(entries->length == 1) ? item_name : item_plural_name)) < 0)
goto done;
git_vector_foreach(entries, i, entry) {
if (i > 0 &&
(error = git_filebuf_printf(file, "%s", (i == entries->length - 1) ? " and " : ", ")) < 0)
goto done;
if ((error = git_filebuf_printf(file, "'%s'", entry->merge_head->ref_name + ref_name_skip)) < 0)
goto done;
entry->written = 1;
}
if (source)
error = git_filebuf_printf(file, " of %s", source);
done:
return error;
}
static int merge_msg_write_branches(
git_filebuf *file,
git_vector *entries,
char sep)
{
return merge_msg_write_entries(file, entries,
"branch", "branches", strlen(GIT_REFS_HEADS_DIR), NULL, sep);
}
static int merge_msg_write_tracking(
git_filebuf *file,
git_vector *entries,
char sep)
{
return merge_msg_write_entries(file, entries,
"remote-tracking branch", "remote-tracking branches", 0, NULL, sep);
}
static int merge_msg_write_tags(
git_filebuf *file,
git_vector *entries,
char sep)
{
return merge_msg_write_entries(file, entries,
"tag", "tags", strlen(GIT_REFS_TAGS_DIR), NULL, sep);
}
static int merge_msg_write_remotes(
git_filebuf *file,
git_vector *entries,
char sep)
{
const char *source;
if (entries->length == 0)
return 0;
source = ((struct merge_msg_entry *)entries->contents[0])->merge_head->remote_url;
return merge_msg_write_entries(file, entries,
"branch", "branches", strlen(GIT_REFS_HEADS_DIR), source, sep);
}
static int write_merge_msg(
git_repository *repo,
const git_annotated_commit *heads[],
size_t heads_len)
{
git_filebuf file = GIT_FILEBUF_INIT;
git_buf file_path = GIT_BUF_INIT;
struct merge_msg_entry *entries;
git_vector matching = GIT_VECTOR_INIT;
size_t i;
char sep = 0;
int error = 0;
GIT_ASSERT_ARG(repo);
GIT_ASSERT_ARG(heads);
entries = git__calloc(heads_len, sizeof(struct merge_msg_entry));
GIT_ERROR_CHECK_ALLOC(entries);
if (git_vector_init(&matching, heads_len, NULL) < 0) {
git__free(entries);
return -1;
}
for (i = 0; i < heads_len; i++)
entries[i].merge_head = heads[i];
if ((error = git_buf_joinpath(&file_path, repo->gitdir, GIT_MERGE_MSG_FILE)) < 0 ||
(error = git_filebuf_open(&file, file_path.ptr, GIT_FILEBUF_CREATE_LEADING_DIRS, GIT_MERGE_FILE_MODE)) < 0 ||
(error = git_filebuf_write(&file, "Merge ", 6)) < 0)
goto cleanup;
/*
* This is to emulate the format of MERGE_MSG by core git.
*
* Core git will write all the commits specified by OID, in the order
* provided, until the first named branch or tag is reached, at which
* point all branches will be written in the order provided, then all
* tags, then all remote tracking branches and finally all commits that
* were specified by OID that were not already written.
*
* Yes. Really.
*/
for (i = 0; i < heads_len; i++) {
if (!msg_entry_is_oid(&entries[i]))
break;
if ((error = git_filebuf_printf(&file,
"%scommit '%s'", (i > 0) ? "; " : "",
entries[i].merge_head->id_str)) < 0)
goto cleanup;
entries[i].written = 1;
}
if (i)
sep = ';';
if ((error = merge_msg_entries(&matching, entries, heads_len, msg_entry_is_branch)) < 0 ||
(error = merge_msg_write_branches(&file, &matching, sep)) < 0)
goto cleanup;
if (matching.length)
sep =',';
if ((error = merge_msg_entries(&matching, entries, heads_len, msg_entry_is_tracking)) < 0 ||
(error = merge_msg_write_tracking(&file, &matching, sep)) < 0)
goto cleanup;
if (matching.length)
sep =',';
if ((error = merge_msg_entries(&matching, entries, heads_len, msg_entry_is_tag)) < 0 ||
(error = merge_msg_write_tags(&file, &matching, sep)) < 0)
goto cleanup;
if (matching.length)
sep =',';
/* We should never be called with multiple remote branches, but handle
* it in case we are... */
while ((error = merge_msg_entries(&matching, entries, heads_len, msg_entry_is_remote)) > 0) {
if ((error = merge_msg_write_remotes(&file, &matching, sep)) < 0)
goto cleanup;
if (matching.length)
sep =',';
}
if (error < 0)
goto cleanup;
for (i = 0; i < heads_len; i++) {
if (merge_msg_entry_written(&entries[i]))
continue;
if ((error = git_filebuf_printf(&file, "; commit '%s'",
entries[i].merge_head->id_str)) < 0)
goto cleanup;
}
if ((error = git_filebuf_printf(&file, "\n")) < 0 ||
(error = git_filebuf_commit(&file)) < 0)
goto cleanup;
cleanup:
if (error < 0)
git_filebuf_cleanup(&file);
git_buf_dispose(&file_path);
git_vector_free(&matching);
git__free(entries);
return error;
}
int git_merge__setup(
git_repository *repo,
const git_annotated_commit *our_head,
const git_annotated_commit *heads[],
size_t heads_len)
{
int error = 0;
GIT_ASSERT_ARG(repo);
GIT_ASSERT_ARG(our_head);
GIT_ASSERT_ARG(heads);
if ((error = git_repository__set_orig_head(repo, git_annotated_commit_id(our_head))) == 0 &&
(error = write_merge_head(repo, heads, heads_len)) == 0 &&
(error = write_merge_mode(repo)) == 0) {
error = write_merge_msg(repo, heads, heads_len);
}
return error;
}
/* Merge branches */
static int merge_ancestor_head(
git_annotated_commit **ancestor_head,
git_repository *repo,
const git_annotated_commit *our_head,
const git_annotated_commit **their_heads,
size_t their_heads_len)
{
git_oid *oids, ancestor_oid;
size_t i, alloc_len;
int error = 0;
GIT_ASSERT_ARG(repo);
GIT_ASSERT_ARG(our_head);
GIT_ASSERT_ARG(their_heads);
GIT_ERROR_CHECK_ALLOC_ADD(&alloc_len, their_heads_len, 1);
oids = git__calloc(alloc_len, sizeof(git_oid));
GIT_ERROR_CHECK_ALLOC(oids);
git_oid_cpy(&oids[0], git_commit_id(our_head->commit));
for (i = 0; i < their_heads_len; i++)
git_oid_cpy(&oids[i + 1], git_annotated_commit_id(their_heads[i]));
if ((error = git_merge_base_many(&ancestor_oid, repo, their_heads_len + 1, oids)) < 0)
goto on_error;
error = git_annotated_commit_lookup(ancestor_head, repo, &ancestor_oid);
on_error:
git__free(oids);
return error;
}
static const char *merge_their_label(const char *branchname)
{
const char *slash;
if ((slash = strrchr(branchname, '/')) == NULL)
return branchname;
if (*(slash+1) == '\0')
return "theirs";
return slash+1;
}
static int merge_normalize_checkout_opts(
git_checkout_options *out,
git_repository *repo,
const git_checkout_options *given_checkout_opts,
unsigned int checkout_strategy,
git_annotated_commit *ancestor,
const git_annotated_commit *our_head,
const git_annotated_commit **their_heads,
size_t their_heads_len)
{
git_checkout_options default_checkout_opts = GIT_CHECKOUT_OPTIONS_INIT;
int error = 0;
GIT_UNUSED(repo);
if (given_checkout_opts != NULL)
memcpy(out, given_checkout_opts, sizeof(git_checkout_options));
else
memcpy(out, &default_checkout_opts, sizeof(git_checkout_options));
out->checkout_strategy = checkout_strategy;
if (!out->ancestor_label) {
if (ancestor && ancestor->type == GIT_ANNOTATED_COMMIT_REAL)
out->ancestor_label = git_commit_summary(ancestor->commit);
else if (ancestor)
out->ancestor_label = "merged common ancestors";
else
out->ancestor_label = "empty base";
}
if (!out->our_label) {
if (our_head && our_head->ref_name)
out->our_label = our_head->ref_name;
else
out->our_label = "ours";
}
if (!out->their_label) {
if (their_heads_len == 1 && their_heads[0]->ref_name)
out->their_label = merge_their_label(their_heads[0]->ref_name);
else if (their_heads_len == 1)
out->their_label = their_heads[0]->id_str;
else
out->their_label = "theirs";
}
return error;
}
static int merge_check_index(size_t *conflicts, git_repository *repo, git_index *index_new, git_vector *merged_paths)
{
git_tree *head_tree = NULL;
git_index *index_repo = NULL;
git_iterator *iter_repo = NULL, *iter_new = NULL;
git_iterator_options iter_opts = GIT_ITERATOR_OPTIONS_INIT;
git_diff *staged_diff_list = NULL, *index_diff_list = NULL;
git_diff_delta *delta;
git_diff_options opts = GIT_DIFF_OPTIONS_INIT;
git_vector staged_paths = GIT_VECTOR_INIT;
size_t i;
int error = 0;
GIT_UNUSED(merged_paths);
*conflicts = 0;
/* No staged changes may exist unless the change staged is identical to
* the result of the merge. This allows one to apply to merge manually,
* then run merge. Any other staged change would be overwritten by
* a reset merge.
*/
if ((error = git_repository_head_tree(&head_tree, repo)) < 0 ||
(error = git_repository_index(&index_repo, repo)) < 0 ||
(error = git_diff_tree_to_index(&staged_diff_list, repo, head_tree, index_repo, &opts)) < 0)
goto done;
if (staged_diff_list->deltas.length == 0)
goto done;
git_vector_foreach(&staged_diff_list->deltas, i, delta) {
if ((error = git_vector_insert(&staged_paths, (char *)delta->new_file.path)) < 0)
goto done;
}
iter_opts.flags = GIT_ITERATOR_DONT_IGNORE_CASE;
iter_opts.pathlist.strings = (char **)staged_paths.contents;
iter_opts.pathlist.count = staged_paths.length;
if ((error = git_iterator_for_index(&iter_repo, repo, index_repo, &iter_opts)) < 0 ||
(error = git_iterator_for_index(&iter_new, repo, index_new, &iter_opts)) < 0 ||
(error = git_diff__from_iterators(&index_diff_list, repo, iter_repo, iter_new, &opts)) < 0)
goto done;
*conflicts = index_diff_list->deltas.length;
done:
git_tree_free(head_tree);
git_index_free(index_repo);
git_iterator_free(iter_repo);
git_iterator_free(iter_new);
git_diff_free(staged_diff_list);
git_diff_free(index_diff_list);
git_vector_free(&staged_paths);
return error;
}
static int merge_check_workdir(size_t *conflicts, git_repository *repo, git_index *index_new, git_vector *merged_paths)
{
git_diff *wd_diff_list = NULL;
git_diff_options opts = GIT_DIFF_OPTIONS_INIT;
int error = 0;
GIT_UNUSED(index_new);
*conflicts = 0;
/* We need to have merged at least 1 file for the possibility to exist to
* have conflicts with the workdir. Passing 0 as the pathspec count paramter
* will consider all files in the working directory, that is, we may detect
* a conflict if there were untracked files in the workdir prior to starting
* the merge. This typically happens when cherry-picking a commmit whose
* changes have already been applied.
*/
if (merged_paths->length == 0)
return 0;
opts.flags |= GIT_DIFF_INCLUDE_UNTRACKED;
/* Workdir changes may exist iff they do not conflict with changes that
* will be applied by the merge (including conflicts). Ensure that there
* are no changes in the workdir to these paths.
*/
opts.flags |= GIT_DIFF_DISABLE_PATHSPEC_MATCH;
opts.pathspec.count = merged_paths->length;
opts.pathspec.strings = (char **)merged_paths->contents;
opts.ignore_submodules = GIT_SUBMODULE_IGNORE_ALL;
if ((error = git_diff_index_to_workdir(&wd_diff_list, repo, NULL, &opts)) < 0)
goto done;
*conflicts = wd_diff_list->deltas.length;
done:
git_diff_free(wd_diff_list);
return error;
}
int git_merge__check_result(git_repository *repo, git_index *index_new)
{
git_tree *head_tree = NULL;
git_iterator *iter_head = NULL, *iter_new = NULL;
git_iterator_options iter_opts = GIT_ITERATOR_OPTIONS_INIT;
git_diff *merged_list = NULL;
git_diff_options opts = GIT_DIFF_OPTIONS_INIT;
git_diff_delta *delta;
git_vector paths = GIT_VECTOR_INIT;
size_t i, index_conflicts = 0, wd_conflicts = 0, conflicts;
const git_index_entry *e;
int error = 0;
iter_opts.flags = GIT_ITERATOR_DONT_IGNORE_CASE;
if ((error = git_repository_head_tree(&head_tree, repo)) < 0 ||
(error = git_iterator_for_tree(&iter_head, head_tree, &iter_opts)) < 0 ||
(error = git_iterator_for_index(&iter_new, repo, index_new, &iter_opts)) < 0 ||
(error = git_diff__from_iterators(&merged_list, repo, iter_head, iter_new, &opts)) < 0)
goto done;
git_vector_foreach(&merged_list->deltas, i, delta) {
if ((error = git_vector_insert(&paths, (char *)delta->new_file.path)) < 0)
goto done;
}
for (i = 0; i < git_index_entrycount(index_new); i++) {
e = git_index_get_byindex(index_new, i);
if (git_index_entry_is_conflict(e) &&
(git_vector_last(&paths) == NULL ||
strcmp(git_vector_last(&paths), e->path) != 0)) {
if ((error = git_vector_insert(&paths, (char *)e->path)) < 0)
goto done;
}
}
/* Make sure the index and workdir state do not prevent merging */
if ((error = merge_check_index(&index_conflicts, repo, index_new, &paths)) < 0 ||
(error = merge_check_workdir(&wd_conflicts, repo, index_new, &paths)) < 0)
goto done;
if ((conflicts = index_conflicts + wd_conflicts) > 0) {
git_error_set(GIT_ERROR_MERGE, "%" PRIuZ " uncommitted change%s would be overwritten by merge",
conflicts, (conflicts != 1) ? "s" : "");
error = GIT_ECONFLICT;
}
done:
git_vector_free(&paths);
git_tree_free(head_tree);
git_iterator_free(iter_head);
git_iterator_free(iter_new);
git_diff_free(merged_list);
return error;
}
int git_merge__append_conflicts_to_merge_msg(
git_repository *repo,
git_index *index)
{
git_filebuf file = GIT_FILEBUF_INIT;
git_buf file_path = GIT_BUF_INIT;
const char *last = NULL;
size_t i;
int error;
if (!git_index_has_conflicts(index))
return 0;
if ((error = git_buf_joinpath(&file_path, repo->gitdir, GIT_MERGE_MSG_FILE)) < 0 ||
(error = git_filebuf_open(&file, file_path.ptr, GIT_FILEBUF_APPEND, GIT_MERGE_FILE_MODE)) < 0)
goto cleanup;
git_filebuf_printf(&file, "\nConflicts:\n");
for (i = 0; i < git_index_entrycount(index); i++) {
const git_index_entry *e = git_index_get_byindex(index, i);
if (!git_index_entry_is_conflict(e))
continue;
if (last == NULL || strcmp(e->path, last) != 0)
git_filebuf_printf(&file, "\t%s\n", e->path);
last = e->path;
}
error = git_filebuf_commit(&file);
cleanup:
if (error < 0)
git_filebuf_cleanup(&file);
git_buf_dispose(&file_path);
return error;
}
static int merge_state_cleanup(git_repository *repo)
{
const char *state_files[] = {
GIT_MERGE_HEAD_FILE,
GIT_MERGE_MODE_FILE,
GIT_MERGE_MSG_FILE,
};
return git_repository__cleanup_files(repo, state_files, ARRAY_SIZE(state_files));
}
static int merge_heads(
git_annotated_commit **ancestor_head_out,
git_annotated_commit **our_head_out,
git_repository *repo,
git_reference *our_ref,
const git_annotated_commit **their_heads,
size_t their_heads_len)
{
git_annotated_commit *ancestor_head = NULL, *our_head = NULL;
int error = 0;
*ancestor_head_out = NULL;
*our_head_out = NULL;
if ((error = git_annotated_commit_from_ref(&our_head, repo, our_ref)) < 0)
goto done;
if ((error = merge_ancestor_head(&ancestor_head, repo, our_head, their_heads, their_heads_len)) < 0) {
if (error != GIT_ENOTFOUND)
goto done;
git_error_clear();
error = 0;
}
*ancestor_head_out = ancestor_head;
*our_head_out = our_head;
done:
if (error < 0) {
git_annotated_commit_free(ancestor_head);
git_annotated_commit_free(our_head);
}
return error;
}
static int merge_preference(git_merge_preference_t *out, git_repository *repo)
{
git_config *config;
const char *value;
int bool_value, error = 0;
*out = GIT_MERGE_PREFERENCE_NONE;
if ((error = git_repository_config_snapshot(&config, repo)) < 0)
goto done;
if ((error = git_config_get_string(&value, config, "merge.ff")) < 0) {
if (error == GIT_ENOTFOUND) {
git_error_clear();
error = 0;
}
goto done;
}
if (git_config_parse_bool(&bool_value, value) == 0) {
if (!bool_value)
*out |= GIT_MERGE_PREFERENCE_NO_FASTFORWARD;
} else {
if (strcasecmp(value, "only") == 0)
*out |= GIT_MERGE_PREFERENCE_FASTFORWARD_ONLY;
}
done:
git_config_free(config);
return error;
}
int git_merge_analysis_for_ref(
git_merge_analysis_t *analysis_out,
git_merge_preference_t *preference_out,
git_repository *repo,
git_reference *our_ref,
const git_annotated_commit **their_heads,
size_t their_heads_len)
{
git_annotated_commit *ancestor_head = NULL, *our_head = NULL;
int error = 0;
bool unborn;
GIT_ASSERT_ARG(analysis_out);
GIT_ASSERT_ARG(preference_out);
GIT_ASSERT_ARG(repo);
GIT_ASSERT_ARG(their_heads && their_heads_len > 0);
if (their_heads_len != 1) {
git_error_set(GIT_ERROR_MERGE, "can only merge a single branch");
error = -1;
goto done;
}
*analysis_out = GIT_MERGE_ANALYSIS_NONE;
if ((error = merge_preference(preference_out, repo)) < 0)
goto done;
if ((error = git_reference__is_unborn_head(&unborn, our_ref, repo)) < 0)
goto done;
if (unborn) {
*analysis_out |= GIT_MERGE_ANALYSIS_FASTFORWARD | GIT_MERGE_ANALYSIS_UNBORN;
error = 0;
goto done;
}
if ((error = merge_heads(&ancestor_head, &our_head, repo, our_ref, their_heads, their_heads_len)) < 0)
goto done;
/* We're up-to-date if we're trying to merge our own common ancestor. */
if (ancestor_head && git_oid_equal(
git_annotated_commit_id(ancestor_head), git_annotated_commit_id(their_heads[0])))
*analysis_out |= GIT_MERGE_ANALYSIS_UP_TO_DATE;
/* We're fastforwardable if we're our own common ancestor. */
else if (ancestor_head && git_oid_equal(
git_annotated_commit_id(ancestor_head), git_annotated_commit_id(our_head)))
*analysis_out |= GIT_MERGE_ANALYSIS_FASTFORWARD | GIT_MERGE_ANALYSIS_NORMAL;
/* Otherwise, just a normal merge is possible. */
else
*analysis_out |= GIT_MERGE_ANALYSIS_NORMAL;
done:
git_annotated_commit_free(ancestor_head);
git_annotated_commit_free(our_head);
return error;
}
int git_merge_analysis(
git_merge_analysis_t *analysis_out,
git_merge_preference_t *preference_out,
git_repository *repo,
const git_annotated_commit **their_heads,
size_t their_heads_len)
{
git_reference *head_ref = NULL;
int error = 0;
if ((error = git_reference_lookup(&head_ref, repo, GIT_HEAD_FILE)) < 0) {
git_error_set(GIT_ERROR_MERGE, "failed to lookup HEAD reference");
return error;
}
error = git_merge_analysis_for_ref(analysis_out, preference_out, repo, head_ref, their_heads, their_heads_len);
git_reference_free(head_ref);
return error;
}
int git_merge(
git_repository *repo,
const git_annotated_commit **their_heads,
size_t their_heads_len,
const git_merge_options *merge_opts,
const git_checkout_options *given_checkout_opts)
{
git_reference *our_ref = NULL;
git_checkout_options checkout_opts;
git_annotated_commit *our_head = NULL, *base = NULL;
git_index *repo_index = NULL, *index = NULL;
git_indexwriter indexwriter = GIT_INDEXWRITER_INIT;
unsigned int checkout_strategy;
int error = 0;
GIT_ASSERT_ARG(repo);
GIT_ASSERT_ARG(their_heads && their_heads_len > 0);
if (their_heads_len != 1) {
git_error_set(GIT_ERROR_MERGE, "can only merge a single branch");
return -1;
}
if ((error = git_repository__ensure_not_bare(repo, "merge")) < 0)
goto done;
checkout_strategy = given_checkout_opts ?
given_checkout_opts->checkout_strategy :
GIT_CHECKOUT_SAFE;
if ((error = git_indexwriter_init_for_operation(&indexwriter, repo,
&checkout_strategy)) < 0)
goto done;
if ((error = git_repository_index(&repo_index, repo) < 0) ||
(error = git_index_read(repo_index, 0) < 0))
goto done;
/* Write the merge setup files to the repository. */
if ((error = git_annotated_commit_from_head(&our_head, repo)) < 0 ||
(error = git_merge__setup(repo, our_head, their_heads,
their_heads_len)) < 0)
goto done;
/* TODO: octopus */
if ((error = merge_annotated_commits(&index, &base, repo, our_head,
(git_annotated_commit *)their_heads[0], 0, merge_opts)) < 0 ||
(error = git_merge__check_result(repo, index)) < 0 ||
(error = git_merge__append_conflicts_to_merge_msg(repo, index)) < 0)
goto done;
/* check out the merge results */
if ((error = merge_normalize_checkout_opts(&checkout_opts, repo,
given_checkout_opts, checkout_strategy,
base, our_head, their_heads, their_heads_len)) < 0 ||
(error = git_checkout_index(repo, index, &checkout_opts)) < 0)
goto done;
error = git_indexwriter_commit(&indexwriter);
done:
if (error < 0)
merge_state_cleanup(repo);
git_indexwriter_cleanup(&indexwriter);
git_index_free(index);
git_annotated_commit_free(our_head);
git_annotated_commit_free(base);
git_reference_free(our_ref);
git_index_free(repo_index);
return error;
}
int git_merge_options_init(git_merge_options *opts, unsigned int version)
{
GIT_INIT_STRUCTURE_FROM_TEMPLATE(
opts, version, git_merge_options, GIT_MERGE_OPTIONS_INIT);
return 0;
}
#ifndef GIT_DEPRECATE_HARD
int git_merge_init_options(git_merge_options *opts, unsigned int version)
{
return git_merge_options_init(opts, version);
}
#endif
int git_merge_file_input_init(git_merge_file_input *input, unsigned int version)
{
GIT_INIT_STRUCTURE_FROM_TEMPLATE(
input, version, git_merge_file_input, GIT_MERGE_FILE_INPUT_INIT);
return 0;
}
#ifndef GIT_DEPRECATE_HARD
int git_merge_file_init_input(git_merge_file_input *input, unsigned int version)
{
return git_merge_file_input_init(input, version);
}
#endif
int git_merge_file_options_init(
git_merge_file_options *opts, unsigned int version)
{
GIT_INIT_STRUCTURE_FROM_TEMPLATE(
opts, version, git_merge_file_options, GIT_MERGE_FILE_OPTIONS_INIT);
return 0;
}
#ifndef GIT_DEPRECATE_HARD
int git_merge_file_init_options(
git_merge_file_options *opts, unsigned int version)
{
return git_merge_file_options_init(opts, version);
}
#endif
|
0 |
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2
|
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2/src/array.h
|
/*
* Copyright (C) the libgit2 contributors. All rights reserved.
*
* This file is part of libgit2, distributed under the GNU GPL v2 with
* a Linking Exception. For full terms see the included COPYING file.
*/
#ifndef INCLUDE_array_h__
#define INCLUDE_array_h__
#include "common.h"
/*
* Use this to declare a typesafe resizable array of items, a la:
*
* git_array_t(int) my_ints = GIT_ARRAY_INIT;
* ...
* int *i = git_array_alloc(my_ints);
* GIT_ERROR_CHECK_ALLOC(i);
* ...
* git_array_clear(my_ints);
*
* You may also want to do things like:
*
* typedef git_array_t(my_struct) my_struct_array_t;
*/
#define git_array_t(type) struct { type *ptr; size_t size, asize; }
#define GIT_ARRAY_INIT { NULL, 0, 0 }
#define git_array_init(a) \
do { (a).size = (a).asize = 0; (a).ptr = NULL; } while (0)
#define git_array_init_to_size(a, desired) \
do { (a).size = 0; (a).asize = desired; (a).ptr = git__calloc(desired, sizeof(*(a).ptr)); } while (0)
#define git_array_clear(a) \
do { git__free((a).ptr); git_array_init(a); } while (0)
#define GIT_ERROR_CHECK_ARRAY(a) GIT_ERROR_CHECK_ALLOC((a).ptr)
typedef git_array_t(char) git_array_generic_t;
/* use a generic array for growth, return 0 on success */
GIT_INLINE(int) git_array_grow(void *_a, size_t item_size)
{
volatile git_array_generic_t *a = _a;
size_t new_size;
char *new_array;
if (a->size < 8) {
new_size = 8;
} else {
if (GIT_MULTIPLY_SIZET_OVERFLOW(&new_size, a->size, 3))
goto on_oom;
new_size /= 2;
}
if ((new_array = git__reallocarray(a->ptr, new_size, item_size)) == NULL)
goto on_oom;
a->ptr = new_array;
a->asize = new_size;
return 0;
on_oom:
git_array_clear(*a);
return -1;
}
#define git_array_alloc(a) \
(((a).size < (a).asize || git_array_grow(&(a), sizeof(*(a).ptr)) == 0) ? \
&(a).ptr[(a).size++] : (void *)NULL)
#define git_array_last(a) ((a).size ? &(a).ptr[(a).size - 1] : (void *)NULL)
#define git_array_pop(a) ((a).size ? &(a).ptr[--(a).size] : (void *)NULL)
#define git_array_get(a, i) (((i) < (a).size) ? &(a).ptr[(i)] : (void *)NULL)
#define git_array_size(a) (a).size
#define git_array_valid_index(a, i) ((i) < (a).size)
#define git_array_foreach(a, i, element) \
for ((i) = 0; (i) < (a).size && ((element) = &(a).ptr[(i)]); (i)++)
GIT_INLINE(int) git_array__search(
size_t *out,
void *array_ptr,
size_t item_size,
size_t array_len,
int (*compare)(const void *, const void *),
const void *key)
{
size_t lim;
unsigned char *part, *array = array_ptr, *base = array_ptr;
int cmp = -1;
for (lim = array_len; lim != 0; lim >>= 1) {
part = base + (lim >> 1) * item_size;
cmp = (*compare)(key, part);
if (cmp == 0) {
base = part;
break;
}
if (cmp > 0) { /* key > p; take right partition */
base = part + 1 * item_size;
lim--;
} /* else take left partition */
}
if (out)
*out = (base - array) / item_size;
return (cmp == 0) ? 0 : GIT_ENOTFOUND;
}
#define git_array_search(out, a, cmp, key) \
git_array__search(out, (a).ptr, sizeof(*(a).ptr), (a).size, \
(cmp), (key))
#endif
|
0 |
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2
|
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2/src/clone.c
|
/*
* Copyright (C) the libgit2 contributors. All rights reserved.
*
* This file is part of libgit2, distributed under the GNU GPL v2 with
* a Linking Exception. For full terms see the included COPYING file.
*/
#include "clone.h"
#include "git2/clone.h"
#include "git2/remote.h"
#include "git2/revparse.h"
#include "git2/branch.h"
#include "git2/config.h"
#include "git2/checkout.h"
#include "git2/commit.h"
#include "git2/tree.h"
#include "remote.h"
#include "futils.h"
#include "refs.h"
#include "path.h"
#include "repository.h"
#include "odb.h"
static int clone_local_into(git_repository *repo, git_remote *remote, const git_fetch_options *fetch_opts, const git_checkout_options *co_opts, const char *branch, int link);
static int create_branch(
git_reference **branch,
git_repository *repo,
const git_oid *target,
const char *name,
const char *log_message)
{
git_commit *head_obj = NULL;
git_reference *branch_ref = NULL;
git_buf refname = GIT_BUF_INIT;
int error;
/* Find the target commit */
if ((error = git_commit_lookup(&head_obj, repo, target)) < 0)
return error;
/* Create the new branch */
if ((error = git_buf_printf(&refname, GIT_REFS_HEADS_DIR "%s", name)) < 0)
return error;
error = git_reference_create(&branch_ref, repo, git_buf_cstr(&refname), target, 0, log_message);
git_buf_dispose(&refname);
git_commit_free(head_obj);
if (!error)
*branch = branch_ref;
else
git_reference_free(branch_ref);
return error;
}
static int setup_tracking_config(
git_repository *repo,
const char *branch_name,
const char *remote_name,
const char *merge_target)
{
git_config *cfg;
git_buf remote_key = GIT_BUF_INIT, merge_key = GIT_BUF_INIT;
int error = -1;
if (git_repository_config__weakptr(&cfg, repo) < 0)
return -1;
if (git_buf_printf(&remote_key, "branch.%s.remote", branch_name) < 0)
goto cleanup;
if (git_buf_printf(&merge_key, "branch.%s.merge", branch_name) < 0)
goto cleanup;
if (git_config_set_string(cfg, git_buf_cstr(&remote_key), remote_name) < 0)
goto cleanup;
if (git_config_set_string(cfg, git_buf_cstr(&merge_key), merge_target) < 0)
goto cleanup;
error = 0;
cleanup:
git_buf_dispose(&remote_key);
git_buf_dispose(&merge_key);
return error;
}
static int create_tracking_branch(
git_reference **branch,
git_repository *repo,
const git_oid *target,
const char *branch_name,
const char *log_message)
{
int error;
if ((error = create_branch(branch, repo, target, branch_name, log_message)) < 0)
return error;
return setup_tracking_config(
repo,
branch_name,
GIT_REMOTE_ORIGIN,
git_reference_name(*branch));
}
static int update_head_to_new_branch(
git_repository *repo,
const git_oid *target,
const char *name,
const char *reflog_message)
{
git_reference *tracking_branch = NULL;
int error;
if (!git__prefixcmp(name, GIT_REFS_HEADS_DIR))
name += strlen(GIT_REFS_HEADS_DIR);
error = create_tracking_branch(&tracking_branch, repo, target, name,
reflog_message);
if (!error)
error = git_repository_set_head(
repo, git_reference_name(tracking_branch));
git_reference_free(tracking_branch);
/* if it already existed, then the user's refspec created it for us, ignore it' */
if (error == GIT_EEXISTS)
error = 0;
return error;
}
static int update_head_to_default(git_repository *repo)
{
git_buf initialbranch = GIT_BUF_INIT;
const char *branch_name;
int error = 0;
if ((error = git_repository_initialbranch(&initialbranch, repo)) < 0)
goto done;
if (git__prefixcmp(initialbranch.ptr, GIT_REFS_HEADS_DIR) != 0) {
git_error_set(GIT_ERROR_INVALID, "invalid initial branch '%s'", initialbranch.ptr);
error = -1;
goto done;
}
branch_name = initialbranch.ptr + strlen(GIT_REFS_HEADS_DIR);
error = setup_tracking_config(repo, branch_name, GIT_REMOTE_ORIGIN,
initialbranch.ptr);
done:
git_buf_dispose(&initialbranch);
return error;
}
static int update_remote_head(
git_repository *repo,
git_remote *remote,
git_buf *target,
const char *reflog_message)
{
git_refspec *refspec;
git_reference *remote_head = NULL;
git_buf remote_head_name = GIT_BUF_INIT;
git_buf remote_branch_name = GIT_BUF_INIT;
int error;
/* Determine the remote tracking ref name from the local branch */
refspec = git_remote__matching_refspec(remote, git_buf_cstr(target));
if (refspec == NULL) {
git_error_set(GIT_ERROR_NET, "the remote's default branch does not fit the refspec configuration");
error = GIT_EINVALIDSPEC;
goto cleanup;
}
if ((error = git_refspec_transform(
&remote_branch_name,
refspec,
git_buf_cstr(target))) < 0)
goto cleanup;
if ((error = git_buf_printf(&remote_head_name,
"%s%s/%s",
GIT_REFS_REMOTES_DIR,
git_remote_name(remote),
GIT_HEAD_FILE)) < 0)
goto cleanup;
error = git_reference_symbolic_create(
&remote_head,
repo,
git_buf_cstr(&remote_head_name),
git_buf_cstr(&remote_branch_name),
true,
reflog_message);
cleanup:
git_reference_free(remote_head);
git_buf_dispose(&remote_branch_name);
git_buf_dispose(&remote_head_name);
return error;
}
static int update_head_to_remote(
git_repository *repo,
git_remote *remote,
const char *reflog_message)
{
int error = 0;
size_t refs_len;
const git_remote_head *remote_head, **refs;
const git_oid *remote_head_id;
git_buf branch = GIT_BUF_INIT;
if ((error = git_remote_ls(&refs, &refs_len, remote)) < 0)
return error;
/* We cloned an empty repository or one with an unborn HEAD */
if (refs_len == 0 || strcmp(refs[0]->name, GIT_HEAD_FILE))
return update_head_to_default(repo);
/* We know we have HEAD, let's see where it points */
remote_head = refs[0];
GIT_ASSERT(remote_head);
remote_head_id = &remote_head->oid;
error = git_remote_default_branch(&branch, remote);
if (error == GIT_ENOTFOUND) {
error = git_repository_set_head_detached(
repo, remote_head_id);
goto cleanup;
}
if ((error = update_remote_head(repo, remote, &branch, reflog_message)) < 0)
goto cleanup;
error = update_head_to_new_branch(
repo,
remote_head_id,
git_buf_cstr(&branch),
reflog_message);
cleanup:
git_buf_dispose(&branch);
return error;
}
static int update_head_to_branch(
git_repository *repo,
git_remote *remote,
const char *branch,
const char *reflog_message)
{
int retcode;
git_buf remote_branch_name = GIT_BUF_INIT;
git_reference *remote_ref = NULL;
git_buf default_branch = GIT_BUF_INIT;
GIT_ASSERT_ARG(remote);
GIT_ASSERT_ARG(branch);
if ((retcode = git_buf_printf(&remote_branch_name, GIT_REFS_REMOTES_DIR "%s/%s",
git_remote_name(remote), branch)) < 0 )
goto cleanup;
if ((retcode = git_reference_lookup(&remote_ref, repo, git_buf_cstr(&remote_branch_name))) < 0)
goto cleanup;
if ((retcode = update_head_to_new_branch(repo, git_reference_target(remote_ref), branch,
reflog_message)) < 0)
goto cleanup;
if ((retcode = git_remote_default_branch(&default_branch, remote)) < 0)
goto cleanup;
if (!git_remote__matching_refspec(remote, git_buf_cstr(&default_branch)))
goto cleanup;
retcode = update_remote_head(repo, remote, &default_branch, reflog_message);
cleanup:
git_reference_free(remote_ref);
git_buf_dispose(&remote_branch_name);
git_buf_dispose(&default_branch);
return retcode;
}
static int default_repository_create(git_repository **out, const char *path, int bare, void *payload)
{
GIT_UNUSED(payload);
return git_repository_init(out, path, bare);
}
static int default_remote_create(
git_remote **out,
git_repository *repo,
const char *name,
const char *url,
void *payload)
{
GIT_UNUSED(payload);
return git_remote_create(out, repo, name, url);
}
/*
* submodules?
*/
static int create_and_configure_origin(
git_remote **out,
git_repository *repo,
const char *url,
const git_clone_options *options)
{
int error;
git_remote *origin = NULL;
char buf[GIT_PATH_MAX];
git_remote_create_cb remote_create = options->remote_cb;
void *payload = options->remote_cb_payload;
/* If the path exists and is a dir, the url should be the absolute path */
if (git_path_root(url) < 0 && git_path_exists(url) && git_path_isdir(url)) {
if (p_realpath(url, buf) == NULL)
return -1;
url = buf;
}
if (!remote_create) {
remote_create = default_remote_create;
payload = NULL;
}
if ((error = remote_create(&origin, repo, "origin", url, payload)) < 0)
goto on_error;
*out = origin;
return 0;
on_error:
git_remote_free(origin);
return error;
}
static bool should_checkout(
git_repository *repo,
bool is_bare,
const git_checkout_options *opts)
{
if (is_bare)
return false;
if (!opts)
return false;
if (opts->checkout_strategy == GIT_CHECKOUT_NONE)
return false;
return !git_repository_head_unborn(repo);
}
static int checkout_branch(git_repository *repo, git_remote *remote, const git_checkout_options *co_opts, const char *branch, const char *reflog_message)
{
int error;
if (branch)
error = update_head_to_branch(repo, remote, branch, reflog_message);
/* Point HEAD to the same ref as the remote's head */
else
error = update_head_to_remote(repo, remote, reflog_message);
if (!error && should_checkout(repo, git_repository_is_bare(repo), co_opts))
error = git_checkout_head(repo, co_opts);
return error;
}
static int clone_into(git_repository *repo, git_remote *_remote, const git_fetch_options *opts, const git_checkout_options *co_opts, const char *branch)
{
int error;
git_buf reflog_message = GIT_BUF_INIT;
git_fetch_options fetch_opts;
git_remote *remote;
GIT_ASSERT_ARG(repo);
GIT_ASSERT_ARG(_remote);
if (!git_repository_is_empty(repo)) {
git_error_set(GIT_ERROR_INVALID, "the repository is not empty");
return -1;
}
if ((error = git_remote_dup(&remote, _remote)) < 0)
return error;
memcpy(&fetch_opts, opts, sizeof(git_fetch_options));
fetch_opts.update_fetchhead = 0;
fetch_opts.download_tags = GIT_REMOTE_DOWNLOAD_TAGS_ALL;
git_buf_printf(&reflog_message, "clone: from %s", git_remote_url(remote));
if ((error = git_remote_fetch(remote, NULL, &fetch_opts, git_buf_cstr(&reflog_message))) != 0)
goto cleanup;
error = checkout_branch(repo, remote, co_opts, branch, git_buf_cstr(&reflog_message));
cleanup:
git_remote_free(remote);
git_buf_dispose(&reflog_message);
return error;
}
int git_clone__should_clone_local(const char *url_or_path, git_clone_local_t local)
{
git_buf fromurl = GIT_BUF_INIT;
const char *path = url_or_path;
bool is_url, is_local;
if (local == GIT_CLONE_NO_LOCAL)
return 0;
if ((is_url = git_path_is_local_file_url(url_or_path)) != 0) {
if (git_path_fromurl(&fromurl, url_or_path) < 0) {
is_local = -1;
goto done;
}
path = fromurl.ptr;
}
is_local = (!is_url || local != GIT_CLONE_LOCAL_AUTO) &&
git_path_isdir(path);
done:
git_buf_dispose(&fromurl);
return is_local;
}
static int git__clone(
git_repository **out,
const char *url,
const char *local_path,
const git_clone_options *_options,
int use_existing)
{
int error = 0;
git_repository *repo = NULL;
git_remote *origin;
git_clone_options options = GIT_CLONE_OPTIONS_INIT;
uint32_t rmdir_flags = GIT_RMDIR_REMOVE_FILES;
git_repository_create_cb repository_cb;
GIT_ASSERT_ARG(out);
GIT_ASSERT_ARG(url);
GIT_ASSERT_ARG(local_path);
if (_options)
memcpy(&options, _options, sizeof(git_clone_options));
GIT_ERROR_CHECK_VERSION(&options, GIT_CLONE_OPTIONS_VERSION, "git_clone_options");
/* Only clone to a new directory or an empty directory */
if (git_path_exists(local_path) && !use_existing && !git_path_is_empty_dir(local_path)) {
git_error_set(GIT_ERROR_INVALID,
"'%s' exists and is not an empty directory", local_path);
return GIT_EEXISTS;
}
/* Only remove the root directory on failure if we create it */
if (git_path_exists(local_path))
rmdir_flags |= GIT_RMDIR_SKIP_ROOT;
if (options.repository_cb)
repository_cb = options.repository_cb;
else
repository_cb = default_repository_create;
if ((error = repository_cb(&repo, local_path, options.bare, options.repository_cb_payload)) < 0)
return error;
if (!(error = create_and_configure_origin(&origin, repo, url, &options))) {
int clone_local = git_clone__should_clone_local(url, options.local);
int link = options.local != GIT_CLONE_LOCAL_NO_LINKS;
if (clone_local == 1)
error = clone_local_into(
repo, origin, &options.fetch_opts, &options.checkout_opts,
options.checkout_branch, link);
else if (clone_local == 0)
error = clone_into(
repo, origin, &options.fetch_opts, &options.checkout_opts,
options.checkout_branch);
else
error = -1;
git_remote_free(origin);
}
if (error != 0) {
git_error_state last_error = {0};
git_error_state_capture(&last_error, error);
git_repository_free(repo);
repo = NULL;
(void)git_futils_rmdir_r(local_path, NULL, rmdir_flags);
git_error_state_restore(&last_error);
}
*out = repo;
return error;
}
int git_clone(
git_repository **out,
const char *url,
const char *local_path,
const git_clone_options *_options)
{
return git__clone(out, url, local_path, _options, 0);
}
int git_clone__submodule(
git_repository **out,
const char *url,
const char *local_path,
const git_clone_options *_options)
{
return git__clone(out, url, local_path, _options, 1);
}
int git_clone_options_init(git_clone_options *opts, unsigned int version)
{
GIT_INIT_STRUCTURE_FROM_TEMPLATE(
opts, version, git_clone_options, GIT_CLONE_OPTIONS_INIT);
return 0;
}
#ifndef GIT_DEPRECATE_HARD
int git_clone_init_options(git_clone_options *opts, unsigned int version)
{
return git_clone_options_init(opts, version);
}
#endif
static bool can_link(const char *src, const char *dst, int link)
{
#ifdef GIT_WIN32
GIT_UNUSED(src);
GIT_UNUSED(dst);
GIT_UNUSED(link);
return false;
#else
struct stat st_src, st_dst;
if (!link)
return false;
if (p_stat(src, &st_src) < 0)
return false;
if (p_stat(dst, &st_dst) < 0)
return false;
return st_src.st_dev == st_dst.st_dev;
#endif
}
static int clone_local_into(git_repository *repo, git_remote *remote, const git_fetch_options *fetch_opts, const git_checkout_options *co_opts, const char *branch, int link)
{
int error, flags;
git_repository *src;
git_buf src_odb = GIT_BUF_INIT, dst_odb = GIT_BUF_INIT, src_path = GIT_BUF_INIT;
git_buf reflog_message = GIT_BUF_INIT;
GIT_ASSERT_ARG(repo);
GIT_ASSERT_ARG(remote);
if (!git_repository_is_empty(repo)) {
git_error_set(GIT_ERROR_INVALID, "the repository is not empty");
return -1;
}
/*
* Let's figure out what path we should use for the source
* repo, if it's not rooted, the path should be relative to
* the repository's worktree/gitdir.
*/
if ((error = git_path_from_url_or_path(&src_path, git_remote_url(remote))) < 0)
return error;
/* Copy .git/objects/ from the source to the target */
if ((error = git_repository_open(&src, git_buf_cstr(&src_path))) < 0) {
git_buf_dispose(&src_path);
return error;
}
if (git_repository_item_path(&src_odb, src, GIT_REPOSITORY_ITEM_OBJECTS) < 0
|| git_repository_item_path(&dst_odb, repo, GIT_REPOSITORY_ITEM_OBJECTS) < 0) {
error = -1;
goto cleanup;
}
flags = 0;
if (can_link(git_repository_path(src), git_repository_path(repo), link))
flags |= GIT_CPDIR_LINK_FILES;
error = git_futils_cp_r(git_buf_cstr(&src_odb), git_buf_cstr(&dst_odb),
flags, GIT_OBJECT_DIR_MODE);
/*
* can_link() doesn't catch all variations, so if we hit an
* error and did want to link, let's try again without trying
* to link.
*/
if (error < 0 && link) {
flags &= ~GIT_CPDIR_LINK_FILES;
error = git_futils_cp_r(git_buf_cstr(&src_odb), git_buf_cstr(&dst_odb),
flags, GIT_OBJECT_DIR_MODE);
}
if (error < 0)
goto cleanup;
git_buf_printf(&reflog_message, "clone: from %s", git_remote_url(remote));
if ((error = git_remote_fetch(remote, NULL, fetch_opts, git_buf_cstr(&reflog_message))) != 0)
goto cleanup;
error = checkout_branch(repo, remote, co_opts, branch, git_buf_cstr(&reflog_message));
cleanup:
git_buf_dispose(&reflog_message);
git_buf_dispose(&src_path);
git_buf_dispose(&src_odb);
git_buf_dispose(&dst_odb);
git_repository_free(src);
return error;
}
|
0 |
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2
|
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2/src/tag.h
|
/*
* Copyright (C) the libgit2 contributors. All rights reserved.
*
* This file is part of libgit2, distributed under the GNU GPL v2 with
* a Linking Exception. For full terms see the included COPYING file.
*/
#ifndef INCLUDE_tag_h__
#define INCLUDE_tag_h__
#include "common.h"
#include "git2/tag.h"
#include "repository.h"
#include "odb.h"
struct git_tag {
git_object object;
git_oid target;
git_object_t type;
char *tag_name;
git_signature *tagger;
char *message;
};
void git_tag__free(void *tag);
int git_tag__parse(void *tag, git_odb_object *obj);
int git_tag__parse_raw(void *tag, const char *data, size_t size);
#endif
|
0 |
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2
|
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2/src/pack.c
|
/*
* Copyright (C) the libgit2 contributors. All rights reserved.
*
* This file is part of libgit2, distributed under the GNU GPL v2 with
* a Linking Exception. For full terms see the included COPYING file.
*/
#include "pack.h"
#include "delta.h"
#include "futils.h"
#include "mwindow.h"
#include "odb.h"
#include "oid.h"
#include "oidarray.h"
/* Option to bypass checking existence of '.keep' files */
bool git_disable_pack_keep_file_checks = false;
static int packfile_open_locked(struct git_pack_file *p);
static off64_t nth_packed_object_offset_locked(struct git_pack_file *p, uint32_t n);
static int packfile_unpack_compressed(
git_rawobj *obj,
struct git_pack_file *p,
git_mwindow **w_curs,
off64_t *curpos,
size_t size,
git_object_t type);
/* Can find the offset of an object given
* a prefix of an identifier.
* Throws GIT_EAMBIGUOUSOIDPREFIX if short oid
* is ambiguous within the pack.
* This method assumes that len is between
* GIT_OID_MINPREFIXLEN and GIT_OID_HEXSZ.
*/
static int pack_entry_find_offset(
off64_t *offset_out,
git_oid *found_oid,
struct git_pack_file *p,
const git_oid *short_oid,
size_t len);
static int packfile_error(const char *message)
{
git_error_set(GIT_ERROR_ODB, "invalid pack file - %s", message);
return -1;
}
/********************
* Delta base cache
********************/
static git_pack_cache_entry *new_cache_object(git_rawobj *source)
{
git_pack_cache_entry *e = git__calloc(1, sizeof(git_pack_cache_entry));
if (!e)
return NULL;
git_atomic32_inc(&e->refcount);
memcpy(&e->raw, source, sizeof(git_rawobj));
return e;
}
static void free_cache_object(void *o)
{
git_pack_cache_entry *e = (git_pack_cache_entry *)o;
if (e != NULL) {
git__free(e->raw.data);
git__free(e);
}
}
static void cache_free(git_pack_cache *cache)
{
git_pack_cache_entry *entry;
if (cache->entries) {
git_offmap_foreach_value(cache->entries, entry, {
free_cache_object(entry);
});
git_offmap_free(cache->entries);
cache->entries = NULL;
}
}
static int cache_init(git_pack_cache *cache)
{
if (git_offmap_new(&cache->entries) < 0)
return -1;
cache->memory_limit = GIT_PACK_CACHE_MEMORY_LIMIT;
if (git_mutex_init(&cache->lock)) {
git_error_set(GIT_ERROR_OS, "failed to initialize pack cache mutex");
git__free(cache->entries);
cache->entries = NULL;
return -1;
}
return 0;
}
static git_pack_cache_entry *cache_get(git_pack_cache *cache, off64_t offset)
{
git_pack_cache_entry *entry;
if (git_mutex_lock(&cache->lock) < 0)
return NULL;
if ((entry = git_offmap_get(cache->entries, offset)) != NULL) {
git_atomic32_inc(&entry->refcount);
entry->last_usage = cache->use_ctr++;
}
git_mutex_unlock(&cache->lock);
return entry;
}
/* Run with the cache lock held */
static void free_lowest_entry(git_pack_cache *cache)
{
off64_t offset;
git_pack_cache_entry *entry;
git_offmap_foreach(cache->entries, offset, entry, {
if (entry && git_atomic32_get(&entry->refcount) == 0) {
cache->memory_used -= entry->raw.len;
git_offmap_delete(cache->entries, offset);
free_cache_object(entry);
}
});
}
static int cache_add(
git_pack_cache_entry **cached_out,
git_pack_cache *cache,
git_rawobj *base,
off64_t offset)
{
git_pack_cache_entry *entry;
int exists;
if (base->len > GIT_PACK_CACHE_SIZE_LIMIT)
return -1;
entry = new_cache_object(base);
if (entry) {
if (git_mutex_lock(&cache->lock) < 0) {
git_error_set(GIT_ERROR_OS, "failed to lock cache");
git__free(entry);
return -1;
}
/* Add it to the cache if nobody else has */
exists = git_offmap_exists(cache->entries, offset);
if (!exists) {
while (cache->memory_used + base->len > cache->memory_limit)
free_lowest_entry(cache);
git_offmap_set(cache->entries, offset, entry);
cache->memory_used += entry->raw.len;
*cached_out = entry;
}
git_mutex_unlock(&cache->lock);
/* Somebody beat us to adding it into the cache */
if (exists) {
git__free(entry);
return -1;
}
}
return 0;
}
/***********************************************************
*
* PACK INDEX METHODS
*
***********************************************************/
static void pack_index_free(struct git_pack_file *p)
{
if (p->oids) {
git__free(p->oids);
p->oids = NULL;
}
if (p->index_map.data) {
git_futils_mmap_free(&p->index_map);
p->index_map.data = NULL;
}
}
/* Run with the packfile lock held */
static int pack_index_check_locked(const char *path, struct git_pack_file *p)
{
struct git_pack_idx_header *hdr;
uint32_t version, nr, i, *index;
void *idx_map;
size_t idx_size;
struct stat st;
int error;
/* TODO: properly open the file without access time using O_NOATIME */
git_file fd = git_futils_open_ro(path);
if (fd < 0)
return fd;
if (p_fstat(fd, &st) < 0) {
p_close(fd);
git_error_set(GIT_ERROR_OS, "unable to stat pack index '%s'", path);
return -1;
}
if (!S_ISREG(st.st_mode) ||
!git__is_sizet(st.st_size) ||
(idx_size = (size_t)st.st_size) < 4 * 256 + 20 + 20)
{
p_close(fd);
git_error_set(GIT_ERROR_ODB, "invalid pack index '%s'", path);
return -1;
}
error = git_futils_mmap_ro(&p->index_map, fd, 0, idx_size);
p_close(fd);
if (error < 0)
return error;
hdr = idx_map = p->index_map.data;
if (hdr->idx_signature == htonl(PACK_IDX_SIGNATURE)) {
version = ntohl(hdr->idx_version);
if (version < 2 || version > 2) {
git_futils_mmap_free(&p->index_map);
return packfile_error("unsupported index version");
}
} else
version = 1;
nr = 0;
index = idx_map;
if (version > 1)
index += 2; /* skip index header */
for (i = 0; i < 256; i++) {
uint32_t n = ntohl(index[i]);
if (n < nr) {
git_futils_mmap_free(&p->index_map);
return packfile_error("index is non-monotonic");
}
nr = n;
}
if (version == 1) {
/*
* Total size:
* - 256 index entries 4 bytes each
* - 24-byte entries * nr (20-byte sha1 + 4-byte offset)
* - 20-byte SHA1 of the packfile
* - 20-byte SHA1 file checksum
*/
if (idx_size != 4*256 + nr * 24 + 20 + 20) {
git_futils_mmap_free(&p->index_map);
return packfile_error("index is corrupted");
}
} else if (version == 2) {
/*
* Minimum size:
* - 8 bytes of header
* - 256 index entries 4 bytes each
* - 20-byte sha1 entry * nr
* - 4-byte crc entry * nr
* - 4-byte offset entry * nr
* - 20-byte SHA1 of the packfile
* - 20-byte SHA1 file checksum
* And after the 4-byte offset table might be a
* variable sized table containing 8-byte entries
* for offsets larger than 2^31.
*/
unsigned long min_size = 8 + 4*256 + nr*(20 + 4 + 4) + 20 + 20;
unsigned long max_size = min_size;
if (nr)
max_size += (nr - 1)*8;
if (idx_size < min_size || idx_size > max_size) {
git_futils_mmap_free(&p->index_map);
return packfile_error("wrong index size");
}
}
p->num_objects = nr;
p->index_version = version;
return 0;
}
/* Run with the packfile lock held */
static int pack_index_open_locked(struct git_pack_file *p)
{
int error = 0;
size_t name_len;
git_buf idx_name = GIT_BUF_INIT;
if (p->index_version > -1)
goto cleanup;
/* checked by git_pack_file alloc */
name_len = strlen(p->pack_name);
GIT_ASSERT(name_len > strlen(".pack"));
if ((error = git_buf_init(&idx_name, name_len)) < 0)
goto cleanup;
git_buf_put(&idx_name, p->pack_name, name_len - strlen(".pack"));
git_buf_puts(&idx_name, ".idx");
if (git_buf_oom(&idx_name)) {
error = -1;
goto cleanup;
}
if (p->index_version == -1)
error = pack_index_check_locked(idx_name.ptr, p);
cleanup:
git_buf_dispose(&idx_name);
return error;
}
static unsigned char *pack_window_open(
struct git_pack_file *p,
git_mwindow **w_cursor,
off64_t offset,
unsigned int *left)
{
unsigned char *pack_data = NULL;
if (git_mutex_lock(&p->lock) < 0) {
git_error_set(GIT_ERROR_THREAD, "unable to lock packfile");
return NULL;
}
if (git_mutex_lock(&p->mwf.lock) < 0) {
git_mutex_unlock(&p->lock);
git_error_set(GIT_ERROR_THREAD, "unable to lock packfile");
return NULL;
}
if (p->mwf.fd == -1 && packfile_open_locked(p) < 0)
goto cleanup;
/* Since packfiles end in a hash of their content and it's
* pointless to ask for an offset into the middle of that
* hash, and the pack_window_contains function above wouldn't match
* don't allow an offset too close to the end of the file.
*
* Don't allow a negative offset, as that means we've wrapped
* around.
*/
if (offset > (p->mwf.size - 20))
goto cleanup;
if (offset < 0)
goto cleanup;
pack_data = git_mwindow_open(&p->mwf, w_cursor, offset, 20, left);
cleanup:
git_mutex_unlock(&p->mwf.lock);
git_mutex_unlock(&p->lock);
return pack_data;
}
/*
* The per-object header is a pretty dense thing, which is
* - first byte: low four bits are "size",
* then three bits of "type",
* with the high bit being "size continues".
* - each byte afterwards: low seven bits are size continuation,
* with the high bit being "size continues"
*/
int git_packfile__object_header(size_t *out, unsigned char *hdr, size_t size, git_object_t type)
{
unsigned char *hdr_base;
unsigned char c;
GIT_ASSERT_ARG(type >= GIT_OBJECT_COMMIT && type <= GIT_OBJECT_REF_DELTA);
/* TODO: add support for chunked objects; see git.git 6c0d19b1 */
c = (unsigned char)((type << 4) | (size & 15));
size >>= 4;
hdr_base = hdr;
while (size) {
*hdr++ = c | 0x80;
c = size & 0x7f;
size >>= 7;
}
*hdr++ = c;
*out = (hdr - hdr_base);
return 0;
}
static int packfile_unpack_header1(
unsigned long *usedp,
size_t *sizep,
git_object_t *type,
const unsigned char *buf,
unsigned long len)
{
unsigned shift;
unsigned long size, c;
unsigned long used = 0;
c = buf[used++];
*type = (c >> 4) & 7;
size = c & 15;
shift = 4;
while (c & 0x80) {
if (len <= used) {
git_error_set(GIT_ERROR_ODB, "buffer too small");
return GIT_EBUFS;
}
if (bitsizeof(long) <= shift) {
*usedp = 0;
git_error_set(GIT_ERROR_ODB, "packfile corrupted");
return -1;
}
c = buf[used++];
size += (c & 0x7f) << shift;
shift += 7;
}
*sizep = (size_t)size;
*usedp = used;
return 0;
}
int git_packfile_unpack_header(
size_t *size_p,
git_object_t *type_p,
struct git_pack_file *p,
git_mwindow **w_curs,
off64_t *curpos)
{
unsigned char *base;
unsigned int left;
unsigned long used;
int error;
if ((error = git_mutex_lock(&p->lock)) < 0)
return error;
if ((error = git_mutex_lock(&p->mwf.lock)) < 0) {
git_mutex_unlock(&p->lock);
return error;
}
if (p->mwf.fd == -1 && (error = packfile_open_locked(p)) < 0) {
git_mutex_unlock(&p->lock);
git_mutex_unlock(&p->mwf.lock);
return error;
}
/* pack_window_open() assures us we have [base, base + 20) available
* as a range that we can look at at. (Its actually the hash
* size that is assured.) With our object header encoding
* the maximum deflated object size is 2^137, which is just
* insane, so we know won't exceed what we have been given.
*/
base = git_mwindow_open(&p->mwf, w_curs, *curpos, 20, &left);
git_mutex_unlock(&p->lock);
git_mutex_unlock(&p->mwf.lock);
if (base == NULL)
return GIT_EBUFS;
error = packfile_unpack_header1(&used, size_p, type_p, base, left);
git_mwindow_close(w_curs);
if (error == GIT_EBUFS)
return error;
else if (error < 0)
return packfile_error("header length is zero");
*curpos += used;
return 0;
}
int git_packfile_resolve_header(
size_t *size_p,
git_object_t *type_p,
struct git_pack_file *p,
off64_t offset)
{
git_mwindow *w_curs = NULL;
off64_t curpos = offset;
size_t size;
git_object_t type;
off64_t base_offset;
int error;
error = git_mutex_lock(&p->lock);
if (error < 0) {
git_error_set(GIT_ERROR_OS, "failed to lock packfile reader");
return error;
}
error = git_mutex_lock(&p->mwf.lock);
if (error < 0) {
git_error_set(GIT_ERROR_OS, "failed to lock packfile reader");
git_mutex_unlock(&p->lock);
return error;
}
if (p->mwf.fd == -1 && (error = packfile_open_locked(p)) < 0) {
git_mutex_unlock(&p->mwf.lock);
git_mutex_unlock(&p->lock);
return error;
}
git_mutex_unlock(&p->mwf.lock);
git_mutex_unlock(&p->lock);
error = git_packfile_unpack_header(&size, &type, p, &w_curs, &curpos);
if (error < 0)
return error;
if (type == GIT_OBJECT_OFS_DELTA || type == GIT_OBJECT_REF_DELTA) {
size_t base_size;
git_packfile_stream stream;
error = get_delta_base(&base_offset, p, &w_curs, &curpos, type, offset);
git_mwindow_close(&w_curs);
if (error < 0)
return error;
if ((error = git_packfile_stream_open(&stream, p, curpos)) < 0)
return error;
error = git_delta_read_header_fromstream(&base_size, size_p, &stream);
git_packfile_stream_dispose(&stream);
if (error < 0)
return error;
} else {
*size_p = size;
base_offset = 0;
}
while (type == GIT_OBJECT_OFS_DELTA || type == GIT_OBJECT_REF_DELTA) {
curpos = base_offset;
error = git_packfile_unpack_header(&size, &type, p, &w_curs, &curpos);
if (error < 0)
return error;
if (type != GIT_OBJECT_OFS_DELTA && type != GIT_OBJECT_REF_DELTA)
break;
error = get_delta_base(&base_offset, p, &w_curs, &curpos, type, base_offset);
git_mwindow_close(&w_curs);
if (error < 0)
return error;
}
*type_p = type;
return error;
}
#define SMALL_STACK_SIZE 64
/**
* Generate the chain of dependencies which we need to get to the
* object at `off`. `chain` is used a stack, popping gives the right
* order to apply deltas on. If an object is found in the pack's base
* cache, we stop calculating there.
*/
static int pack_dependency_chain(git_dependency_chain *chain_out,
git_pack_cache_entry **cached_out, off64_t *cached_off,
struct pack_chain_elem *small_stack, size_t *stack_sz,
struct git_pack_file *p, off64_t obj_offset)
{
git_dependency_chain chain = GIT_ARRAY_INIT;
git_mwindow *w_curs = NULL;
off64_t curpos = obj_offset, base_offset;
int error = 0, use_heap = 0;
size_t size, elem_pos;
git_object_t type;
elem_pos = 0;
while (true) {
struct pack_chain_elem *elem;
git_pack_cache_entry *cached = NULL;
/* if we have a base cached, we can stop here instead */
if ((cached = cache_get(&p->bases, obj_offset)) != NULL) {
*cached_out = cached;
*cached_off = obj_offset;
break;
}
/* if we run out of space on the small stack, use the array */
if (elem_pos == SMALL_STACK_SIZE) {
git_array_init_to_size(chain, elem_pos);
GIT_ERROR_CHECK_ARRAY(chain);
memcpy(chain.ptr, small_stack, elem_pos * sizeof(struct pack_chain_elem));
chain.size = elem_pos;
use_heap = 1;
}
curpos = obj_offset;
if (!use_heap) {
elem = &small_stack[elem_pos];
} else {
elem = git_array_alloc(chain);
if (!elem) {
error = -1;
goto on_error;
}
}
elem->base_key = obj_offset;
error = git_packfile_unpack_header(&size, &type, p, &w_curs, &curpos);
if (error < 0)
goto on_error;
elem->offset = curpos;
elem->size = size;
elem->type = type;
elem->base_key = obj_offset;
if (type != GIT_OBJECT_OFS_DELTA && type != GIT_OBJECT_REF_DELTA)
break;
error = get_delta_base(&base_offset, p, &w_curs, &curpos, type, obj_offset);
git_mwindow_close(&w_curs);
if (error < 0)
goto on_error;
/* we need to pass the pos *after* the delta-base bit */
elem->offset = curpos;
/* go through the loop again, but with the new object */
obj_offset = base_offset;
elem_pos++;
}
*stack_sz = elem_pos + 1;
*chain_out = chain;
return error;
on_error:
git_array_clear(chain);
return error;
}
int git_packfile_unpack(
git_rawobj *obj,
struct git_pack_file *p,
off64_t *obj_offset)
{
git_mwindow *w_curs = NULL;
off64_t curpos = *obj_offset;
int error, free_base = 0;
git_dependency_chain chain = GIT_ARRAY_INIT;
struct pack_chain_elem *elem = NULL, *stack;
git_pack_cache_entry *cached = NULL;
struct pack_chain_elem small_stack[SMALL_STACK_SIZE];
size_t stack_size = 0, elem_pos, alloclen;
git_object_t base_type;
error = git_mutex_lock(&p->lock);
if (error < 0) {
git_error_set(GIT_ERROR_OS, "failed to lock packfile reader");
return error;
}
error = git_mutex_lock(&p->mwf.lock);
if (error < 0) {
git_error_set(GIT_ERROR_OS, "failed to lock packfile reader");
git_mutex_unlock(&p->lock);
return error;
}
if (p->mwf.fd == -1)
error = packfile_open_locked(p);
git_mutex_unlock(&p->mwf.lock);
git_mutex_unlock(&p->lock);
if (error < 0)
return error;
/*
* TODO: optionally check the CRC on the packfile
*/
error = pack_dependency_chain(&chain, &cached, obj_offset, small_stack, &stack_size, p, *obj_offset);
if (error < 0)
return error;
obj->data = NULL;
obj->len = 0;
obj->type = GIT_OBJECT_INVALID;
/* let's point to the right stack */
stack = chain.ptr ? chain.ptr : small_stack;
elem_pos = stack_size;
if (cached) {
memcpy(obj, &cached->raw, sizeof(git_rawobj));
base_type = obj->type;
elem_pos--; /* stack_size includes the base, which isn't actually there */
} else {
elem = &stack[--elem_pos];
base_type = elem->type;
}
switch (base_type) {
case GIT_OBJECT_COMMIT:
case GIT_OBJECT_TREE:
case GIT_OBJECT_BLOB:
case GIT_OBJECT_TAG:
if (!cached) {
curpos = elem->offset;
error = packfile_unpack_compressed(obj, p, &w_curs, &curpos, elem->size, elem->type);
git_mwindow_close(&w_curs);
base_type = elem->type;
}
if (error < 0)
goto cleanup;
break;
case GIT_OBJECT_OFS_DELTA:
case GIT_OBJECT_REF_DELTA:
error = packfile_error("dependency chain ends in a delta");
goto cleanup;
default:
error = packfile_error("invalid packfile type in header");
goto cleanup;
}
/*
* Finding the object we want a cached base element is
* problematic, as we need to make sure we don't accidentally
* give the caller the cached object, which it would then feel
* free to free, so we need to copy the data.
*/
if (cached && stack_size == 1) {
void *data = obj->data;
GIT_ERROR_CHECK_ALLOC_ADD(&alloclen, obj->len, 1);
obj->data = git__malloc(alloclen);
GIT_ERROR_CHECK_ALLOC(obj->data);
memcpy(obj->data, data, obj->len + 1);
git_atomic32_dec(&cached->refcount);
goto cleanup;
}
/* we now apply each consecutive delta until we run out */
while (elem_pos > 0 && !error) {
git_rawobj base, delta;
/*
* We can now try to add the base to the cache, as
* long as it's not already the cached one.
*/
if (!cached)
free_base = !!cache_add(&cached, &p->bases, obj, elem->base_key);
elem = &stack[elem_pos - 1];
curpos = elem->offset;
error = packfile_unpack_compressed(&delta, p, &w_curs, &curpos, elem->size, elem->type);
git_mwindow_close(&w_curs);
if (error < 0) {
/* We have transferred ownership of the data to the cache. */
obj->data = NULL;
break;
}
/* the current object becomes the new base, on which we apply the delta */
base = *obj;
obj->data = NULL;
obj->len = 0;
obj->type = GIT_OBJECT_INVALID;
error = git_delta_apply(&obj->data, &obj->len, base.data, base.len, delta.data, delta.len);
obj->type = base_type;
/*
* We usually don't want to free the base at this
* point, as we put it into the cache in the previous
* iteration. free_base lets us know that we got the
* base object directly from the packfile, so we can free it.
*/
git__free(delta.data);
if (free_base) {
free_base = 0;
git__free(base.data);
}
if (cached) {
git_atomic32_dec(&cached->refcount);
cached = NULL;
}
if (error < 0)
break;
elem_pos--;
}
cleanup:
if (error < 0) {
git__free(obj->data);
if (cached)
git_atomic32_dec(&cached->refcount);
}
if (elem)
*obj_offset = curpos;
git_array_clear(chain);
return error;
}
int git_packfile_stream_open(git_packfile_stream *obj, struct git_pack_file *p, off64_t curpos)
{
memset(obj, 0, sizeof(git_packfile_stream));
obj->curpos = curpos;
obj->p = p;
if (git_zstream_init(&obj->zstream, GIT_ZSTREAM_INFLATE) < 0) {
git_error_set(GIT_ERROR_ZLIB, "failed to init packfile stream");
return -1;
}
return 0;
}
ssize_t git_packfile_stream_read(git_packfile_stream *obj, void *buffer, size_t len)
{
unsigned int window_len;
unsigned char *in;
int error;
if (obj->done)
return 0;
if ((in = pack_window_open(obj->p, &obj->mw, obj->curpos, &window_len)) == NULL)
return GIT_EBUFS;
if ((error = git_zstream_set_input(&obj->zstream, in, window_len)) < 0 ||
(error = git_zstream_get_output_chunk(buffer, &len, &obj->zstream)) < 0) {
git_mwindow_close(&obj->mw);
git_error_set(GIT_ERROR_ZLIB, "error reading from the zlib stream");
return -1;
}
git_mwindow_close(&obj->mw);
obj->curpos += window_len - obj->zstream.in_len;
if (git_zstream_eos(&obj->zstream))
obj->done = 1;
/* If we didn't write anything out but we're not done, we need more data */
if (!len && !git_zstream_eos(&obj->zstream))
return GIT_EBUFS;
return len;
}
void git_packfile_stream_dispose(git_packfile_stream *obj)
{
git_zstream_free(&obj->zstream);
}
static int packfile_unpack_compressed(
git_rawobj *obj,
struct git_pack_file *p,
git_mwindow **mwindow,
off64_t *position,
size_t size,
git_object_t type)
{
git_zstream zstream = GIT_ZSTREAM_INIT;
size_t buffer_len, total = 0;
char *data = NULL;
int error;
GIT_ERROR_CHECK_ALLOC_ADD(&buffer_len, size, 1);
data = git__calloc(1, buffer_len);
GIT_ERROR_CHECK_ALLOC(data);
if ((error = git_zstream_init(&zstream, GIT_ZSTREAM_INFLATE)) < 0) {
git_error_set(GIT_ERROR_ZLIB, "failed to init zlib stream on unpack");
goto out;
}
do {
size_t bytes = buffer_len - total;
unsigned int window_len, consumed;
unsigned char *in;
if ((in = pack_window_open(p, mwindow, *position, &window_len)) == NULL) {
error = -1;
goto out;
}
if ((error = git_zstream_set_input(&zstream, in, window_len)) < 0 ||
(error = git_zstream_get_output_chunk(data + total, &bytes, &zstream)) < 0) {
git_mwindow_close(mwindow);
goto out;
}
git_mwindow_close(mwindow);
consumed = window_len - (unsigned int)zstream.in_len;
if (!bytes && !consumed) {
git_error_set(GIT_ERROR_ZLIB, "error inflating zlib stream");
error = -1;
goto out;
}
*position += consumed;
total += bytes;
} while (!git_zstream_eos(&zstream));
if (total != size || !git_zstream_eos(&zstream)) {
git_error_set(GIT_ERROR_ZLIB, "error inflating zlib stream");
error = -1;
goto out;
}
obj->type = type;
obj->len = size;
obj->data = data;
out:
git_zstream_free(&zstream);
if (error)
git__free(data);
return error;
}
/*
* curpos is where the data starts, delta_obj_offset is the where the
* header starts
*/
int get_delta_base(
off64_t *delta_base_out,
struct git_pack_file *p,
git_mwindow **w_curs,
off64_t *curpos,
git_object_t type,
off64_t delta_obj_offset)
{
unsigned int left = 0;
unsigned char *base_info;
off64_t base_offset;
git_oid unused;
GIT_ASSERT_ARG(delta_base_out);
base_info = pack_window_open(p, w_curs, *curpos, &left);
/* Assumption: the only reason this would fail is because the file is too small */
if (base_info == NULL)
return GIT_EBUFS;
/* pack_window_open() assured us we have [base_info, base_info + 20)
* as a range that we can look at without walking off the
* end of the mapped window. Its actually the hash size
* that is assured. An OFS_DELTA longer than the hash size
* is stupid, as then a REF_DELTA would be smaller to store.
*/
if (type == GIT_OBJECT_OFS_DELTA) {
unsigned used = 0;
unsigned char c = base_info[used++];
size_t unsigned_base_offset = c & 127;
while (c & 128) {
if (left <= used)
return GIT_EBUFS;
unsigned_base_offset += 1;
if (!unsigned_base_offset || MSB(unsigned_base_offset, 7))
return packfile_error("overflow");
c = base_info[used++];
unsigned_base_offset = (unsigned_base_offset << 7) + (c & 127);
}
if (unsigned_base_offset == 0 || (size_t)delta_obj_offset <= unsigned_base_offset)
return packfile_error("out of bounds");
base_offset = delta_obj_offset - unsigned_base_offset;
*curpos += used;
} else if (type == GIT_OBJECT_REF_DELTA) {
/* If we have the cooperative cache, search in it first */
if (p->has_cache) {
struct git_pack_entry *entry;
git_oid oid;
git_oid_fromraw(&oid, base_info);
if ((entry = git_oidmap_get(p->idx_cache, &oid)) != NULL) {
if (entry->offset == 0)
return packfile_error("delta offset is zero");
*curpos += 20;
*delta_base_out = entry->offset;
return 0;
} else {
/* If we're building an index, don't try to find the pack
* entry; we just haven't seen it yet. We'll make
* progress again in the next loop.
*/
return GIT_PASSTHROUGH;
}
}
/* The base entry _must_ be in the same pack */
if (pack_entry_find_offset(&base_offset, &unused, p, (git_oid *)base_info, GIT_OID_HEXSZ) < 0)
return packfile_error("base entry delta is not in the same pack");
*curpos += 20;
} else
return packfile_error("unknown object type");
if (base_offset == 0)
return packfile_error("delta offset is zero");
*delta_base_out = base_offset;
return 0;
}
/***********************************************************
*
* PACKFILE METHODS
*
***********************************************************/
void git_packfile_free(struct git_pack_file *p, bool unlink_packfile)
{
bool locked = true;
if (!p)
return;
cache_free(&p->bases);
if (git_mutex_lock(&p->lock) < 0) {
git_error_set(GIT_ERROR_OS, "failed to lock packfile");
locked = false;
}
if (p->mwf.fd >= 0) {
git_mwindow_free_all(&p->mwf);
p_close(p->mwf.fd);
p->mwf.fd = -1;
}
if (locked)
git_mutex_unlock(&p->lock);
if (unlink_packfile)
p_unlink(p->pack_name);
pack_index_free(p);
git__free(p->bad_object_sha1);
git_mutex_free(&p->bases.lock);
git_mutex_free(&p->mwf.lock);
git_mutex_free(&p->lock);
git__free(p);
}
/* Run with the packfile and mwf locks held */
static int packfile_open_locked(struct git_pack_file *p)
{
struct stat st;
struct git_pack_header hdr;
git_oid sha1;
unsigned char *idx_sha1;
if (pack_index_open_locked(p) < 0)
return git_odb__error_notfound("failed to open packfile", NULL, 0);
if (p->mwf.fd >= 0)
return 0;
/* TODO: open with noatime */
p->mwf.fd = git_futils_open_ro(p->pack_name);
if (p->mwf.fd < 0)
goto cleanup;
if (p_fstat(p->mwf.fd, &st) < 0) {
git_error_set(GIT_ERROR_OS, "could not stat packfile");
goto cleanup;
}
/* If we created the struct before we had the pack we lack size. */
if (!p->mwf.size) {
if (!S_ISREG(st.st_mode))
goto cleanup;
p->mwf.size = (off64_t)st.st_size;
} else if (p->mwf.size != st.st_size)
goto cleanup;
#if 0
/* We leave these file descriptors open with sliding mmap;
* there is no point keeping them open across exec(), though.
*/
fd_flag = fcntl(p->mwf.fd, F_GETFD, 0);
if (fd_flag < 0)
goto cleanup;
fd_flag |= FD_CLOEXEC;
if (fcntl(p->pack_fd, F_SETFD, fd_flag) == -1)
goto cleanup;
#endif
/* Verify we recognize this pack file format. */
if (p_read(p->mwf.fd, &hdr, sizeof(hdr)) < 0 ||
hdr.hdr_signature != htonl(PACK_SIGNATURE) ||
!pack_version_ok(hdr.hdr_version))
goto cleanup;
/* Verify the pack matches its index. */
if (p->num_objects != ntohl(hdr.hdr_entries) ||
p_pread(p->mwf.fd, sha1.id, GIT_OID_RAWSZ, p->mwf.size - GIT_OID_RAWSZ) < 0)
goto cleanup;
idx_sha1 = ((unsigned char *)p->index_map.data) + p->index_map.len - 40;
if (git_oid__cmp(&sha1, (git_oid *)idx_sha1) != 0)
goto cleanup;
if (git_mwindow_file_register(&p->mwf) < 0)
goto cleanup;
return 0;
cleanup:
git_error_set(GIT_ERROR_OS, "invalid packfile '%s'", p->pack_name);
if (p->mwf.fd >= 0)
p_close(p->mwf.fd);
p->mwf.fd = -1;
return -1;
}
int git_packfile__name(char **out, const char *path)
{
size_t path_len;
git_buf buf = GIT_BUF_INIT;
path_len = strlen(path);
if (path_len < strlen(".idx"))
return git_odb__error_notfound("invalid packfile path", NULL, 0);
if (git_buf_printf(&buf, "%.*s.pack", (int)(path_len - strlen(".idx")), path) < 0)
return -1;
*out = git_buf_detach(&buf);
return 0;
}
int git_packfile_alloc(struct git_pack_file **pack_out, const char *path)
{
struct stat st;
struct git_pack_file *p;
size_t path_len = path ? strlen(path) : 0, alloc_len;
*pack_out = NULL;
if (path_len < strlen(".idx"))
return git_odb__error_notfound("invalid packfile path", NULL, 0);
GIT_ERROR_CHECK_ALLOC_ADD(&alloc_len, sizeof(*p), path_len);
GIT_ERROR_CHECK_ALLOC_ADD(&alloc_len, alloc_len, 2);
p = git__calloc(1, alloc_len);
GIT_ERROR_CHECK_ALLOC(p);
memcpy(p->pack_name, path, path_len + 1);
/*
* Make sure a corresponding .pack file exists and that
* the index looks sane.
*/
if (git__suffixcmp(path, ".idx") == 0) {
size_t root_len = path_len - strlen(".idx");
if (!git_disable_pack_keep_file_checks) {
memcpy(p->pack_name + root_len, ".keep", sizeof(".keep"));
if (git_path_exists(p->pack_name) == true)
p->pack_keep = 1;
}
memcpy(p->pack_name + root_len, ".pack", sizeof(".pack"));
}
if (p_stat(p->pack_name, &st) < 0 || !S_ISREG(st.st_mode)) {
git__free(p);
return git_odb__error_notfound("packfile not found", NULL, 0);
}
/* ok, it looks sane as far as we can check without
* actually mapping the pack file.
*/
p->mwf.fd = -1;
p->mwf.size = st.st_size;
p->pack_local = 1;
p->mtime = (git_time_t)st.st_mtime;
p->index_version = -1;
if (git_mutex_init(&p->lock) < 0) {
git_error_set(GIT_ERROR_OS, "failed to initialize packfile mutex");
git__free(p);
return -1;
}
if (git_mutex_init(&p->mwf.lock) < 0) {
git_error_set(GIT_ERROR_OS, "failed to initialize packfile window mutex");
git_mutex_free(&p->lock);
git__free(p);
return -1;
}
if (cache_init(&p->bases) < 0) {
git_mutex_free(&p->mwf.lock);
git_mutex_free(&p->lock);
git__free(p);
return -1;
}
*pack_out = p;
return 0;
}
/***********************************************************
*
* PACKFILE ENTRY SEARCH INTERNALS
*
***********************************************************/
static off64_t nth_packed_object_offset_locked(struct git_pack_file *p, uint32_t n)
{
const unsigned char *index, *end;
uint32_t off32;
index = p->index_map.data;
end = index + p->index_map.len;
index += 4 * 256;
if (p->index_version == 1)
return ntohl(*((uint32_t *)(index + 24 * n)));
index += 8 + p->num_objects * (20 + 4);
off32 = ntohl(*((uint32_t *)(index + 4 * n)));
if (!(off32 & 0x80000000))
return off32;
index += p->num_objects * 4 + (off32 & 0x7fffffff) * 8;
/* Make sure we're not being sent out of bounds */
if (index >= end - 8)
return -1;
return (((uint64_t)ntohl(*((uint32_t *)(index + 0)))) << 32) |
ntohl(*((uint32_t *)(index + 4)));
}
static int git__memcmp4(const void *a, const void *b) {
return memcmp(a, b, 4);
}
int git_pack_foreach_entry(
struct git_pack_file *p,
git_odb_foreach_cb cb,
void *data)
{
const unsigned char *index, *current;
uint32_t i;
int error = 0;
git_array_oid_t oids = GIT_ARRAY_INIT;
git_oid *oid;
if (git_mutex_lock(&p->lock) < 0)
return packfile_error("failed to get lock for git_pack_foreach_entry");
if ((error = pack_index_open_locked(p)) < 0) {
git_mutex_unlock(&p->lock);
return error;
}
if (!p->index_map.data) {
git_error_set(GIT_ERROR_INTERNAL, "internal error: p->index_map.data == NULL");
git_mutex_unlock(&p->lock);
return -1;
}
index = p->index_map.data;
if (p->index_version > 1)
index += 8;
index += 4 * 256;
if (p->oids == NULL) {
git_vector offsets, oids;
if ((error = git_vector_init(&oids, p->num_objects, NULL))) {
git_mutex_unlock(&p->lock);
return error;
}
if ((error = git_vector_init(&offsets, p->num_objects, git__memcmp4))) {
git_mutex_unlock(&p->lock);
return error;
}
if (p->index_version > 1) {
const unsigned char *off = index + 24 * p->num_objects;
for (i = 0; i < p->num_objects; i++)
git_vector_insert(&offsets, (void*)&off[4 * i]);
git_vector_sort(&offsets);
git_vector_foreach(&offsets, i, current)
git_vector_insert(&oids, (void*)&index[5 * (current - off)]);
} else {
for (i = 0; i < p->num_objects; i++)
git_vector_insert(&offsets, (void*)&index[24 * i]);
git_vector_sort(&offsets);
git_vector_foreach(&offsets, i, current)
git_vector_insert(&oids, (void*)¤t[4]);
}
git_vector_free(&offsets);
p->oids = (git_oid **)git_vector_detach(NULL, NULL, &oids);
}
/* We need to copy the OIDs to another array before we relinquish the lock to avoid races. */
git_array_init_to_size(oids, p->num_objects);
if (!oids.ptr) {
git_mutex_unlock(&p->lock);
git_array_clear(oids);
GIT_ERROR_CHECK_ARRAY(oids);
}
for (i = 0; i < p->num_objects; i++) {
oid = git_array_alloc(oids);
if (!oid) {
git_mutex_unlock(&p->lock);
git_array_clear(oids);
GIT_ERROR_CHECK_ALLOC(oid);
}
git_oid_cpy(oid, p->oids[i]);
}
git_mutex_unlock(&p->lock);
git_array_foreach(oids, i, oid) {
if ((error = cb(oid, data)) != 0) {
git_error_set_after_callback(error);
break;
}
}
git_array_clear(oids);
return error;
}
int git_pack_foreach_entry_offset(
struct git_pack_file *p,
git_pack_foreach_entry_offset_cb cb,
void *data)
{
const unsigned char *index;
off64_t current_offset;
const git_oid *current_oid;
uint32_t i;
int error = 0;
if (git_mutex_lock(&p->lock) < 0)
return packfile_error("failed to get lock for git_pack_foreach_entry_offset");
index = p->index_map.data;
if (index == NULL) {
if ((error = pack_index_open_locked(p)) < 0)
goto cleanup;
if (!p->index_map.data) {
git_error_set(GIT_ERROR_INTERNAL, "internal error: p->index_map.data == NULL");
goto cleanup;
}
index = p->index_map.data;
}
if (p->index_version > 1)
index += 8;
index += 4 * 256;
/* all offsets should have been validated by pack_index_check_locked */
if (p->index_version > 1) {
const unsigned char *offsets = index + 24 * p->num_objects;
const unsigned char *large_offset_ptr;
const unsigned char *large_offsets = index + 28 * p->num_objects;
const unsigned char *large_offsets_end = ((const unsigned char *)p->index_map.data) + p->index_map.len - 20;
for (i = 0; i < p->num_objects; i++) {
current_offset = ntohl(*(const uint32_t *)(offsets + 4 * i));
if (current_offset & 0x80000000) {
large_offset_ptr = large_offsets + (current_offset & 0x7fffffff) * 8;
if (large_offset_ptr >= large_offsets_end) {
error = packfile_error("invalid large offset");
goto cleanup;
}
current_offset = (((off64_t)ntohl(*((uint32_t *)(large_offset_ptr + 0)))) << 32) |
ntohl(*((uint32_t *)(large_offset_ptr + 4)));
}
current_oid = (const git_oid *)(index + 20 * i);
if ((error = cb(current_oid, current_offset, data)) != 0) {
error = git_error_set_after_callback(error);
goto cleanup;
}
}
} else {
for (i = 0; i < p->num_objects; i++) {
current_offset = ntohl(*(const uint32_t *)(index + 24 * i));
current_oid = (const git_oid *)(index + 24 * i + 4);
if ((error = cb(current_oid, current_offset, data)) != 0) {
error = git_error_set_after_callback(error);
goto cleanup;
}
}
}
cleanup:
git_mutex_unlock(&p->lock);
return error;
}
int git_pack__lookup_sha1(const void *oid_lookup_table, size_t stride, unsigned lo,
unsigned hi, const unsigned char *oid_prefix)
{
const unsigned char *base = oid_lookup_table;
while (lo < hi) {
unsigned mi = (lo + hi) / 2;
int cmp = git_oid__hashcmp(base + mi * stride, oid_prefix);
if (!cmp)
return mi;
if (cmp > 0)
hi = mi;
else
lo = mi+1;
}
return -((int)lo)-1;
}
static int pack_entry_find_offset(
off64_t *offset_out,
git_oid *found_oid,
struct git_pack_file *p,
const git_oid *short_oid,
size_t len)
{
const uint32_t *level1_ofs;
const unsigned char *index;
unsigned hi, lo, stride;
int pos, found = 0;
off64_t offset;
const unsigned char *current = 0;
int error = 0;
*offset_out = 0;
if (git_mutex_lock(&p->lock) < 0)
return packfile_error("failed to get lock for pack_entry_find_offset");
if ((error = pack_index_open_locked(p)) < 0)
goto cleanup;
if (!p->index_map.data) {
git_error_set(GIT_ERROR_INTERNAL, "internal error: p->index_map.data == NULL");
goto cleanup;
}
index = p->index_map.data;
level1_ofs = p->index_map.data;
if (p->index_version > 1) {
level1_ofs += 2;
index += 8;
}
index += 4 * 256;
hi = ntohl(level1_ofs[(int)short_oid->id[0]]);
lo = ((short_oid->id[0] == 0x0) ? 0 : ntohl(level1_ofs[(int)short_oid->id[0] - 1]));
if (p->index_version > 1) {
stride = 20;
} else {
stride = 24;
index += 4;
}
#ifdef INDEX_DEBUG_LOOKUP
printf("%02x%02x%02x... lo %u hi %u nr %d\n",
short_oid->id[0], short_oid->id[1], short_oid->id[2], lo, hi, p->num_objects);
#endif
pos = git_pack__lookup_sha1(index, stride, lo, hi, short_oid->id);
if (pos >= 0) {
/* An object matching exactly the oid was found */
found = 1;
current = index + pos * stride;
} else {
/* No object was found */
/* pos refers to the object with the "closest" oid to short_oid */
pos = - 1 - pos;
if (pos < (int)p->num_objects) {
current = index + pos * stride;
if (!git_oid_ncmp(short_oid, (const git_oid *)current, len))
found = 1;
}
}
if (found && len != GIT_OID_HEXSZ && pos + 1 < (int)p->num_objects) {
/* Check for ambiguousity */
const unsigned char *next = current + stride;
if (!git_oid_ncmp(short_oid, (const git_oid *)next, len)) {
found = 2;
}
}
if (!found) {
error = git_odb__error_notfound("failed to find offset for pack entry", short_oid, len);
goto cleanup;
}
if (found > 1) {
error = git_odb__error_ambiguous("found multiple offsets for pack entry");
goto cleanup;
}
if ((offset = nth_packed_object_offset_locked(p, pos)) < 0) {
git_error_set(GIT_ERROR_ODB, "packfile index is corrupt");
error = -1;
goto cleanup;
}
*offset_out = offset;
git_oid_fromraw(found_oid, current);
#ifdef INDEX_DEBUG_LOOKUP
{
unsigned char hex_sha1[GIT_OID_HEXSZ + 1];
git_oid_fmt(hex_sha1, found_oid);
hex_sha1[GIT_OID_HEXSZ] = '\0';
printf("found lo=%d %s\n", lo, hex_sha1);
}
#endif
cleanup:
git_mutex_unlock(&p->lock);
return error;
}
int git_pack_entry_find(
struct git_pack_entry *e,
struct git_pack_file *p,
const git_oid *short_oid,
size_t len)
{
off64_t offset;
git_oid found_oid;
int error;
GIT_ASSERT_ARG(p);
if (len == GIT_OID_HEXSZ && p->num_bad_objects) {
unsigned i;
for (i = 0; i < p->num_bad_objects; i++)
if (git_oid__cmp(short_oid, &p->bad_object_sha1[i]) == 0)
return packfile_error("bad object found in packfile");
}
error = pack_entry_find_offset(&offset, &found_oid, p, short_oid, len);
if (error < 0)
return error;
error = git_mutex_lock(&p->lock);
if (error < 0) {
git_error_set(GIT_ERROR_OS, "failed to lock packfile reader");
return error;
}
error = git_mutex_lock(&p->mwf.lock);
if (error < 0) {
git_mutex_unlock(&p->lock);
git_error_set(GIT_ERROR_OS, "failed to lock packfile reader");
return error;
}
/* we found a unique entry in the index;
* make sure the packfile backing the index
* still exists on disk */
if (p->mwf.fd == -1)
error = packfile_open_locked(p);
git_mutex_unlock(&p->mwf.lock);
git_mutex_unlock(&p->lock);
if (error < 0)
return error;
e->offset = offset;
e->p = p;
git_oid_cpy(&e->sha1, &found_oid);
return 0;
}
|
0 |
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2
|
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2/src/oidarray.c
|
/*
* Copyright (C) the libgit2 contributors. All rights reserved.
*
* This file is part of libgit2, distributed under the GNU GPL v2 with
* a Linking Exception. For full terms see the included COPYING file.
*/
#include "oidarray.h"
#include "git2/oidarray.h"
#include "array.h"
void git_oidarray_dispose(git_oidarray *arr)
{
git__free(arr->ids);
}
void git_oidarray__from_array(git_oidarray *arr, git_array_oid_t *array)
{
arr->count = array->size;
arr->ids = array->ptr;
}
void git_oidarray__reverse(git_oidarray *arr)
{
size_t i;
git_oid tmp;
for (i = 0; i < arr->count / 2; i++) {
git_oid_cpy(&tmp, &arr->ids[i]);
git_oid_cpy(&arr->ids[i], &arr->ids[(arr->count-1)-i]);
git_oid_cpy(&arr->ids[(arr->count-1)-i], &tmp);
}
}
#ifndef GIT_DEPRECATE_HARD
void git_oidarray_free(git_oidarray *arr)
{
git_oidarray_dispose(arr);
}
#endif
|
0 |
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2
|
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2/src/remote.c
|
/*
* Copyright (C) the libgit2 contributors. All rights reserved.
*
* This file is part of libgit2, distributed under the GNU GPL v2 with
* a Linking Exception. For full terms see the included COPYING file.
*/
#include "remote.h"
#include "git2/config.h"
#include "git2/types.h"
#include "git2/oid.h"
#include "git2/net.h"
#include "config.h"
#include "repository.h"
#include "fetch.h"
#include "refs.h"
#include "refspec.h"
#include "fetchhead.h"
#include "push.h"
#define CONFIG_URL_FMT "remote.%s.url"
#define CONFIG_PUSHURL_FMT "remote.%s.pushurl"
#define CONFIG_FETCH_FMT "remote.%s.fetch"
#define CONFIG_PUSH_FMT "remote.%s.push"
#define CONFIG_TAGOPT_FMT "remote.%s.tagopt"
static int dwim_refspecs(git_vector *out, git_vector *refspecs, git_vector *refs);
static int lookup_remote_prune_config(git_remote *remote, git_config *config, const char *name);
char *apply_insteadof(git_config *config, const char *url, int direction);
static int add_refspec_to(git_vector *vector, const char *string, bool is_fetch)
{
git_refspec *spec;
spec = git__calloc(1, sizeof(git_refspec));
GIT_ERROR_CHECK_ALLOC(spec);
if (git_refspec__parse(spec, string, is_fetch) < 0) {
git__free(spec);
return -1;
}
spec->push = !is_fetch;
if (git_vector_insert(vector, spec) < 0) {
git_refspec__dispose(spec);
git__free(spec);
return -1;
}
return 0;
}
static int add_refspec(git_remote *remote, const char *string, bool is_fetch)
{
return add_refspec_to(&remote->refspecs, string, is_fetch);
}
static int download_tags_value(git_remote *remote, git_config *cfg)
{
git_config_entry *ce;
git_buf buf = GIT_BUF_INIT;
int error;
if (git_buf_printf(&buf, "remote.%s.tagopt", remote->name) < 0)
return -1;
error = git_config__lookup_entry(&ce, cfg, git_buf_cstr(&buf), false);
git_buf_dispose(&buf);
if (!error && ce && ce->value) {
if (!strcmp(ce->value, "--no-tags"))
remote->download_tags = GIT_REMOTE_DOWNLOAD_TAGS_NONE;
else if (!strcmp(ce->value, "--tags"))
remote->download_tags = GIT_REMOTE_DOWNLOAD_TAGS_ALL;
}
git_config_entry_free(ce);
return error;
}
static int ensure_remote_name_is_valid(const char *name)
{
int valid, error;
error = git_remote_name_is_valid(&valid, name);
if (!error && !valid) {
git_error_set(
GIT_ERROR_CONFIG,
"'%s' is not a valid remote name.", name ? name : "(null)");
error = GIT_EINVALIDSPEC;
}
return error;
}
static int write_add_refspec(git_repository *repo, const char *name, const char *refspec, bool fetch)
{
git_config *cfg;
git_buf var = GIT_BUF_INIT;
git_refspec spec;
const char *fmt;
int error;
if ((error = git_repository_config__weakptr(&cfg, repo)) < 0)
return error;
fmt = fetch ? CONFIG_FETCH_FMT : CONFIG_PUSH_FMT;
if ((error = ensure_remote_name_is_valid(name)) < 0)
return error;
if ((error = git_refspec__parse(&spec, refspec, fetch)) < 0)
return error;
git_refspec__dispose(&spec);
if ((error = git_buf_printf(&var, fmt, name)) < 0)
return error;
/*
* "$^" is an unmatchable regexp: it will not match anything at all, so
* all values will be considered new and we will not replace any
* present value.
*/
if ((error = git_config_set_multivar(cfg, var.ptr, "$^", refspec)) < 0) {
goto cleanup;
}
cleanup:
git_buf_dispose(&var);
return 0;
}
static int canonicalize_url(git_buf *out, const char *in)
{
if (in == NULL || strlen(in) == 0) {
git_error_set(GIT_ERROR_INVALID, "cannot set empty URL");
return GIT_EINVALIDSPEC;
}
#ifdef GIT_WIN32
/* Given a UNC path like \\server\path, we need to convert this
* to //server/path for compatibility with core git.
*/
if (in[0] == '\\' && in[1] == '\\' &&
(git__isalpha(in[2]) || git__isdigit(in[2]))) {
const char *c;
for (c = in; *c; c++)
git_buf_putc(out, *c == '\\' ? '/' : *c);
return git_buf_oom(out) ? -1 : 0;
}
#endif
return git_buf_puts(out, in);
}
static int default_fetchspec_for_name(git_buf *buf, const char *name)
{
if (git_buf_printf(buf, "+refs/heads/*:refs/remotes/%s/*", name) < 0)
return -1;
return 0;
}
static int ensure_remote_doesnot_exist(git_repository *repo, const char *name)
{
int error;
git_remote *remote;
error = git_remote_lookup(&remote, repo, name);
if (error == GIT_ENOTFOUND)
return 0;
if (error < 0)
return error;
git_remote_free(remote);
git_error_set(GIT_ERROR_CONFIG, "remote '%s' already exists", name);
return GIT_EEXISTS;
}
int git_remote_create_options_init(git_remote_create_options *opts, unsigned int version)
{
GIT_INIT_STRUCTURE_FROM_TEMPLATE(
opts, version, git_remote_create_options, GIT_REMOTE_CREATE_OPTIONS_INIT);
return 0;
}
#ifndef GIT_DEPRECATE_HARD
int git_remote_create_init_options(git_remote_create_options *opts, unsigned int version)
{
return git_remote_create_options_init(opts, version);
}
#endif
int git_remote_create_with_opts(git_remote **out, const char *url, const git_remote_create_options *opts)
{
git_remote *remote = NULL;
git_config *config_ro = NULL, *config_rw;
git_buf canonical_url = GIT_BUF_INIT;
git_buf var = GIT_BUF_INIT;
git_buf specbuf = GIT_BUF_INIT;
const git_remote_create_options dummy_opts = GIT_REMOTE_CREATE_OPTIONS_INIT;
int error = -1;
GIT_ASSERT_ARG(out);
GIT_ASSERT_ARG(url);
if (!opts) {
opts = &dummy_opts;
}
GIT_ERROR_CHECK_VERSION(opts, GIT_REMOTE_CREATE_OPTIONS_VERSION, "git_remote_create_options");
if (opts->name != NULL) {
if ((error = ensure_remote_name_is_valid(opts->name)) < 0)
return error;
if (opts->repository &&
(error = ensure_remote_doesnot_exist(opts->repository, opts->name)) < 0)
return error;
}
if (opts->repository) {
if ((error = git_repository_config_snapshot(&config_ro, opts->repository)) < 0)
goto on_error;
}
remote = git__calloc(1, sizeof(git_remote));
GIT_ERROR_CHECK_ALLOC(remote);
remote->repo = opts->repository;
if ((error = git_vector_init(&remote->refs, 8, NULL)) < 0 ||
(error = canonicalize_url(&canonical_url, url)) < 0)
goto on_error;
if (opts->repository && !(opts->flags & GIT_REMOTE_CREATE_SKIP_INSTEADOF)) {
remote->url = apply_insteadof(config_ro, canonical_url.ptr, GIT_DIRECTION_FETCH);
} else {
remote->url = git__strdup(canonical_url.ptr);
}
GIT_ERROR_CHECK_ALLOC(remote->url);
if (opts->name != NULL) {
remote->name = git__strdup(opts->name);
GIT_ERROR_CHECK_ALLOC(remote->name);
if (opts->repository &&
((error = git_buf_printf(&var, CONFIG_URL_FMT, opts->name)) < 0 ||
(error = git_repository_config__weakptr(&config_rw, opts->repository)) < 0 ||
(error = git_config_set_string(config_rw, var.ptr, canonical_url.ptr)) < 0))
goto on_error;
}
if (opts->fetchspec != NULL ||
(opts->name && !(opts->flags & GIT_REMOTE_CREATE_SKIP_DEFAULT_FETCHSPEC))) {
const char *fetch = NULL;
if (opts->fetchspec) {
fetch = opts->fetchspec;
} else {
if ((error = default_fetchspec_for_name(&specbuf, opts->name)) < 0)
goto on_error;
fetch = git_buf_cstr(&specbuf);
}
if ((error = add_refspec(remote, fetch, true)) < 0)
goto on_error;
/* only write for named remotes with a repository */
if (opts->repository && opts->name &&
((error = write_add_refspec(opts->repository, opts->name, fetch, true)) < 0 ||
(error = lookup_remote_prune_config(remote, config_ro, opts->name)) < 0))
goto on_error;
/* Move the data over to where the matching functions can find them */
if ((error = dwim_refspecs(&remote->active_refspecs, &remote->refspecs, &remote->refs)) < 0)
goto on_error;
}
/* A remote without a name doesn't download tags */
if (!opts->name)
remote->download_tags = GIT_REMOTE_DOWNLOAD_TAGS_NONE;
else
remote->download_tags = GIT_REMOTE_DOWNLOAD_TAGS_AUTO;
git_buf_dispose(&var);
*out = remote;
error = 0;
on_error:
if (error)
git_remote_free(remote);
git_config_free(config_ro);
git_buf_dispose(&specbuf);
git_buf_dispose(&canonical_url);
git_buf_dispose(&var);
return error;
}
int git_remote_create(git_remote **out, git_repository *repo, const char *name, const char *url)
{
git_buf buf = GIT_BUF_INIT;
int error;
git_remote_create_options opts = GIT_REMOTE_CREATE_OPTIONS_INIT;
/* Those 2 tests are duplicated here because of backward-compatibility */
if ((error = ensure_remote_name_is_valid(name)) < 0)
return error;
if (canonicalize_url(&buf, url) < 0)
return GIT_ERROR;
git_buf_clear(&buf);
opts.repository = repo;
opts.name = name;
error = git_remote_create_with_opts(out, url, &opts);
git_buf_dispose(&buf);
return error;
}
int git_remote_create_with_fetchspec(git_remote **out, git_repository *repo, const char *name, const char *url, const char *fetch)
{
int error;
git_remote_create_options opts = GIT_REMOTE_CREATE_OPTIONS_INIT;
if ((error = ensure_remote_name_is_valid(name)) < 0)
return error;
opts.repository = repo;
opts.name = name;
opts.fetchspec = fetch;
opts.flags = GIT_REMOTE_CREATE_SKIP_DEFAULT_FETCHSPEC;
return git_remote_create_with_opts(out, url, &opts);
}
int git_remote_create_anonymous(git_remote **out, git_repository *repo, const char *url)
{
git_remote_create_options opts = GIT_REMOTE_CREATE_OPTIONS_INIT;
opts.repository = repo;
return git_remote_create_with_opts(out, url, &opts);
}
int git_remote_create_detached(git_remote **out, const char *url)
{
return git_remote_create_with_opts(out, url, NULL);
}
int git_remote_dup(git_remote **dest, git_remote *source)
{
size_t i;
int error = 0;
git_refspec *spec;
git_remote *remote = git__calloc(1, sizeof(git_remote));
GIT_ERROR_CHECK_ALLOC(remote);
if (source->name != NULL) {
remote->name = git__strdup(source->name);
GIT_ERROR_CHECK_ALLOC(remote->name);
}
if (source->url != NULL) {
remote->url = git__strdup(source->url);
GIT_ERROR_CHECK_ALLOC(remote->url);
}
if (source->pushurl != NULL) {
remote->pushurl = git__strdup(source->pushurl);
GIT_ERROR_CHECK_ALLOC(remote->pushurl);
}
remote->repo = source->repo;
remote->download_tags = source->download_tags;
remote->prune_refs = source->prune_refs;
if (git_vector_init(&remote->refs, 32, NULL) < 0 ||
git_vector_init(&remote->refspecs, 2, NULL) < 0 ||
git_vector_init(&remote->active_refspecs, 2, NULL) < 0) {
error = -1;
goto cleanup;
}
git_vector_foreach(&source->refspecs, i, spec) {
if ((error = add_refspec(remote, spec->string, !spec->push)) < 0)
goto cleanup;
}
*dest = remote;
cleanup:
if (error < 0)
git__free(remote);
return error;
}
struct refspec_cb_data {
git_remote *remote;
int fetch;
};
static int refspec_cb(const git_config_entry *entry, void *payload)
{
struct refspec_cb_data *data = (struct refspec_cb_data *)payload;
return add_refspec(data->remote, entry->value, data->fetch);
}
static int get_optional_config(
bool *found, git_config *config, git_buf *buf,
git_config_foreach_cb cb, void *payload)
{
int error = 0;
const char *key = git_buf_cstr(buf);
if (git_buf_oom(buf))
return -1;
if (cb != NULL)
error = git_config_get_multivar_foreach(config, key, NULL, cb, payload);
else
error = git_config_get_string(payload, config, key);
if (found)
*found = !error;
if (error == GIT_ENOTFOUND) {
git_error_clear();
error = 0;
}
return error;
}
int git_remote_lookup(git_remote **out, git_repository *repo, const char *name)
{
git_remote *remote = NULL;
git_buf buf = GIT_BUF_INIT;
const char *val;
int error = 0;
git_config *config;
struct refspec_cb_data data = { NULL };
bool optional_setting_found = false, found;
GIT_ASSERT_ARG(out);
GIT_ASSERT_ARG(repo);
GIT_ASSERT_ARG(name);
if ((error = ensure_remote_name_is_valid(name)) < 0)
return error;
if ((error = git_repository_config_snapshot(&config, repo)) < 0)
return error;
remote = git__calloc(1, sizeof(git_remote));
GIT_ERROR_CHECK_ALLOC(remote);
remote->name = git__strdup(name);
GIT_ERROR_CHECK_ALLOC(remote->name);
if (git_vector_init(&remote->refs, 32, NULL) < 0 ||
git_vector_init(&remote->refspecs, 2, NULL) < 0 ||
git_vector_init(&remote->passive_refspecs, 2, NULL) < 0 ||
git_vector_init(&remote->active_refspecs, 2, NULL) < 0) {
error = -1;
goto cleanup;
}
if ((error = git_buf_printf(&buf, "remote.%s.url", name)) < 0)
goto cleanup;
if ((error = get_optional_config(&found, config, &buf, NULL, (void *)&val)) < 0)
goto cleanup;
optional_setting_found |= found;
remote->repo = repo;
remote->download_tags = GIT_REMOTE_DOWNLOAD_TAGS_AUTO;
if (found && strlen(val) > 0) {
remote->url = apply_insteadof(config, val, GIT_DIRECTION_FETCH);
GIT_ERROR_CHECK_ALLOC(remote->url);
}
val = NULL;
git_buf_clear(&buf);
git_buf_printf(&buf, "remote.%s.pushurl", name);
if ((error = get_optional_config(&found, config, &buf, NULL, (void *)&val)) < 0)
goto cleanup;
optional_setting_found |= found;
if (!optional_setting_found) {
error = GIT_ENOTFOUND;
git_error_set(GIT_ERROR_CONFIG, "remote '%s' does not exist", name);
goto cleanup;
}
if (found && strlen(val) > 0) {
remote->pushurl = apply_insteadof(config, val, GIT_DIRECTION_PUSH);
GIT_ERROR_CHECK_ALLOC(remote->pushurl);
}
data.remote = remote;
data.fetch = true;
git_buf_clear(&buf);
git_buf_printf(&buf, "remote.%s.fetch", name);
if ((error = get_optional_config(NULL, config, &buf, refspec_cb, &data)) < 0)
goto cleanup;
data.fetch = false;
git_buf_clear(&buf);
git_buf_printf(&buf, "remote.%s.push", name);
if ((error = get_optional_config(NULL, config, &buf, refspec_cb, &data)) < 0)
goto cleanup;
if ((error = download_tags_value(remote, config)) < 0)
goto cleanup;
if ((error = lookup_remote_prune_config(remote, config, name)) < 0)
goto cleanup;
/* Move the data over to where the matching functions can find them */
if ((error = dwim_refspecs(&remote->active_refspecs, &remote->refspecs, &remote->refs)) < 0)
goto cleanup;
*out = remote;
cleanup:
git_config_free(config);
git_buf_dispose(&buf);
if (error < 0)
git_remote_free(remote);
return error;
}
static int lookup_remote_prune_config(git_remote *remote, git_config *config, const char *name)
{
git_buf buf = GIT_BUF_INIT;
int error = 0;
git_buf_printf(&buf, "remote.%s.prune", name);
if ((error = git_config_get_bool(&remote->prune_refs, config, git_buf_cstr(&buf))) < 0) {
if (error == GIT_ENOTFOUND) {
git_error_clear();
if ((error = git_config_get_bool(&remote->prune_refs, config, "fetch.prune")) < 0) {
if (error == GIT_ENOTFOUND) {
git_error_clear();
error = 0;
}
}
}
}
git_buf_dispose(&buf);
return error;
}
const char *git_remote_name(const git_remote *remote)
{
GIT_ASSERT_ARG_WITH_RETVAL(remote, NULL);
return remote->name;
}
git_repository *git_remote_owner(const git_remote *remote)
{
GIT_ASSERT_ARG_WITH_RETVAL(remote, NULL);
return remote->repo;
}
const char *git_remote_url(const git_remote *remote)
{
GIT_ASSERT_ARG_WITH_RETVAL(remote, NULL);
return remote->url;
}
int git_remote_set_instance_url(git_remote *remote, const char *url)
{
char *tmp;
GIT_ASSERT_ARG(remote);
GIT_ASSERT_ARG(url);
if ((tmp = git__strdup(url)) == NULL)
return -1;
git__free(remote->url);
remote->url = tmp;
return 0;
}
static int set_url(git_repository *repo, const char *remote, const char *pattern, const char *url)
{
git_config *cfg;
git_buf buf = GIT_BUF_INIT, canonical_url = GIT_BUF_INIT;
int error;
GIT_ASSERT_ARG(repo);
GIT_ASSERT_ARG(remote);
if ((error = ensure_remote_name_is_valid(remote)) < 0)
return error;
if ((error = git_repository_config__weakptr(&cfg, repo)) < 0)
return error;
if ((error = git_buf_printf(&buf, pattern, remote)) < 0)
return error;
if (url) {
if ((error = canonicalize_url(&canonical_url, url)) < 0)
goto cleanup;
error = git_config_set_string(cfg, buf.ptr, url);
} else {
error = git_config_delete_entry(cfg, buf.ptr);
}
cleanup:
git_buf_dispose(&canonical_url);
git_buf_dispose(&buf);
return error;
}
int git_remote_set_url(git_repository *repo, const char *remote, const char *url)
{
return set_url(repo, remote, CONFIG_URL_FMT, url);
}
const char *git_remote_pushurl(const git_remote *remote)
{
GIT_ASSERT_ARG_WITH_RETVAL(remote, NULL);
return remote->pushurl;
}
int git_remote_set_instance_pushurl(git_remote *remote, const char *url)
{
char *tmp;
GIT_ASSERT_ARG(remote);
GIT_ASSERT_ARG(url);
if ((tmp = git__strdup(url)) == NULL)
return -1;
git__free(remote->pushurl);
remote->pushurl = tmp;
return 0;
}
int git_remote_set_pushurl(git_repository *repo, const char *remote, const char *url)
{
return set_url(repo, remote, CONFIG_PUSHURL_FMT, url);
}
static int resolve_url(
git_buf *resolved_url,
const char *url,
int direction,
const git_remote_callbacks *callbacks)
{
#ifdef GIT_DEPRECATE_HARD
GIT_UNUSED(direction);
GIT_UNUSED(callbacks);
#else
int status, error;
if (callbacks && callbacks->resolve_url) {
git_buf_clear(resolved_url);
status = callbacks->resolve_url(resolved_url, url, direction, callbacks->payload);
if (status != GIT_PASSTHROUGH) {
git_error_set_after_callback_function(status, "git_resolve_url_cb");
if ((error = git_buf_sanitize(resolved_url)) < 0)
return error;
return status;
}
}
#endif
return git_buf_sets(resolved_url, url);
}
int git_remote__urlfordirection(
git_buf *url_out,
struct git_remote *remote,
int direction,
const git_remote_callbacks *callbacks)
{
const char *url = NULL;
GIT_ASSERT_ARG(remote);
GIT_ASSERT_ARG(direction == GIT_DIRECTION_FETCH || direction == GIT_DIRECTION_PUSH);
if (callbacks && callbacks->remote_ready) {
int status = callbacks->remote_ready(remote, direction, callbacks->payload);
if (status != 0 && status != GIT_PASSTHROUGH) {
git_error_set_after_callback_function(status, "git_remote_ready_cb");
return status;
}
}
if (direction == GIT_DIRECTION_FETCH)
url = remote->url;
else if (direction == GIT_DIRECTION_PUSH)
url = remote->pushurl ? remote->pushurl : remote->url;
if (!url) {
git_error_set(GIT_ERROR_INVALID,
"malformed remote '%s' - missing %s URL",
remote->name ? remote->name : "(anonymous)",
direction == GIT_DIRECTION_FETCH ? "fetch" : "push");
return GIT_EINVALID;
}
return resolve_url(url_out, url, direction, callbacks);
}
static int remote_transport_set_callbacks(git_transport *t, const git_remote_callbacks *cbs)
{
if (!t->set_callbacks || !cbs)
return 0;
return t->set_callbacks(t, cbs->sideband_progress, NULL,
cbs->certificate_check, cbs->payload);
}
static int set_transport_custom_headers(git_transport *t, const git_strarray *custom_headers)
{
if (!t->set_custom_headers)
return 0;
return t->set_custom_headers(t, custom_headers);
}
int git_remote__connect(git_remote *remote, git_direction direction, const git_remote_callbacks *callbacks, const git_remote_connection_opts *conn)
{
git_transport *t;
git_buf url = GIT_BUF_INIT;
int flags = GIT_TRANSPORTFLAGS_NONE;
int error;
void *payload = NULL;
git_credential_acquire_cb credentials = NULL;
git_transport_cb transport = NULL;
GIT_ASSERT_ARG(remote);
if (callbacks) {
GIT_ERROR_CHECK_VERSION(callbacks, GIT_REMOTE_CALLBACKS_VERSION, "git_remote_callbacks");
credentials = callbacks->credentials;
transport = callbacks->transport;
payload = callbacks->payload;
}
if (conn->proxy)
GIT_ERROR_CHECK_VERSION(conn->proxy, GIT_PROXY_OPTIONS_VERSION, "git_proxy_options");
t = remote->transport;
if ((error = git_remote__urlfordirection(&url, remote, direction, callbacks)) < 0)
goto on_error;
/* If we don't have a transport object yet, and the caller specified a
* custom transport factory, use that */
if (!t && transport &&
(error = transport(&t, remote, payload)) < 0)
goto on_error;
/* If we still don't have a transport, then use the global
* transport registrations which map URI schemes to transport factories */
if (!t && (error = git_transport_new(&t, remote, url.ptr)) < 0)
goto on_error;
if ((error = set_transport_custom_headers(t, conn->custom_headers)) != 0)
goto on_error;
if ((error = remote_transport_set_callbacks(t, callbacks)) < 0 ||
(error = t->connect(t, url.ptr, credentials, payload, conn->proxy, direction, flags)) != 0)
goto on_error;
remote->transport = t;
git_buf_dispose(&url);
return 0;
on_error:
if (t)
t->free(t);
git_buf_dispose(&url);
if (t == remote->transport)
remote->transport = NULL;
return error;
}
int git_remote_connect(git_remote *remote, git_direction direction, const git_remote_callbacks *callbacks, const git_proxy_options *proxy, const git_strarray *custom_headers)
{
git_remote_connection_opts conn;
conn.proxy = proxy;
conn.custom_headers = custom_headers;
return git_remote__connect(remote, direction, callbacks, &conn);
}
int git_remote_ls(const git_remote_head ***out, size_t *size, git_remote *remote)
{
GIT_ASSERT_ARG(remote);
if (!remote->transport) {
git_error_set(GIT_ERROR_NET, "this remote has never connected");
return -1;
}
return remote->transport->ls(out, size, remote->transport);
}
static int lookup_config(char **out, git_config *cfg, const char *name)
{
git_config_entry *ce = NULL;
int error;
if ((error = git_config__lookup_entry(&ce, cfg, name, false)) < 0)
return error;
if (ce && ce->value) {
*out = git__strdup(ce->value);
GIT_ERROR_CHECK_ALLOC(*out);
} else {
error = GIT_ENOTFOUND;
}
git_config_entry_free(ce);
return error;
}
static void url_config_trim(git_net_url *url)
{
size_t len = strlen(url->path);
if (url->path[len - 1] == '/') {
len--;
} else {
while (len && url->path[len - 1] != '/')
len--;
}
url->path[len] = '\0';
}
static int http_proxy_config(char **out, git_remote *remote, git_net_url *url)
{
git_config *cfg = NULL;
git_buf buf = GIT_BUF_INIT;
git_net_url lookup_url = GIT_NET_URL_INIT;
int error;
if ((error = git_net_url_dup(&lookup_url, url)) < 0)
goto done;
if (remote->repo) {
if ((error = git_repository_config(&cfg, remote->repo)) < 0)
goto done;
} else {
if ((error = git_config_open_default(&cfg)) < 0)
goto done;
}
/* remote.<name>.proxy config setting */
if (remote->name && remote->name[0]) {
git_buf_clear(&buf);
if ((error = git_buf_printf(&buf, "remote.%s.proxy", remote->name)) < 0 ||
(error = lookup_config(out, cfg, buf.ptr)) != GIT_ENOTFOUND)
goto done;
}
while (true) {
git_buf_clear(&buf);
if ((error = git_buf_puts(&buf, "http.")) < 0 ||
(error = git_net_url_fmt(&buf, &lookup_url)) < 0 ||
(error = git_buf_puts(&buf, ".proxy")) < 0 ||
(error = lookup_config(out, cfg, buf.ptr)) != GIT_ENOTFOUND)
goto done;
if (! lookup_url.path[0])
break;
url_config_trim(&lookup_url);
}
git_buf_clear(&buf);
error = lookup_config(out, cfg, "http.proxy");
done:
git_config_free(cfg);
git_buf_dispose(&buf);
git_net_url_dispose(&lookup_url);
return error;
}
static int http_proxy_env(char **out, git_remote *remote, git_net_url *url)
{
git_buf proxy_env = GIT_BUF_INIT, no_proxy_env = GIT_BUF_INIT;
bool use_ssl = (strcmp(url->scheme, "https") == 0);
int error;
GIT_UNUSED(remote);
/* http_proxy / https_proxy environment variables */
error = git__getenv(&proxy_env, use_ssl ? "https_proxy" : "http_proxy");
/* try uppercase environment variables */
if (error == GIT_ENOTFOUND)
error = git__getenv(&proxy_env, use_ssl ? "HTTPS_PROXY" : "HTTP_PROXY");
if (error)
goto done;
/* no_proxy/NO_PROXY environment variables */
error = git__getenv(&no_proxy_env, "no_proxy");
if (error == GIT_ENOTFOUND)
error = git__getenv(&no_proxy_env, "NO_PROXY");
if (error && error != GIT_ENOTFOUND)
goto done;
if (!git_net_url_matches_pattern_list(url, no_proxy_env.ptr))
*out = git_buf_detach(&proxy_env);
else
error = GIT_ENOTFOUND;
done:
git_buf_dispose(&proxy_env);
git_buf_dispose(&no_proxy_env);
return error;
}
int git_remote__http_proxy(char **out, git_remote *remote, git_net_url *url)
{
int error;
GIT_ASSERT_ARG(out);
GIT_ASSERT_ARG(remote);
*out = NULL;
/*
* Go through the possible sources for proxy configuration,
* Examine the various git config options first, then
* consult environment variables.
*/
if ((error = http_proxy_config(out, remote, url)) != GIT_ENOTFOUND ||
(error = http_proxy_env(out, remote, url)) != GIT_ENOTFOUND)
return error;
return 0;
}
/* DWIM `refspecs` based on `refs` and append the output to `out` */
static int dwim_refspecs(git_vector *out, git_vector *refspecs, git_vector *refs)
{
size_t i;
git_refspec *spec;
git_vector_foreach(refspecs, i, spec) {
if (git_refspec__dwim_one(out, spec, refs) < 0)
return -1;
}
return 0;
}
static void free_refspecs(git_vector *vec)
{
size_t i;
git_refspec *spec;
git_vector_foreach(vec, i, spec) {
git_refspec__dispose(spec);
git__free(spec);
}
git_vector_clear(vec);
}
static int remote_head_cmp(const void *_a, const void *_b)
{
const git_remote_head *a = (git_remote_head *) _a;
const git_remote_head *b = (git_remote_head *) _b;
return git__strcmp_cb(a->name, b->name);
}
static int ls_to_vector(git_vector *out, git_remote *remote)
{
git_remote_head **heads;
size_t heads_len, i;
if (git_remote_ls((const git_remote_head ***)&heads, &heads_len, remote) < 0)
return -1;
if (git_vector_init(out, heads_len, remote_head_cmp) < 0)
return -1;
for (i = 0; i < heads_len; i++) {
if (git_vector_insert(out, heads[i]) < 0)
return -1;
}
return 0;
}
int git_remote_download(git_remote *remote, const git_strarray *refspecs, const git_fetch_options *opts)
{
int error = -1;
size_t i;
git_vector *to_active, specs = GIT_VECTOR_INIT, refs = GIT_VECTOR_INIT;
const git_remote_callbacks *cbs = NULL;
const git_strarray *custom_headers = NULL;
const git_proxy_options *proxy = NULL;
GIT_ASSERT_ARG(remote);
if (!remote->repo) {
git_error_set(GIT_ERROR_INVALID, "cannot download detached remote");
return -1;
}
if (opts) {
GIT_ERROR_CHECK_VERSION(&opts->callbacks, GIT_REMOTE_CALLBACKS_VERSION, "git_remote_callbacks");
cbs = &opts->callbacks;
custom_headers = &opts->custom_headers;
GIT_ERROR_CHECK_VERSION(&opts->proxy_opts, GIT_PROXY_OPTIONS_VERSION, "git_proxy_options");
proxy = &opts->proxy_opts;
}
if (!git_remote_connected(remote) &&
(error = git_remote_connect(remote, GIT_DIRECTION_FETCH, cbs, proxy, custom_headers)) < 0)
goto on_error;
if (ls_to_vector(&refs, remote) < 0)
return -1;
if ((git_vector_init(&specs, 0, NULL)) < 0)
goto on_error;
remote->passed_refspecs = 0;
if (!refspecs || !refspecs->count) {
to_active = &remote->refspecs;
} else {
for (i = 0; i < refspecs->count; i++) {
if ((error = add_refspec_to(&specs, refspecs->strings[i], true)) < 0)
goto on_error;
}
to_active = &specs;
remote->passed_refspecs = 1;
}
free_refspecs(&remote->passive_refspecs);
if ((error = dwim_refspecs(&remote->passive_refspecs, &remote->refspecs, &refs)) < 0)
goto on_error;
free_refspecs(&remote->active_refspecs);
error = dwim_refspecs(&remote->active_refspecs, to_active, &refs);
git_vector_free(&refs);
free_refspecs(&specs);
git_vector_free(&specs);
if (error < 0)
return error;
if (remote->push) {
git_push_free(remote->push);
remote->push = NULL;
}
if ((error = git_fetch_negotiate(remote, opts)) < 0)
return error;
return git_fetch_download_pack(remote, cbs);
on_error:
git_vector_free(&refs);
free_refspecs(&specs);
git_vector_free(&specs);
return error;
}
int git_remote_fetch(
git_remote *remote,
const git_strarray *refspecs,
const git_fetch_options *opts,
const char *reflog_message)
{
int error, update_fetchhead = 1;
git_remote_autotag_option_t tagopt = remote->download_tags;
bool prune = false;
git_buf reflog_msg_buf = GIT_BUF_INIT;
const git_remote_callbacks *cbs = NULL;
git_remote_connection_opts conn = GIT_REMOTE_CONNECTION_OPTIONS_INIT;
if (opts) {
GIT_ERROR_CHECK_VERSION(&opts->callbacks, GIT_REMOTE_CALLBACKS_VERSION, "git_remote_callbacks");
cbs = &opts->callbacks;
conn.custom_headers = &opts->custom_headers;
update_fetchhead = opts->update_fetchhead;
tagopt = opts->download_tags;
GIT_ERROR_CHECK_VERSION(&opts->proxy_opts, GIT_PROXY_OPTIONS_VERSION, "git_proxy_options");
conn.proxy = &opts->proxy_opts;
}
/* Connect and download everything */
if ((error = git_remote__connect(remote, GIT_DIRECTION_FETCH, cbs, &conn)) != 0)
return error;
error = git_remote_download(remote, refspecs, opts);
/* We don't need to be connected anymore */
git_remote_disconnect(remote);
/* If the download failed, return the error */
if (error != 0)
return error;
/* Default reflog message */
if (reflog_message)
git_buf_sets(&reflog_msg_buf, reflog_message);
else {
git_buf_printf(&reflog_msg_buf, "fetch %s",
remote->name ? remote->name : remote->url);
}
/* Create "remote/foo" branches for all remote branches */
error = git_remote_update_tips(remote, cbs, update_fetchhead, tagopt, git_buf_cstr(&reflog_msg_buf));
git_buf_dispose(&reflog_msg_buf);
if (error < 0)
return error;
if (opts && opts->prune == GIT_FETCH_PRUNE)
prune = true;
else if (opts && opts->prune == GIT_FETCH_PRUNE_UNSPECIFIED && remote->prune_refs)
prune = true;
else if (opts && opts->prune == GIT_FETCH_NO_PRUNE)
prune = false;
else
prune = remote->prune_refs;
if (prune)
error = git_remote_prune(remote, cbs);
return error;
}
static int remote_head_for_fetchspec_src(git_remote_head **out, git_vector *update_heads, const char *fetchspec_src)
{
unsigned int i;
git_remote_head *remote_ref;
GIT_ASSERT_ARG(update_heads);
GIT_ASSERT_ARG(fetchspec_src);
*out = NULL;
git_vector_foreach(update_heads, i, remote_ref) {
if (strcmp(remote_ref->name, fetchspec_src) == 0) {
*out = remote_ref;
break;
}
}
return 0;
}
static int ref_to_update(int *update, git_buf *remote_name, git_remote *remote, git_refspec *spec, const char *ref_name)
{
int error = 0;
git_repository *repo;
git_buf upstream_remote = GIT_BUF_INIT;
git_buf upstream_name = GIT_BUF_INIT;
repo = git_remote_owner(remote);
if ((!git_reference__is_branch(ref_name)) ||
!git_remote_name(remote) ||
(error = git_branch_upstream_remote(&upstream_remote, repo, ref_name) < 0) ||
git__strcmp(git_remote_name(remote), git_buf_cstr(&upstream_remote)) ||
(error = git_branch_upstream_name(&upstream_name, repo, ref_name)) < 0 ||
!git_refspec_dst_matches(spec, git_buf_cstr(&upstream_name)) ||
(error = git_refspec_rtransform(remote_name, spec, upstream_name.ptr)) < 0) {
/* Not an error if there is no upstream */
if (error == GIT_ENOTFOUND) {
git_error_clear();
error = 0;
}
*update = 0;
} else {
*update = 1;
}
git_buf_dispose(&upstream_remote);
git_buf_dispose(&upstream_name);
return error;
}
static int remote_head_for_ref(git_remote_head **out, git_remote *remote, git_refspec *spec, git_vector *update_heads, git_reference *ref)
{
git_reference *resolved_ref = NULL;
git_buf remote_name = GIT_BUF_INIT;
git_config *config = NULL;
const char *ref_name;
int error = 0, update;
GIT_ASSERT_ARG(out);
GIT_ASSERT_ARG(spec);
GIT_ASSERT_ARG(ref);
*out = NULL;
error = git_reference_resolve(&resolved_ref, ref);
/* If we're in an unborn branch, let's pretend nothing happened */
if (error == GIT_ENOTFOUND && git_reference_type(ref) == GIT_REFERENCE_SYMBOLIC) {
ref_name = git_reference_symbolic_target(ref);
error = 0;
} else {
ref_name = git_reference_name(resolved_ref);
}
/*
* The ref name may be unresolvable - perhaps it's pointing to
* something invalid. In this case, there is no remote head for
* this ref.
*/
if (!ref_name) {
error = 0;
goto cleanup;
}
if ((error = ref_to_update(&update, &remote_name, remote, spec, ref_name)) < 0)
goto cleanup;
if (update)
error = remote_head_for_fetchspec_src(out, update_heads, git_buf_cstr(&remote_name));
cleanup:
git_buf_dispose(&remote_name);
git_reference_free(resolved_ref);
git_config_free(config);
return error;
}
static int git_remote_write_fetchhead(git_remote *remote, git_refspec *spec, git_vector *update_heads)
{
git_reference *head_ref = NULL;
git_fetchhead_ref *fetchhead_ref;
git_remote_head *remote_ref, *merge_remote_ref;
git_vector fetchhead_refs;
bool include_all_fetchheads;
unsigned int i = 0;
int error = 0;
GIT_ASSERT_ARG(remote);
/* no heads, nothing to do */
if (update_heads->length == 0)
return 0;
if (git_vector_init(&fetchhead_refs, update_heads->length, git_fetchhead_ref_cmp) < 0)
return -1;
/* Iff refspec is * (but not subdir slash star), include tags */
include_all_fetchheads = (strcmp(GIT_REFS_HEADS_DIR "*", git_refspec_src(spec)) == 0);
/* Determine what to merge: if refspec was a wildcard, just use HEAD */
if (git_refspec_is_wildcard(spec)) {
if ((error = git_reference_lookup(&head_ref, remote->repo, GIT_HEAD_FILE)) < 0 ||
(error = remote_head_for_ref(&merge_remote_ref, remote, spec, update_heads, head_ref)) < 0)
goto cleanup;
} else {
/* If we're fetching a single refspec, that's the only thing that should be in FETCH_HEAD. */
if ((error = remote_head_for_fetchspec_src(&merge_remote_ref, update_heads, git_refspec_src(spec))) < 0)
goto cleanup;
}
/* Create the FETCH_HEAD file */
git_vector_foreach(update_heads, i, remote_ref) {
int merge_this_fetchhead = (merge_remote_ref == remote_ref);
if (!include_all_fetchheads &&
!git_refspec_src_matches(spec, remote_ref->name) &&
!merge_this_fetchhead)
continue;
if (git_fetchhead_ref_create(&fetchhead_ref,
&remote_ref->oid,
merge_this_fetchhead,
remote_ref->name,
git_remote_url(remote)) < 0)
goto cleanup;
if (git_vector_insert(&fetchhead_refs, fetchhead_ref) < 0)
goto cleanup;
}
git_fetchhead_write(remote->repo, &fetchhead_refs);
cleanup:
for (i = 0; i < fetchhead_refs.length; ++i)
git_fetchhead_ref_free(fetchhead_refs.contents[i]);
git_vector_free(&fetchhead_refs);
git_reference_free(head_ref);
return error;
}
/**
* Generate a list of candidates for pruning by getting a list of
* references which match the rhs of an active refspec.
*/
static int prune_candidates(git_vector *candidates, git_remote *remote)
{
git_strarray arr = { 0 };
size_t i;
int error;
if ((error = git_reference_list(&arr, remote->repo)) < 0)
return error;
for (i = 0; i < arr.count; i++) {
const char *refname = arr.strings[i];
char *refname_dup;
if (!git_remote__matching_dst_refspec(remote, refname))
continue;
refname_dup = git__strdup(refname);
GIT_ERROR_CHECK_ALLOC(refname_dup);
if ((error = git_vector_insert(candidates, refname_dup)) < 0)
goto out;
}
out:
git_strarray_dispose(&arr);
return error;
}
static int find_head(const void *_a, const void *_b)
{
git_remote_head *a = (git_remote_head *) _a;
git_remote_head *b = (git_remote_head *) _b;
return strcmp(a->name, b->name);
}
int git_remote_prune(git_remote *remote, const git_remote_callbacks *callbacks)
{
size_t i, j;
git_vector remote_refs = GIT_VECTOR_INIT;
git_vector candidates = GIT_VECTOR_INIT;
const git_refspec *spec;
const char *refname;
int error;
git_oid zero_id = {{ 0 }};
if (callbacks)
GIT_ERROR_CHECK_VERSION(callbacks, GIT_REMOTE_CALLBACKS_VERSION, "git_remote_callbacks");
if ((error = ls_to_vector(&remote_refs, remote)) < 0)
goto cleanup;
git_vector_set_cmp(&remote_refs, find_head);
if ((error = prune_candidates(&candidates, remote)) < 0)
goto cleanup;
/*
* Remove those entries from the candidate list for which we
* can find a remote reference in at least one refspec.
*/
git_vector_foreach(&candidates, i, refname) {
git_vector_foreach(&remote->active_refspecs, j, spec) {
git_buf buf = GIT_BUF_INIT;
size_t pos;
char *src_name;
git_remote_head key = {0};
if (!git_refspec_dst_matches(spec, refname))
continue;
if ((error = git_refspec_rtransform(&buf, spec, refname)) < 0)
goto cleanup;
key.name = (char *) git_buf_cstr(&buf);
error = git_vector_bsearch(&pos, &remote_refs, &key);
git_buf_dispose(&buf);
if (error < 0 && error != GIT_ENOTFOUND)
goto cleanup;
if (error == GIT_ENOTFOUND)
continue;
/* If we did find a source, remove it from the candidates. */
if ((error = git_vector_set((void **) &src_name, &candidates, i, NULL)) < 0)
goto cleanup;
git__free(src_name);
break;
}
}
/*
* For those candidates still left in the list, we need to
* remove them. We do not remove symrefs, as those are for
* stuff like origin/HEAD which will never match, but we do
* not want to remove them.
*/
git_vector_foreach(&candidates, i, refname) {
git_reference *ref;
git_oid id;
if (refname == NULL)
continue;
error = git_reference_lookup(&ref, remote->repo, refname);
/* as we want it gone, let's not consider this an error */
if (error == GIT_ENOTFOUND)
continue;
if (error < 0)
goto cleanup;
if (git_reference_type(ref) == GIT_REFERENCE_SYMBOLIC) {
git_reference_free(ref);
continue;
}
git_oid_cpy(&id, git_reference_target(ref));
error = git_reference_delete(ref);
git_reference_free(ref);
if (error < 0)
goto cleanup;
if (callbacks && callbacks->update_tips)
error = callbacks->update_tips(refname, &id, &zero_id, callbacks->payload);
if (error < 0)
goto cleanup;
}
cleanup:
git_vector_free(&remote_refs);
git_vector_free_deep(&candidates);
return error;
}
static int update_tips_for_spec(
git_remote *remote,
const git_remote_callbacks *callbacks,
int update_fetchhead,
git_remote_autotag_option_t tagopt,
git_refspec *spec,
git_vector *refs,
const char *log_message)
{
int error = 0, autotag, valid;
unsigned int i = 0;
git_buf refname = GIT_BUF_INIT;
git_oid old;
git_odb *odb;
git_remote_head *head;
git_reference *ref;
git_refspec tagspec;
git_vector update_heads;
GIT_ASSERT_ARG(remote);
if (git_repository_odb__weakptr(&odb, remote->repo) < 0)
return -1;
if (git_refspec__parse(&tagspec, GIT_REFSPEC_TAGS, true) < 0)
return -1;
/* Make a copy of the transport's refs */
if (git_vector_init(&update_heads, 16, NULL) < 0)
return -1;
for (; i < refs->length; ++i) {
head = git_vector_get(refs, i);
autotag = 0;
git_buf_clear(&refname);
/* Ignore malformed ref names (which also saves us from tag^{} */
if (git_reference_name_is_valid(&valid, head->name) < 0)
goto on_error;
if (!valid)
continue;
/* If we have a tag, see if the auto-follow rules say to update it */
if (git_refspec_src_matches(&tagspec, head->name)) {
if (tagopt != GIT_REMOTE_DOWNLOAD_TAGS_NONE) {
if (tagopt == GIT_REMOTE_DOWNLOAD_TAGS_AUTO)
autotag = 1;
git_buf_clear(&refname);
if (git_buf_puts(&refname, head->name) < 0)
goto on_error;
}
}
/* If we didn't want to auto-follow the tag, check if the refspec matches */
if (!autotag && git_refspec_src_matches(spec, head->name)) {
if (spec->dst) {
if (git_refspec_transform(&refname, spec, head->name) < 0)
goto on_error;
} else {
/*
* no rhs mans store it in FETCH_HEAD, even if we don't
update anything else.
*/
if ((error = git_vector_insert(&update_heads, head)) < 0)
goto on_error;
continue;
}
}
/* If we still don't have a refname, we don't want it */
if (git_buf_len(&refname) == 0) {
continue;
}
/* In autotag mode, only create tags for objects already in db */
if (autotag && !git_odb_exists(odb, &head->oid))
continue;
if (!autotag && git_vector_insert(&update_heads, head) < 0)
goto on_error;
error = git_reference_name_to_id(&old, remote->repo, refname.ptr);
if (error < 0 && error != GIT_ENOTFOUND)
goto on_error;
if (!(error || error == GIT_ENOTFOUND)
&& !spec->force
&& !git_graph_descendant_of(remote->repo, &head->oid, &old))
continue;
if (error == GIT_ENOTFOUND) {
memset(&old, 0, GIT_OID_RAWSZ);
if (autotag && git_vector_insert(&update_heads, head) < 0)
goto on_error;
}
if (!git_oid__cmp(&old, &head->oid))
continue;
/* In autotag mode, don't overwrite any locally-existing tags */
error = git_reference_create(&ref, remote->repo, refname.ptr, &head->oid, !autotag,
log_message);
if (error == GIT_EEXISTS)
continue;
if (error < 0)
goto on_error;
git_reference_free(ref);
if (callbacks && callbacks->update_tips != NULL) {
if (callbacks->update_tips(refname.ptr, &old, &head->oid, callbacks->payload) < 0)
goto on_error;
}
}
if (update_fetchhead &&
(error = git_remote_write_fetchhead(remote, spec, &update_heads)) < 0)
goto on_error;
git_vector_free(&update_heads);
git_refspec__dispose(&tagspec);
git_buf_dispose(&refname);
return 0;
on_error:
git_vector_free(&update_heads);
git_refspec__dispose(&tagspec);
git_buf_dispose(&refname);
return -1;
}
/**
* Iteration over the three vectors, with a pause whenever we find a match
*
* On each stop, we store the iteration stat in the inout i,j,k
* parameters, and return the currently matching passive refspec as
* well as the head which we matched.
*/
static int next_head(const git_remote *remote, git_vector *refs,
git_refspec **out_spec, git_remote_head **out_head,
size_t *out_i, size_t *out_j, size_t *out_k)
{
const git_vector *active, *passive;
git_remote_head *head;
git_refspec *spec, *passive_spec;
size_t i, j, k;
int valid;
active = &remote->active_refspecs;
passive = &remote->passive_refspecs;
i = *out_i;
j = *out_j;
k = *out_k;
for (; i < refs->length; i++) {
head = git_vector_get(refs, i);
if (git_reference_name_is_valid(&valid, head->name) < 0)
return -1;
if (!valid)
continue;
for (; j < active->length; j++) {
spec = git_vector_get(active, j);
if (!git_refspec_src_matches(spec, head->name))
continue;
for (; k < passive->length; k++) {
passive_spec = git_vector_get(passive, k);
if (!git_refspec_src_matches(passive_spec, head->name))
continue;
*out_spec = passive_spec;
*out_head = head;
*out_i = i;
*out_j = j;
*out_k = k + 1;
return 0;
}
k = 0;
}
j = 0;
}
return GIT_ITEROVER;
}
static int opportunistic_updates(const git_remote *remote, const git_remote_callbacks *callbacks,
git_vector *refs, const char *msg)
{
size_t i, j, k;
git_refspec *spec;
git_remote_head *head;
git_reference *ref;
git_buf refname = GIT_BUF_INIT;
int error = 0;
i = j = k = 0;
while ((error = next_head(remote, refs, &spec, &head, &i, &j, &k)) == 0) {
git_oid old = {{ 0 }};
/*
* If we got here, there is a refspec which was used
* for fetching which matches the source of one of the
* passive refspecs, so we should update that
* remote-tracking branch, but not add it to
* FETCH_HEAD
*/
git_buf_clear(&refname);
if ((error = git_refspec_transform(&refname, spec, head->name)) < 0)
goto cleanup;
error = git_reference_name_to_id(&old, remote->repo, refname.ptr);
if (error < 0 && error != GIT_ENOTFOUND)
goto cleanup;
if (!git_oid_cmp(&old, &head->oid))
continue;
/* If we did find a current reference, make sure we haven't lost a race */
if (error)
error = git_reference_create(&ref, remote->repo, refname.ptr, &head->oid, true, msg);
else
error = git_reference_create_matching(&ref, remote->repo, refname.ptr, &head->oid, true, &old, msg);
git_reference_free(ref);
if (error < 0)
goto cleanup;
if (callbacks && callbacks->update_tips != NULL) {
if (callbacks->update_tips(refname.ptr, &old, &head->oid, callbacks->payload) < 0)
goto cleanup;
}
}
if (error == GIT_ITEROVER)
error = 0;
cleanup:
git_buf_dispose(&refname);
return error;
}
static int truncate_fetch_head(const char *gitdir)
{
git_buf path = GIT_BUF_INIT;
int error;
if ((error = git_buf_joinpath(&path, gitdir, GIT_FETCH_HEAD_FILE)) < 0)
return error;
error = git_futils_truncate(path.ptr, GIT_REFS_FILE_MODE);
git_buf_dispose(&path);
return error;
}
int git_remote_update_tips(
git_remote *remote,
const git_remote_callbacks *callbacks,
int update_fetchhead,
git_remote_autotag_option_t download_tags,
const char *reflog_message)
{
git_refspec *spec, tagspec;
git_vector refs = GIT_VECTOR_INIT;
git_remote_autotag_option_t tagopt;
int error;
size_t i;
/* push has its own logic hidden away in the push object */
if (remote->push) {
return git_push_update_tips(remote->push, callbacks);
}
if (git_refspec__parse(&tagspec, GIT_REFSPEC_TAGS, true) < 0)
return -1;
if ((error = ls_to_vector(&refs, remote)) < 0)
goto out;
if (download_tags == GIT_REMOTE_DOWNLOAD_TAGS_UNSPECIFIED)
tagopt = remote->download_tags;
else
tagopt = download_tags;
if ((error = truncate_fetch_head(git_repository_path(remote->repo))) < 0)
goto out;
if (tagopt == GIT_REMOTE_DOWNLOAD_TAGS_ALL) {
if ((error = update_tips_for_spec(remote, callbacks, update_fetchhead, tagopt, &tagspec, &refs, reflog_message)) < 0)
goto out;
}
git_vector_foreach(&remote->active_refspecs, i, spec) {
if (spec->push)
continue;
if ((error = update_tips_for_spec(remote, callbacks, update_fetchhead, tagopt, spec, &refs, reflog_message)) < 0)
goto out;
}
/* Only try to do opportunistic updates if the refpec lists differ. */
if (remote->passed_refspecs)
error = opportunistic_updates(remote, callbacks, &refs, reflog_message);
out:
git_vector_free(&refs);
git_refspec__dispose(&tagspec);
return error;
}
int git_remote_connected(const git_remote *remote)
{
GIT_ASSERT_ARG(remote);
if (!remote->transport || !remote->transport->is_connected)
return 0;
/* Ask the transport if it's connected. */
return remote->transport->is_connected(remote->transport);
}
int git_remote_stop(git_remote *remote)
{
GIT_ASSERT_ARG(remote);
if (remote->transport && remote->transport->cancel)
remote->transport->cancel(remote->transport);
return 0;
}
int git_remote_disconnect(git_remote *remote)
{
GIT_ASSERT_ARG(remote);
if (git_remote_connected(remote))
remote->transport->close(remote->transport);
return 0;
}
void git_remote_free(git_remote *remote)
{
if (remote == NULL)
return;
if (remote->transport != NULL) {
git_remote_disconnect(remote);
remote->transport->free(remote->transport);
remote->transport = NULL;
}
git_vector_free(&remote->refs);
free_refspecs(&remote->refspecs);
git_vector_free(&remote->refspecs);
free_refspecs(&remote->active_refspecs);
git_vector_free(&remote->active_refspecs);
free_refspecs(&remote->passive_refspecs);
git_vector_free(&remote->passive_refspecs);
git_push_free(remote->push);
git__free(remote->url);
git__free(remote->pushurl);
git__free(remote->name);
git__free(remote);
}
static int remote_list_cb(const git_config_entry *entry, void *payload)
{
git_vector *list = payload;
const char *name = entry->name + strlen("remote.");
size_t namelen = strlen(name);
char *remote_name;
/* we know name matches "remote.<stuff>.(push)?url" */
if (!strcmp(&name[namelen - 4], ".url"))
remote_name = git__strndup(name, namelen - 4); /* strip ".url" */
else
remote_name = git__strndup(name, namelen - 8); /* strip ".pushurl" */
GIT_ERROR_CHECK_ALLOC(remote_name);
return git_vector_insert(list, remote_name);
}
int git_remote_list(git_strarray *remotes_list, git_repository *repo)
{
int error;
git_config *cfg;
git_vector list = GIT_VECTOR_INIT;
if ((error = git_repository_config__weakptr(&cfg, repo)) < 0)
return error;
if ((error = git_vector_init(&list, 4, git__strcmp_cb)) < 0)
return error;
error = git_config_foreach_match(
cfg, "^remote\\..*\\.(push)?url$", remote_list_cb, &list);
if (error < 0) {
git_vector_free_deep(&list);
return error;
}
git_vector_uniq(&list, git__free);
remotes_list->strings =
(char **)git_vector_detach(&remotes_list->count, NULL, &list);
return 0;
}
const git_indexer_progress *git_remote_stats(git_remote *remote)
{
GIT_ASSERT_ARG_WITH_RETVAL(remote, NULL);
return &remote->stats;
}
git_remote_autotag_option_t git_remote_autotag(const git_remote *remote)
{
return remote->download_tags;
}
int git_remote_set_autotag(git_repository *repo, const char *remote, git_remote_autotag_option_t value)
{
git_buf var = GIT_BUF_INIT;
git_config *config;
int error;
GIT_ASSERT_ARG(repo && remote);
if ((error = ensure_remote_name_is_valid(remote)) < 0)
return error;
if ((error = git_repository_config__weakptr(&config, repo)) < 0)
return error;
if ((error = git_buf_printf(&var, CONFIG_TAGOPT_FMT, remote)))
return error;
switch (value) {
case GIT_REMOTE_DOWNLOAD_TAGS_NONE:
error = git_config_set_string(config, var.ptr, "--no-tags");
break;
case GIT_REMOTE_DOWNLOAD_TAGS_ALL:
error = git_config_set_string(config, var.ptr, "--tags");
break;
case GIT_REMOTE_DOWNLOAD_TAGS_AUTO:
error = git_config_delete_entry(config, var.ptr);
if (error == GIT_ENOTFOUND)
error = 0;
break;
default:
git_error_set(GIT_ERROR_INVALID, "invalid value for the tagopt setting");
error = -1;
}
git_buf_dispose(&var);
return error;
}
int git_remote_prune_refs(const git_remote *remote)
{
return remote->prune_refs;
}
static int rename_remote_config_section(
git_repository *repo,
const char *old_name,
const char *new_name)
{
git_buf old_section_name = GIT_BUF_INIT,
new_section_name = GIT_BUF_INIT;
int error = -1;
if (git_buf_printf(&old_section_name, "remote.%s", old_name) < 0)
goto cleanup;
if (new_name &&
(git_buf_printf(&new_section_name, "remote.%s", new_name) < 0))
goto cleanup;
error = git_config_rename_section(
repo,
git_buf_cstr(&old_section_name),
new_name ? git_buf_cstr(&new_section_name) : NULL);
cleanup:
git_buf_dispose(&old_section_name);
git_buf_dispose(&new_section_name);
return error;
}
struct update_data {
git_config *config;
const char *old_remote_name;
const char *new_remote_name;
};
static int update_config_entries_cb(
const git_config_entry *entry,
void *payload)
{
struct update_data *data = (struct update_data *)payload;
if (strcmp(entry->value, data->old_remote_name))
return 0;
return git_config_set_string(
data->config, entry->name, data->new_remote_name);
}
static int update_branch_remote_config_entry(
git_repository *repo,
const char *old_name,
const char *new_name)
{
int error;
struct update_data data = { NULL };
if ((error = git_repository_config__weakptr(&data.config, repo)) < 0)
return error;
data.old_remote_name = old_name;
data.new_remote_name = new_name;
return git_config_foreach_match(
data.config, "branch\\..+\\.remote", update_config_entries_cb, &data);
}
static int rename_one_remote_reference(
git_reference *reference_in,
const char *old_remote_name,
const char *new_remote_name)
{
int error;
git_reference *ref = NULL, *dummy = NULL;
git_buf namespace = GIT_BUF_INIT, old_namespace = GIT_BUF_INIT;
git_buf new_name = GIT_BUF_INIT;
git_buf log_message = GIT_BUF_INIT;
size_t pfx_len;
const char *target;
if ((error = git_buf_printf(&namespace, GIT_REFS_REMOTES_DIR "%s/", new_remote_name)) < 0)
return error;
pfx_len = strlen(GIT_REFS_REMOTES_DIR) + strlen(old_remote_name) + 1;
git_buf_puts(&new_name, namespace.ptr);
if ((error = git_buf_puts(&new_name, git_reference_name(reference_in) + pfx_len)) < 0)
goto cleanup;
if ((error = git_buf_printf(&log_message,
"renamed remote %s to %s",
old_remote_name, new_remote_name)) < 0)
goto cleanup;
if ((error = git_reference_rename(&ref, reference_in, git_buf_cstr(&new_name), 1,
git_buf_cstr(&log_message))) < 0)
goto cleanup;
if (git_reference_type(ref) != GIT_REFERENCE_SYMBOLIC)
goto cleanup;
/* Handle refs like origin/HEAD -> origin/master */
target = git_reference_symbolic_target(ref);
if ((error = git_buf_printf(&old_namespace, GIT_REFS_REMOTES_DIR "%s/", old_remote_name)) < 0)
goto cleanup;
if (git__prefixcmp(target, old_namespace.ptr))
goto cleanup;
git_buf_clear(&new_name);
git_buf_puts(&new_name, namespace.ptr);
if ((error = git_buf_puts(&new_name, target + pfx_len)) < 0)
goto cleanup;
error = git_reference_symbolic_set_target(&dummy, ref, git_buf_cstr(&new_name),
git_buf_cstr(&log_message));
git_reference_free(dummy);
cleanup:
git_reference_free(reference_in);
git_reference_free(ref);
git_buf_dispose(&namespace);
git_buf_dispose(&old_namespace);
git_buf_dispose(&new_name);
git_buf_dispose(&log_message);
return error;
}
static int rename_remote_references(
git_repository *repo,
const char *old_name,
const char *new_name)
{
int error;
git_buf buf = GIT_BUF_INIT;
git_reference *ref;
git_reference_iterator *iter;
if ((error = git_buf_printf(&buf, GIT_REFS_REMOTES_DIR "%s/*", old_name)) < 0)
return error;
error = git_reference_iterator_glob_new(&iter, repo, git_buf_cstr(&buf));
git_buf_dispose(&buf);
if (error < 0)
return error;
while ((error = git_reference_next(&ref, iter)) == 0) {
if ((error = rename_one_remote_reference(ref, old_name, new_name)) < 0)
break;
}
git_reference_iterator_free(iter);
return (error == GIT_ITEROVER) ? 0 : error;
}
static int rename_fetch_refspecs(git_vector *problems, git_remote *remote, const char *new_name)
{
git_config *config;
git_buf base = GIT_BUF_INIT, var = GIT_BUF_INIT, val = GIT_BUF_INIT;
const git_refspec *spec;
size_t i;
int error = 0;
if ((error = git_repository_config__weakptr(&config, remote->repo)) < 0)
return error;
if ((error = git_vector_init(problems, 1, NULL)) < 0)
return error;
if ((error = default_fetchspec_for_name(&base, remote->name)) < 0)
return error;
git_vector_foreach(&remote->refspecs, i, spec) {
if (spec->push)
continue;
/* Does the dst part of the refspec follow the expected format? */
if (strcmp(git_buf_cstr(&base), spec->string)) {
char *dup;
dup = git__strdup(spec->string);
GIT_ERROR_CHECK_ALLOC(dup);
if ((error = git_vector_insert(problems, dup)) < 0)
break;
continue;
}
/* If we do want to move it to the new section */
git_buf_clear(&val);
git_buf_clear(&var);
if (default_fetchspec_for_name(&val, new_name) < 0 ||
git_buf_printf(&var, "remote.%s.fetch", new_name) < 0)
{
error = -1;
break;
}
if ((error = git_config_set_string(
config, git_buf_cstr(&var), git_buf_cstr(&val))) < 0)
break;
}
git_buf_dispose(&base);
git_buf_dispose(&var);
git_buf_dispose(&val);
if (error < 0) {
char *str;
git_vector_foreach(problems, i, str)
git__free(str);
git_vector_free(problems);
}
return error;
}
int git_remote_rename(git_strarray *out, git_repository *repo, const char *name, const char *new_name)
{
int error;
git_vector problem_refspecs = GIT_VECTOR_INIT;
git_remote *remote = NULL;
GIT_ASSERT_ARG(out && repo && name && new_name);
if ((error = git_remote_lookup(&remote, repo, name)) < 0)
return error;
if ((error = ensure_remote_name_is_valid(new_name)) < 0)
goto cleanup;
if ((error = ensure_remote_doesnot_exist(repo, new_name)) < 0)
goto cleanup;
if ((error = rename_remote_config_section(repo, name, new_name)) < 0)
goto cleanup;
if ((error = update_branch_remote_config_entry(repo, name, new_name)) < 0)
goto cleanup;
if ((error = rename_remote_references(repo, name, new_name)) < 0)
goto cleanup;
if ((error = rename_fetch_refspecs(&problem_refspecs, remote, new_name)) < 0)
goto cleanup;
out->count = problem_refspecs.length;
out->strings = (char **) problem_refspecs.contents;
cleanup:
if (error < 0)
git_vector_free(&problem_refspecs);
git_remote_free(remote);
return error;
}
int git_remote_name_is_valid(int *valid, const char *remote_name)
{
git_buf buf = GIT_BUF_INIT;
git_refspec refspec = {0};
int error;
GIT_ASSERT(valid);
*valid = 0;
if (!remote_name || *remote_name == '\0')
return 0;
if ((error = git_buf_printf(&buf, "refs/heads/test:refs/remotes/%s/test", remote_name)) < 0)
goto done;
error = git_refspec__parse(&refspec, git_buf_cstr(&buf), true);
if (!error)
*valid = 1;
else if (error == GIT_EINVALIDSPEC)
error = 0;
done:
git_buf_dispose(&buf);
git_refspec__dispose(&refspec);
return error;
}
git_refspec *git_remote__matching_refspec(git_remote *remote, const char *refname)
{
git_refspec *spec;
size_t i;
git_vector_foreach(&remote->active_refspecs, i, spec) {
if (spec->push)
continue;
if (git_refspec_src_matches(spec, refname))
return spec;
}
return NULL;
}
git_refspec *git_remote__matching_dst_refspec(git_remote *remote, const char *refname)
{
git_refspec *spec;
size_t i;
git_vector_foreach(&remote->active_refspecs, i, spec) {
if (spec->push)
continue;
if (git_refspec_dst_matches(spec, refname))
return spec;
}
return NULL;
}
int git_remote_add_fetch(git_repository *repo, const char *remote, const char *refspec)
{
return write_add_refspec(repo, remote, refspec, true);
}
int git_remote_add_push(git_repository *repo, const char *remote, const char *refspec)
{
return write_add_refspec(repo, remote, refspec, false);
}
static int copy_refspecs(git_strarray *array, const git_remote *remote, unsigned int push)
{
size_t i;
git_vector refspecs;
git_refspec *spec;
char *dup;
if (git_vector_init(&refspecs, remote->refspecs.length, NULL) < 0)
return -1;
git_vector_foreach(&remote->refspecs, i, spec) {
if (spec->push != push)
continue;
if ((dup = git__strdup(spec->string)) == NULL)
goto on_error;
if (git_vector_insert(&refspecs, dup) < 0) {
git__free(dup);
goto on_error;
}
}
array->strings = (char **)refspecs.contents;
array->count = refspecs.length;
return 0;
on_error:
git_vector_free_deep(&refspecs);
return -1;
}
int git_remote_get_fetch_refspecs(git_strarray *array, const git_remote *remote)
{
return copy_refspecs(array, remote, false);
}
int git_remote_get_push_refspecs(git_strarray *array, const git_remote *remote)
{
return copy_refspecs(array, remote, true);
}
size_t git_remote_refspec_count(const git_remote *remote)
{
return remote->refspecs.length;
}
const git_refspec *git_remote_get_refspec(const git_remote *remote, size_t n)
{
return git_vector_get(&remote->refspecs, n);
}
int git_remote_init_callbacks(git_remote_callbacks *opts, unsigned int version)
{
GIT_INIT_STRUCTURE_FROM_TEMPLATE(
opts, version, git_remote_callbacks, GIT_REMOTE_CALLBACKS_INIT);
return 0;
}
/* asserts a branch.<foo>.remote format */
static const char *name_offset(size_t *len_out, const char *name)
{
size_t prefix_len;
const char *dot;
prefix_len = strlen("remote.");
dot = strchr(name + prefix_len, '.');
GIT_ASSERT_ARG_WITH_RETVAL(dot, NULL);
*len_out = dot - name - prefix_len;
return name + prefix_len;
}
static int remove_branch_config_related_entries(
git_repository *repo,
const char *remote_name)
{
int error;
git_config *config;
git_config_entry *entry;
git_config_iterator *iter;
git_buf buf = GIT_BUF_INIT;
if ((error = git_repository_config__weakptr(&config, repo)) < 0)
return error;
if ((error = git_config_iterator_glob_new(&iter, config, "branch\\..+\\.remote")) < 0)
return error;
/* find any branches with us as upstream and remove that config */
while ((error = git_config_next(&entry, iter)) == 0) {
const char *branch;
size_t branch_len;
if (strcmp(remote_name, entry->value))
continue;
if ((branch = name_offset(&branch_len, entry->name)) == NULL) {
error = -1;
break;
}
git_buf_clear(&buf);
if ((error = git_buf_printf(&buf, "branch.%.*s.merge", (int)branch_len, branch)) < 0)
break;
if ((error = git_config_delete_entry(config, git_buf_cstr(&buf))) < 0) {
if (error != GIT_ENOTFOUND)
break;
git_error_clear();
}
git_buf_clear(&buf);
if ((error = git_buf_printf(&buf, "branch.%.*s.remote", (int)branch_len, branch)) < 0)
break;
if ((error = git_config_delete_entry(config, git_buf_cstr(&buf))) < 0) {
if (error != GIT_ENOTFOUND)
break;
git_error_clear();
}
}
if (error == GIT_ITEROVER)
error = 0;
git_buf_dispose(&buf);
git_config_iterator_free(iter);
return error;
}
static int remove_refs(git_repository *repo, const git_refspec *spec)
{
git_reference_iterator *iter = NULL;
git_vector refs;
const char *name;
char *dup;
int error;
size_t i;
if ((error = git_vector_init(&refs, 8, NULL)) < 0)
return error;
if ((error = git_reference_iterator_new(&iter, repo)) < 0)
goto cleanup;
while ((error = git_reference_next_name(&name, iter)) == 0) {
if (!git_refspec_dst_matches(spec, name))
continue;
dup = git__strdup(name);
if (!dup) {
error = -1;
goto cleanup;
}
if ((error = git_vector_insert(&refs, dup)) < 0)
goto cleanup;
}
if (error == GIT_ITEROVER)
error = 0;
if (error < 0)
goto cleanup;
git_vector_foreach(&refs, i, name) {
if ((error = git_reference_remove(repo, name)) < 0)
break;
}
cleanup:
git_reference_iterator_free(iter);
git_vector_foreach(&refs, i, dup) {
git__free(dup);
}
git_vector_free(&refs);
return error;
}
static int remove_remote_tracking(git_repository *repo, const char *remote_name)
{
git_remote *remote;
int error;
size_t i, count;
/* we want to use what's on the config, regardless of changes to the instance in memory */
if ((error = git_remote_lookup(&remote, repo, remote_name)) < 0)
return error;
count = git_remote_refspec_count(remote);
for (i = 0; i < count; i++) {
const git_refspec *refspec = git_remote_get_refspec(remote, i);
/* shouldn't ever actually happen */
if (refspec == NULL)
continue;
if ((error = remove_refs(repo, refspec)) < 0)
break;
}
git_remote_free(remote);
return error;
}
int git_remote_delete(git_repository *repo, const char *name)
{
int error;
GIT_ASSERT_ARG(repo);
GIT_ASSERT_ARG(name);
if ((error = remove_branch_config_related_entries(repo, name)) < 0 ||
(error = remove_remote_tracking(repo, name)) < 0 ||
(error = rename_remote_config_section(repo, name, NULL)) < 0)
return error;
return 0;
}
int git_remote_default_branch(git_buf *out, git_remote *remote)
{
const git_remote_head **heads;
const git_remote_head *guess = NULL;
const git_oid *head_id;
size_t heads_len, i;
git_buf local_default = GIT_BUF_INIT;
int error;
GIT_ASSERT_ARG(out);
if ((error = git_remote_ls(&heads, &heads_len, remote)) < 0)
goto done;
if (heads_len == 0 || strcmp(heads[0]->name, GIT_HEAD_FILE)) {
error = GIT_ENOTFOUND;
goto done;
}
if ((error = git_buf_sanitize(out)) < 0)
return error;
/* the first one must be HEAD so if that has the symref info, we're done */
if (heads[0]->symref_target) {
error = git_buf_puts(out, heads[0]->symref_target);
goto done;
}
/*
* If there's no symref information, we have to look over them
* and guess. We return the first match unless the default
* branch is a candidate. Then we return the default branch.
*/
if ((error = git_repository_initialbranch(&local_default, remote->repo)) < 0)
goto done;
head_id = &heads[0]->oid;
for (i = 1; i < heads_len; i++) {
if (git_oid_cmp(head_id, &heads[i]->oid))
continue;
if (git__prefixcmp(heads[i]->name, GIT_REFS_HEADS_DIR))
continue;
if (!guess) {
guess = heads[i];
continue;
}
if (!git__strcmp(local_default.ptr, heads[i]->name)) {
guess = heads[i];
break;
}
}
if (!guess) {
error = GIT_ENOTFOUND;
goto done;
}
error = git_buf_puts(out, guess->name);
done:
git_buf_dispose(&local_default);
return error;
}
int git_remote_upload(git_remote *remote, const git_strarray *refspecs, const git_push_options *opts)
{
size_t i;
int error;
git_push *push;
git_refspec *spec;
const git_remote_callbacks *cbs = NULL;
git_remote_connection_opts conn = GIT_REMOTE_CONNECTION_OPTIONS_INIT;
GIT_ASSERT_ARG(remote);
if (!remote->repo) {
git_error_set(GIT_ERROR_INVALID, "cannot download detached remote");
return -1;
}
if (opts) {
cbs = &opts->callbacks;
conn.custom_headers = &opts->custom_headers;
conn.proxy = &opts->proxy_opts;
}
if (!git_remote_connected(remote) &&
(error = git_remote__connect(remote, GIT_DIRECTION_PUSH, cbs, &conn)) < 0)
goto cleanup;
free_refspecs(&remote->active_refspecs);
if ((error = dwim_refspecs(&remote->active_refspecs, &remote->refspecs, &remote->refs)) < 0)
goto cleanup;
if (remote->push) {
git_push_free(remote->push);
remote->push = NULL;
}
if ((error = git_push_new(&remote->push, remote)) < 0)
return error;
push = remote->push;
if (opts && (error = git_push_set_options(push, opts)) < 0)
goto cleanup;
if (refspecs && refspecs->count > 0) {
for (i = 0; i < refspecs->count; i++) {
if ((error = git_push_add_refspec(push, refspecs->strings[i])) < 0)
goto cleanup;
}
} else {
git_vector_foreach(&remote->refspecs, i, spec) {
if (!spec->push)
continue;
if ((error = git_push_add_refspec(push, spec->string)) < 0)
goto cleanup;
}
}
if ((error = git_push_finish(push, cbs)) < 0)
goto cleanup;
if (cbs && cbs->push_update_reference &&
(error = git_push_status_foreach(push, cbs->push_update_reference, cbs->payload)) < 0)
goto cleanup;
cleanup:
return error;
}
int git_remote_push(git_remote *remote, const git_strarray *refspecs, const git_push_options *opts)
{
int error;
const git_remote_callbacks *cbs = NULL;
const git_strarray *custom_headers = NULL;
const git_proxy_options *proxy = NULL;
GIT_ASSERT_ARG(remote);
if (!remote->repo) {
git_error_set(GIT_ERROR_INVALID, "cannot download detached remote");
return -1;
}
if (opts) {
GIT_ERROR_CHECK_VERSION(&opts->callbacks, GIT_REMOTE_CALLBACKS_VERSION, "git_remote_callbacks");
cbs = &opts->callbacks;
custom_headers = &opts->custom_headers;
GIT_ERROR_CHECK_VERSION(&opts->proxy_opts, GIT_PROXY_OPTIONS_VERSION, "git_proxy_options");
proxy = &opts->proxy_opts;
}
if ((error = git_remote_connect(remote, GIT_DIRECTION_PUSH, cbs, proxy, custom_headers)) < 0)
return error;
if ((error = git_remote_upload(remote, refspecs, opts)) < 0)
return error;
error = git_remote_update_tips(remote, cbs, 0, 0, NULL);
git_remote_disconnect(remote);
return error;
}
#define PREFIX "url"
#define SUFFIX_FETCH "insteadof"
#define SUFFIX_PUSH "pushinsteadof"
char *apply_insteadof(git_config *config, const char *url, int direction)
{
size_t match_length, prefix_length, suffix_length;
char *replacement = NULL;
const char *regexp;
git_buf result = GIT_BUF_INIT;
git_config_entry *entry;
git_config_iterator *iter;
GIT_ASSERT_ARG_WITH_RETVAL(config, NULL);
GIT_ASSERT_ARG_WITH_RETVAL(url, NULL);
GIT_ASSERT_ARG_WITH_RETVAL(direction == GIT_DIRECTION_FETCH || direction == GIT_DIRECTION_PUSH, NULL);
/* Add 1 to prefix/suffix length due to the additional escaped dot */
prefix_length = strlen(PREFIX) + 1;
if (direction == GIT_DIRECTION_FETCH) {
regexp = PREFIX "\\..*\\." SUFFIX_FETCH;
suffix_length = strlen(SUFFIX_FETCH) + 1;
} else {
regexp = PREFIX "\\..*\\." SUFFIX_PUSH;
suffix_length = strlen(SUFFIX_PUSH) + 1;
}
if (git_config_iterator_glob_new(&iter, config, regexp) < 0)
return NULL;
match_length = 0;
while (git_config_next(&entry, iter) == 0) {
size_t n, replacement_length;
/* Check if entry value is a prefix of URL */
if (git__prefixcmp(url, entry->value))
continue;
/* Check if entry value is longer than previous
* prefixes */
if ((n = strlen(entry->value)) <= match_length)
continue;
git__free(replacement);
match_length = n;
/* Cut off prefix and suffix of the value */
replacement_length =
strlen(entry->name) - (prefix_length + suffix_length);
replacement = git__strndup(entry->name + prefix_length,
replacement_length);
}
git_config_iterator_free(iter);
if (match_length == 0)
return git__strdup(url);
git_buf_printf(&result, "%s%s", replacement, url + match_length);
git__free(replacement);
return result.ptr;
}
/* Deprecated functions */
#ifndef GIT_DEPRECATE_HARD
int git_remote_is_valid_name(const char *remote_name)
{
int valid = 0;
git_remote_name_is_valid(&valid, remote_name);
return valid;
}
#endif
|
0 |
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2
|
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2/src/thread.h
|
/*
* Copyright (C) the libgit2 contributors. All rights reserved.
*
* This file is part of libgit2, distributed under the GNU GPL v2 with
* a Linking Exception. For full terms see the included COPYING file.
*/
#ifndef INCLUDE_thread_h__
#define INCLUDE_thread_h__
#if defined(GIT_THREADS)
#if defined(__clang__)
# if (__clang_major__ < 3 || (__clang_major__ == 3 && __clang_minor__ < 1))
# error Atomic primitives do not exist on this version of clang; configure libgit2 with -DTHREADSAFE=OFF
# else
# define GIT_BUILTIN_ATOMIC
# endif
#elif defined(__GNUC__)
# if (__GNUC__ < 4 || (__GNUC__ == 4 && __GNUC_MINOR__ < 1))
# error Atomic primitives do not exist on this version of gcc; configure libgit2 with -DTHREADSAFE=OFF
# elif (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 7))
# define GIT_BUILTIN_ATOMIC
# else
# define GIT_BUILTIN_SYNC
# endif
#endif
#endif /* GIT_THREADS */
/* Common operations even if threading has been disabled */
typedef struct {
#if defined(GIT_WIN32)
volatile long val;
#else
volatile int val;
#endif
} git_atomic32;
#ifdef GIT_ARCH_64
typedef struct {
#if defined(GIT_WIN32)
volatile __int64 val;
#else
volatile int64_t val;
#endif
} git_atomic64;
typedef git_atomic64 git_atomic_ssize;
#define git_atomic_ssize_set git_atomic64_set
#define git_atomic_ssize_add git_atomic64_add
#define git_atomic_ssize_get git_atomic64_get
#else
typedef git_atomic32 git_atomic_ssize;
#define git_atomic_ssize_set git_atomic32_set
#define git_atomic_ssize_add git_atomic32_add
#define git_atomic_ssize_get git_atomic32_get
#endif
#ifdef GIT_THREADS
#ifdef GIT_WIN32
# include "win32/thread.h"
#else
# include "unix/pthread.h"
#endif
/*
* Atomically sets the contents of *a to be val.
*/
GIT_INLINE(void) git_atomic32_set(git_atomic32 *a, int val)
{
#if defined(GIT_WIN32)
InterlockedExchange(&a->val, (LONG)val);
#elif defined(GIT_BUILTIN_ATOMIC)
__atomic_store_n(&a->val, val, __ATOMIC_SEQ_CST);
#elif defined(GIT_BUILTIN_SYNC)
__sync_lock_test_and_set(&a->val, val);
#else
# error "Unsupported architecture for atomic operations"
#endif
}
/*
* Atomically increments the contents of *a by 1, and stores the result back into *a.
* @return the result of the operation.
*/
GIT_INLINE(int) git_atomic32_inc(git_atomic32 *a)
{
#if defined(GIT_WIN32)
return InterlockedIncrement(&a->val);
#elif defined(GIT_BUILTIN_ATOMIC)
return __atomic_add_fetch(&a->val, 1, __ATOMIC_SEQ_CST);
#elif defined(GIT_BUILTIN_SYNC)
return __sync_add_and_fetch(&a->val, 1);
#else
# error "Unsupported architecture for atomic operations"
#endif
}
/*
* Atomically adds the contents of *a and addend, and stores the result back into *a.
* @return the result of the operation.
*/
GIT_INLINE(int) git_atomic32_add(git_atomic32 *a, int32_t addend)
{
#if defined(GIT_WIN32)
return InterlockedAdd(&a->val, addend);
#elif defined(GIT_BUILTIN_ATOMIC)
return __atomic_add_fetch(&a->val, addend, __ATOMIC_SEQ_CST);
#elif defined(GIT_BUILTIN_SYNC)
return __sync_add_and_fetch(&a->val, addend);
#else
# error "Unsupported architecture for atomic operations"
#endif
}
/*
* Atomically decrements the contents of *a by 1, and stores the result back into *a.
* @return the result of the operation.
*/
GIT_INLINE(int) git_atomic32_dec(git_atomic32 *a)
{
#if defined(GIT_WIN32)
return InterlockedDecrement(&a->val);
#elif defined(GIT_BUILTIN_ATOMIC)
return __atomic_sub_fetch(&a->val, 1, __ATOMIC_SEQ_CST);
#elif defined(GIT_BUILTIN_SYNC)
return __sync_sub_and_fetch(&a->val, 1);
#else
# error "Unsupported architecture for atomic operations"
#endif
}
/*
* Atomically gets the contents of *a.
* @return the contents of *a.
*/
GIT_INLINE(int) git_atomic32_get(git_atomic32 *a)
{
#if defined(GIT_WIN32)
return (int)InterlockedCompareExchange(&a->val, 0, 0);
#elif defined(GIT_BUILTIN_ATOMIC)
return __atomic_load_n(&a->val, __ATOMIC_SEQ_CST);
#elif defined(GIT_BUILTIN_SYNC)
return __sync_val_compare_and_swap(&a->val, 0, 0);
#else
# error "Unsupported architecture for atomic operations"
#endif
}
GIT_INLINE(void *) git_atomic__compare_and_swap(
void * volatile *ptr, void *oldval, void *newval)
{
#if defined(GIT_WIN32)
return InterlockedCompareExchangePointer((volatile PVOID *)ptr, newval, oldval);
#elif defined(GIT_BUILTIN_ATOMIC)
void *foundval = oldval;
__atomic_compare_exchange(ptr, &foundval, &newval, false, __ATOMIC_SEQ_CST, __ATOMIC_SEQ_CST);
return foundval;
#elif defined(GIT_BUILTIN_SYNC)
return __sync_val_compare_and_swap(ptr, oldval, newval);
#else
# error "Unsupported architecture for atomic operations"
#endif
}
GIT_INLINE(volatile void *) git_atomic__swap(
void * volatile *ptr, void *newval)
{
#if defined(GIT_WIN32)
return InterlockedExchangePointer(ptr, newval);
#elif defined(GIT_BUILTIN_ATOMIC)
void * volatile foundval = NULL;
__atomic_exchange(ptr, &newval, &foundval, __ATOMIC_SEQ_CST);
return foundval;
#elif defined(GIT_BUILTIN_SYNC)
return (volatile void *)__sync_lock_test_and_set(ptr, newval);
#else
# error "Unsupported architecture for atomic operations"
#endif
}
GIT_INLINE(volatile void *) git_atomic__load(void * volatile *ptr)
{
#if defined(GIT_WIN32)
void *newval = NULL, *oldval = NULL;
return (volatile void *)InterlockedCompareExchangePointer((volatile PVOID *)ptr, newval, oldval);
#elif defined(GIT_BUILTIN_ATOMIC)
return (volatile void *)__atomic_load_n(ptr, __ATOMIC_SEQ_CST);
#elif defined(GIT_BUILTIN_SYNC)
return (volatile void *)__sync_val_compare_and_swap(ptr, 0, 0);
#else
# error "Unsupported architecture for atomic operations"
#endif
}
#ifdef GIT_ARCH_64
/*
* Atomically adds the contents of *a and addend, and stores the result back into *a.
* @return the result of the operation.
*/
GIT_INLINE(int64_t) git_atomic64_add(git_atomic64 *a, int64_t addend)
{
#if defined(GIT_WIN32)
return InterlockedAdd64(&a->val, addend);
#elif defined(GIT_BUILTIN_ATOMIC)
return __atomic_add_fetch(&a->val, addend, __ATOMIC_SEQ_CST);
#elif defined(GIT_BUILTIN_SYNC)
return __sync_add_and_fetch(&a->val, addend);
#else
# error "Unsupported architecture for atomic operations"
#endif
}
/*
* Atomically sets the contents of *a to be val.
*/
GIT_INLINE(void) git_atomic64_set(git_atomic64 *a, int64_t val)
{
#if defined(GIT_WIN32)
InterlockedExchange64(&a->val, val);
#elif defined(GIT_BUILTIN_ATOMIC)
__atomic_store_n(&a->val, val, __ATOMIC_SEQ_CST);
#elif defined(GIT_BUILTIN_SYNC)
__sync_lock_test_and_set(&a->val, val);
#else
# error "Unsupported architecture for atomic operations"
#endif
}
/*
* Atomically gets the contents of *a.
* @return the contents of *a.
*/
GIT_INLINE(int64_t) git_atomic64_get(git_atomic64 *a)
{
#if defined(GIT_WIN32)
return (int64_t)InterlockedCompareExchange64(&a->val, 0, 0);
#elif defined(GIT_BUILTIN_ATOMIC)
return __atomic_load_n(&a->val, __ATOMIC_SEQ_CST);
#elif defined(GIT_BUILTIN_SYNC)
return __sync_val_compare_and_swap(&a->val, 0, 0);
#else
# error "Unsupported architecture for atomic operations"
#endif
}
#endif
#else
#define git_threads_global_init git__noop
#define git_thread unsigned int
#define git_thread_create(thread, start_routine, arg) git__noop()
#define git_thread_join(id, status) git__noop()
/* Pthreads Mutex */
#define git_mutex unsigned int
#define git_mutex_init(a) git__noop()
#define git_mutex_init(a) git__noop()
#define git_mutex_lock(a) git__noop()
#define git_mutex_unlock(a) git__noop()
#define git_mutex_free(a) git__noop()
/* Pthreads condition vars */
#define git_cond unsigned int
#define git_cond_init(c) git__noop()
#define git_cond_free(c) git__noop()
#define git_cond_wait(c, l) git__noop()
#define git_cond_signal(c) git__noop()
#define git_cond_broadcast(c) git__noop()
/* Pthreads rwlock */
#define git_rwlock unsigned int
#define git_rwlock_init(a) git__noop()
#define git_rwlock_rdlock(a) git__noop()
#define git_rwlock_rdunlock(a) git__noop()
#define git_rwlock_wrlock(a) git__noop()
#define git_rwlock_wrunlock(a) git__noop()
#define git_rwlock_free(a) git__noop()
#define GIT_RWLOCK_STATIC_INIT 0
GIT_INLINE(void) git_atomic32_set(git_atomic32 *a, int val)
{
a->val = val;
}
GIT_INLINE(int) git_atomic32_inc(git_atomic32 *a)
{
return ++a->val;
}
GIT_INLINE(int) git_atomic32_add(git_atomic32 *a, int32_t addend)
{
a->val += addend;
return a->val;
}
GIT_INLINE(int) git_atomic32_dec(git_atomic32 *a)
{
return --a->val;
}
GIT_INLINE(int) git_atomic32_get(git_atomic32 *a)
{
return (int)a->val;
}
GIT_INLINE(void *) git_atomic__compare_and_swap(
void * volatile *ptr, void *oldval, void *newval)
{
void *foundval = *ptr;
if (foundval == oldval)
*ptr = newval;
return foundval;
}
GIT_INLINE(volatile void *) git_atomic__swap(
void * volatile *ptr, void *newval)
{
volatile void *old = *ptr;
*ptr = newval;
return old;
}
GIT_INLINE(volatile void *) git_atomic__load(void * volatile *ptr)
{
return *ptr;
}
#ifdef GIT_ARCH_64
GIT_INLINE(int64_t) git_atomic64_add(git_atomic64 *a, int64_t addend)
{
a->val += addend;
return a->val;
}
GIT_INLINE(void) git_atomic64_set(git_atomic64 *a, int64_t val)
{
a->val = val;
}
GIT_INLINE(int64_t) git_atomic64_get(git_atomic64 *a)
{
return (int64_t)a->val;
}
#endif
#endif
/*
* Atomically replace the contents of *ptr (if they are equal to oldval) with
* newval. ptr must point to a pointer or a value that is the same size as a
* pointer. This is semantically compatible with:
*
* #define git_atomic_compare_and_swap(ptr, oldval, newval) \
* ({ \
* void *foundval = *ptr; \
* if (foundval == oldval) \
* *ptr = newval; \
* foundval; \
* })
*
* @return the original contents of *ptr.
*/
#define git_atomic_compare_and_swap(ptr, oldval, newval) \
git_atomic__compare_and_swap((void * volatile *)ptr, oldval, newval)
/*
* Atomically replace the contents of v with newval. v must be the same size as
* a pointer. This is semantically compatible with:
*
* #define git_atomic_swap(v, newval) \
* ({ \
* volatile void *old = v; \
* v = newval; \
* old; \
* })
*
* @return the original contents of v.
*/
#define git_atomic_swap(v, newval) \
(void *)git_atomic__swap((void * volatile *)&(v), newval)
/*
* Atomically reads the contents of v. v must be the same size as a pointer.
* This is semantically compatible with:
*
* #define git_atomic_load(v) v
*
* @return the contents of v.
*/
#define git_atomic_load(v) \
(void *)git_atomic__load((void * volatile *)&(v))
#if defined(GIT_THREADS)
# if defined(GIT_WIN32)
# define GIT_MEMORY_BARRIER MemoryBarrier()
# elif defined(GIT_BUILTIN_ATOMIC)
# define GIT_MEMORY_BARRIER __atomic_thread_fence(__ATOMIC_SEQ_CST)
# elif defined(GIT_BUILTIN_SYNC)
# define GIT_MEMORY_BARRIER __sync_synchronize()
# endif
#else
# define GIT_MEMORY_BARRIER /* noop */
#endif
/* Thread-local data */
#if !defined(GIT_THREADS)
# define git_tlsdata_key int
#elif defined(GIT_WIN32)
# define git_tlsdata_key DWORD
#elif defined(_POSIX_THREADS)
# define git_tlsdata_key pthread_key_t
#else
# error unknown threading model
#endif
/**
* Create a thread-local data key. The destroy function will be
* called upon thread exit. On some platforms, it may be called
* when all threads have deleted their keys.
*
* Note that the tlsdata functions do not set an error message on
* failure; this is because the error handling in libgit2 is itself
* handled by thread-local data storage.
*
* @param key the tlsdata key
* @param destroy_fn function pointer called upon thread exit
* @return 0 on success, non-zero on failure
*/
int git_tlsdata_init(git_tlsdata_key *key, void (GIT_SYSTEM_CALL *destroy_fn)(void *));
/**
* Set a the thread-local value for the given key.
*
* @param key the tlsdata key to store data on
* @param value the pointer to store
* @return 0 on success, non-zero on failure
*/
int git_tlsdata_set(git_tlsdata_key key, void *value);
/**
* Get the thread-local value for the given key.
*
* @param key the tlsdata key to retrieve the value of
* @return the pointer stored with git_tlsdata_set
*/
void *git_tlsdata_get(git_tlsdata_key key);
/**
* Delete the given thread-local key.
*
* @param key the tlsdata key to dispose
* @return 0 on success, non-zero on failure
*/
int git_tlsdata_dispose(git_tlsdata_key key);
#endif
|
0 |
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2
|
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2/src/sortedcache.h
|
/*
* Copyright (C) the libgit2 contributors. All rights reserved.
*
* This file is part of libgit2, distributed under the GNU GPL v2 with
* a Linking Exception. For full terms see the included COPYING file.
*/
#ifndef INCLUDE_sorted_cache_h__
#define INCLUDE_sorted_cache_h__
#include "common.h"
#include "util.h"
#include "futils.h"
#include "vector.h"
#include "thread.h"
#include "pool.h"
#include "strmap.h"
#include <stddef.h>
/*
* The purpose of this data structure is to cache the parsed contents of a
* file (a.k.a. the backing file) where each item in the file can be
* identified by a key string and you want to both look them up by name
* and traverse them in sorted order. Each item is assumed to itself end
* in a GIT_FLEX_ARRAY.
*/
typedef void (*git_sortedcache_free_item_fn)(void *payload, void *item);
typedef struct {
git_refcount rc;
git_rwlock lock;
size_t item_path_offset;
git_sortedcache_free_item_fn free_item;
void *free_item_payload;
git_pool pool;
git_vector items;
git_strmap *map;
git_futils_filestamp stamp;
char path[GIT_FLEX_ARRAY];
} git_sortedcache;
/* Create a new sortedcache
*
* Even though every sortedcache stores items with a GIT_FLEX_ARRAY at
* the end containing their key string, you have to provide the item_cmp
* sorting function because the sorting function doesn't get a payload
* and therefore can't know the offset to the item key string. :-(
*
* @param out The allocated git_sortedcache
* @param item_path_offset Offset to the GIT_FLEX_ARRAY item key in the
* struct - use offsetof(struct mine, key-field) to get this
* @param free_item Optional callback to free each item
* @param free_item_payload Optional payload passed to free_item callback
* @param item_cmp Compare the keys of two items
* @param path The path to the backing store file for this cache; this
* may be NULL. The cache makes it easy to load this and check
* if it has been modified since the last load and/or write.
*/
GIT_WARN_UNUSED_RESULT int git_sortedcache_new(
git_sortedcache **out,
size_t item_path_offset, /* use offsetof(struct, path-field) macro */
git_sortedcache_free_item_fn free_item,
void *free_item_payload,
git_vector_cmp item_cmp,
const char *path);
/* Copy a sorted cache
*
* - `copy_item` can be NULL to just use memcpy
* - if `lock`, grabs read lock on `src` during copy and releases after
*/
GIT_WARN_UNUSED_RESULT int git_sortedcache_copy(
git_sortedcache **out,
git_sortedcache *src,
bool lock,
int (*copy_item)(void *payload, void *tgt_item, void *src_item),
void *payload);
/* Free sorted cache (first calling `free_item` callbacks)
*
* Don't call on a locked collection - it may acquire a write lock
*/
void git_sortedcache_free(git_sortedcache *sc);
/* Increment reference count - balance with call to free */
void git_sortedcache_incref(git_sortedcache *sc);
/* Get the pathname associated with this cache at creation time */
const char *git_sortedcache_path(git_sortedcache *sc);
/*
* CACHE WRITE FUNCTIONS
*
* The following functions require you to have a writer lock to make the
* modification. Some of the functions take a `wlock` parameter and
* will optionally lock and unlock for you if that is passed as true.
*
*/
/* Lock sortedcache for write */
GIT_WARN_UNUSED_RESULT int git_sortedcache_wlock(git_sortedcache *sc);
/* Unlock sorted cache when done with write */
void git_sortedcache_wunlock(git_sortedcache *sc);
/* Lock cache and load backing file into a buffer.
*
* This grabs a write lock on the cache then looks at the modification
* time and size of the file on disk.
*
* If the file appears to have changed, this loads the file contents into
* the buffer and returns a positive value leaving the cache locked - the
* caller should parse the file content, update the cache as needed, then
* release the lock. NOTE: In this case, the caller MUST unlock the cache.
*
* If the file appears to be unchanged, then this automatically releases
* the lock on the cache, clears the buffer, and returns 0.
*
* @return 0 if up-to-date, 1 if out-of-date, <0 on error
*/
GIT_WARN_UNUSED_RESULT int git_sortedcache_lockandload(
git_sortedcache *sc, git_buf *buf);
/* Refresh file timestamp after write completes
* You should already be holding the write lock when you call this.
*/
void git_sortedcache_updated(git_sortedcache *sc);
/* Release all items in sorted cache
*
* If `wlock` is true, grabs write lock and releases when done, otherwise
* you should already be holding a write lock when you call this.
*/
GIT_WARN_UNUSED_RESULT int git_sortedcache_clear(
git_sortedcache *sc, bool wlock);
/* Find and/or insert item, returning pointer to item data.
* You should already be holding the write lock when you call this.
*/
GIT_WARN_UNUSED_RESULT int git_sortedcache_upsert(
void **out, git_sortedcache *sc, const char *key);
/* Removes entry at pos from cache
* You should already be holding the write lock when you call this.
*/
int git_sortedcache_remove(git_sortedcache *sc, size_t pos);
/*
* CACHE READ FUNCTIONS
*
* The following functions access items in the cache. To prevent the
* results from being invalidated before they can be used, you should be
* holding either a read lock or a write lock when using these functions.
*
*/
/* Lock sortedcache for read */
GIT_WARN_UNUSED_RESULT int git_sortedcache_rlock(git_sortedcache *sc);
/* Unlock sorted cache when done with read */
void git_sortedcache_runlock(git_sortedcache *sc);
/* Lookup item by key - returns NULL if not found */
void *git_sortedcache_lookup(const git_sortedcache *sc, const char *key);
/* Get how many items are in the cache
*
* You can call this function without holding a lock, but be aware
* that it may change before you use it.
*/
size_t git_sortedcache_entrycount(const git_sortedcache *sc);
/* Lookup item by index - returns NULL if out of range */
void *git_sortedcache_entry(git_sortedcache *sc, size_t pos);
/* Lookup index of item by key - returns GIT_ENOTFOUND if not found */
int git_sortedcache_lookup_index(
size_t *out, git_sortedcache *sc, const char *key);
#endif
|
0 |
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2
|
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2/src/strmap.h
|
/*
* Copyright (C) the libgit2 contributors. All rights reserved.
*
* This file is part of libgit2, distributed under the GNU GPL v2 with
* a Linking Exception. For full terms see the included COPYING file.
*/
#ifndef INCLUDE_strmap_h__
#define INCLUDE_strmap_h__
#include "common.h"
/** A map with C strings as key. */
typedef struct kh_str_s git_strmap;
/**
* Allocate a new string map.
*
* @param out Pointer to the map that shall be allocated.
* @return 0 on success, an error code if allocation has failed.
*/
int git_strmap_new(git_strmap **out);
/**
* Free memory associated with the map.
*
* Note that this function will _not_ free keys or values added
* to this map.
*
* @param map Pointer to the map that is to be free'd. May be
* `NULL`.
*/
void git_strmap_free(git_strmap *map);
/**
* Clear all entries from the map.
*
* This function will remove all entries from the associated map.
* Memory associated with it will not be released, though.
*
* @param map Pointer to the map that shall be cleared. May be
* `NULL`.
*/
void git_strmap_clear(git_strmap *map);
/**
* Return the number of elements in the map.
*
* @parameter map map containing the elements
* @return number of elements in the map
*/
size_t git_strmap_size(git_strmap *map);
/**
* Return value associated with the given key.
*
* @param map map to search key in
* @param key key to search for
* @return value associated with the given key or NULL if the key was not found
*/
void *git_strmap_get(git_strmap *map, const char *key);
/**
* Set the entry for key to value.
*
* If the map has no corresponding entry for the given key, a new
* entry will be created with the given value. If an entry exists
* already, its value will be updated to match the given value.
*
* @param map map to create new entry in
* @param key key to set
* @param value value to associate the key with; may be NULL
* @return zero if the key was successfully set, a negative error
* code otherwise
*/
int git_strmap_set(git_strmap *map, const char *key, void *value);
/**
* Delete an entry from the map.
*
* Delete the given key and its value from the map. If no such
* key exists, this will do nothing.
*
* @param map map to delete key in
* @param key key to delete
* @return `0` if the key has been deleted, GIT_ENOTFOUND if no
* such key was found, a negative code in case of an
* error
*/
int git_strmap_delete(git_strmap *map, const char *key);
/**
* Check whether a key exists in the given map.
*
* @param map map to query for the key
* @param key key to search for
* @return 0 if the key has not been found, 1 otherwise
*/
int git_strmap_exists(git_strmap *map, const char *key);
/**
* Iterate over entries of the map.
*
* This functions allows to iterate over all key-value entries of
* the map. The current position is stored in the `iter` variable
* and should be initialized to `0` before the first call to this
* function.
*
* @param map map to iterate over
* @param value pointer to the variable where to store the current
* value. May be NULL.
* @param iter iterator storing the current position. Initialize
* with zero previous to the first call.
* @param key pointer to the variable where to store the current
* key. May be NULL.
* @return `0` if the next entry was correctly retrieved.
* GIT_ITEROVER if no entries are left. A negative error
* code otherwise.
*/
int git_strmap_iterate(void **value, git_strmap *map, size_t *iter, const char **key);
#define git_strmap_foreach(h, kvar, vvar, code) { size_t __i = 0; \
while (git_strmap_iterate((void **) &(vvar), h, &__i, &(kvar)) == 0) { \
code; \
} }
#define git_strmap_foreach_value(h, vvar, code) { size_t __i = 0; \
while (git_strmap_iterate((void **) &(vvar), h, &__i, NULL) == 0) { \
code; \
} }
#endif
|
0 |
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2
|
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2/src/config_file.c
|
/*
* Copyright (C) the libgit2 contributors. All rights reserved.
*
* This file is part of libgit2, distributed under the GNU GPL v2 with
* a Linking Exception. For full terms see the included COPYING file.
*/
#include "config.h"
#include "git2/config.h"
#include "git2/sys/config.h"
#include "array.h"
#include "buffer.h"
#include "config_backend.h"
#include "config_entries.h"
#include "config_parse.h"
#include "filebuf.h"
#include "regexp.h"
#include "sysdir.h"
#include "wildmatch.h"
/* Max depth for [include] directives */
#define MAX_INCLUDE_DEPTH 10
typedef struct config_file {
git_futils_filestamp stamp;
git_oid checksum;
char *path;
git_array_t(struct config_file) includes;
} config_file;
typedef struct {
git_config_backend parent;
git_mutex values_mutex;
git_config_entries *entries;
const git_repository *repo;
git_config_level_t level;
git_array_t(git_config_parser) readers;
bool locked;
git_filebuf locked_buf;
git_buf locked_content;
config_file file;
} config_file_backend;
typedef struct {
const git_repository *repo;
config_file *file;
git_config_entries *entries;
git_config_level_t level;
unsigned int depth;
} config_file_parse_data;
static int config_file_read(git_config_entries *entries, const git_repository *repo, config_file *file, git_config_level_t level, int depth);
static int config_file_read_buffer(git_config_entries *entries, const git_repository *repo, config_file *file, git_config_level_t level, int depth, const char *buf, size_t buflen);
static int config_file_write(config_file_backend *cfg, const char *orig_key, const char *key, const git_regexp *preg, const char *value);
static char *escape_value(const char *ptr);
/**
* Take the current values map from the backend and increase its
* refcount. This is its own function to make sure we use the mutex to
* avoid the map pointer from changing under us.
*/
static int config_file_entries_take(git_config_entries **out, config_file_backend *b)
{
int error;
if ((error = git_mutex_lock(&b->values_mutex)) < 0) {
git_error_set(GIT_ERROR_OS, "failed to lock config backend");
return error;
}
git_config_entries_incref(b->entries);
*out = b->entries;
git_mutex_unlock(&b->values_mutex);
return 0;
}
static void config_file_clear(config_file *file)
{
config_file *include;
uint32_t i;
if (file == NULL)
return;
git_array_foreach(file->includes, i, include) {
config_file_clear(include);
}
git_array_clear(file->includes);
git__free(file->path);
}
static int config_file_open(git_config_backend *cfg, git_config_level_t level, const git_repository *repo)
{
config_file_backend *b = GIT_CONTAINER_OF(cfg, config_file_backend, parent);
int res;
b->level = level;
b->repo = repo;
if ((res = git_config_entries_new(&b->entries)) < 0)
return res;
if (!git_path_exists(b->file.path))
return 0;
/*
* git silently ignores configuration files that are not
* readable. We emulate that behavior. This is particularly
* important for sandboxed applications on macOS where the
* git configuration files may not be readable.
*/
if (p_access(b->file.path, R_OK) < 0)
return GIT_ENOTFOUND;
if (res < 0 || (res = config_file_read(b->entries, repo, &b->file, level, 0)) < 0) {
git_config_entries_free(b->entries);
b->entries = NULL;
}
return res;
}
static int config_file_is_modified(int *modified, config_file *file)
{
config_file *include;
git_buf buf = GIT_BUF_INIT;
git_oid hash;
uint32_t i;
int error = 0;
*modified = 0;
if (!git_futils_filestamp_check(&file->stamp, file->path))
goto check_includes;
if ((error = git_futils_readbuffer(&buf, file->path)) < 0)
goto out;
if ((error = git_hash_buf(&hash, buf.ptr, buf.size)) < 0)
goto out;
if (!git_oid_equal(&hash, &file->checksum)) {
*modified = 1;
goto out;
}
check_includes:
git_array_foreach(file->includes, i, include) {
if ((error = config_file_is_modified(modified, include)) < 0 || *modified)
goto out;
}
out:
git_buf_dispose(&buf);
return error;
}
static void config_file_clear_includes(config_file_backend *cfg)
{
config_file *include;
uint32_t i;
git_array_foreach(cfg->file.includes, i, include)
config_file_clear(include);
git_array_clear(cfg->file.includes);
}
static int config_file_set_entries(git_config_backend *cfg, git_config_entries *entries)
{
config_file_backend *b = GIT_CONTAINER_OF(cfg, config_file_backend, parent);
git_config_entries *old = NULL;
int error;
if (b->parent.readonly) {
git_error_set(GIT_ERROR_CONFIG, "this backend is read-only");
return -1;
}
if ((error = git_mutex_lock(&b->values_mutex)) < 0) {
git_error_set(GIT_ERROR_OS, "failed to lock config backend");
goto out;
}
old = b->entries;
b->entries = entries;
git_mutex_unlock(&b->values_mutex);
out:
git_config_entries_free(old);
return error;
}
static int config_file_refresh_from_buffer(git_config_backend *cfg, const char *buf, size_t buflen)
{
config_file_backend *b = GIT_CONTAINER_OF(cfg, config_file_backend, parent);
git_config_entries *entries = NULL;
int error;
config_file_clear_includes(b);
if ((error = git_config_entries_new(&entries)) < 0 ||
(error = config_file_read_buffer(entries, b->repo, &b->file,
b->level, 0, buf, buflen)) < 0 ||
(error = config_file_set_entries(cfg, entries)) < 0)
goto out;
entries = NULL;
out:
git_config_entries_free(entries);
return error;
}
static int config_file_refresh(git_config_backend *cfg)
{
config_file_backend *b = GIT_CONTAINER_OF(cfg, config_file_backend, parent);
git_config_entries *entries = NULL;
int error, modified;
if (cfg->readonly)
return 0;
if ((error = config_file_is_modified(&modified, &b->file)) < 0 && error != GIT_ENOTFOUND)
goto out;
if (!modified)
return 0;
config_file_clear_includes(b);
if ((error = git_config_entries_new(&entries)) < 0 ||
(error = config_file_read(entries, b->repo, &b->file, b->level, 0)) < 0 ||
(error = config_file_set_entries(cfg, entries)) < 0)
goto out;
entries = NULL;
out:
git_config_entries_free(entries);
return (error == GIT_ENOTFOUND) ? 0 : error;
}
static void config_file_free(git_config_backend *_backend)
{
config_file_backend *backend = GIT_CONTAINER_OF(_backend, config_file_backend, parent);
if (backend == NULL)
return;
config_file_clear(&backend->file);
git_config_entries_free(backend->entries);
git_mutex_free(&backend->values_mutex);
git__free(backend);
}
static int config_file_iterator(
git_config_iterator **iter,
struct git_config_backend *backend)
{
config_file_backend *b = GIT_CONTAINER_OF(backend, config_file_backend, parent);
git_config_entries *dupped = NULL, *entries = NULL;
int error;
if ((error = config_file_refresh(backend)) < 0 ||
(error = config_file_entries_take(&entries, b)) < 0 ||
(error = git_config_entries_dup(&dupped, entries)) < 0 ||
(error = git_config_entries_iterator_new(iter, dupped)) < 0)
goto out;
out:
/* Let iterator delete duplicated entries when it's done */
git_config_entries_free(entries);
git_config_entries_free(dupped);
return error;
}
static int config_file_snapshot(git_config_backend **out, git_config_backend *backend)
{
return git_config_backend_snapshot(out, backend);
}
static int config_file_set(git_config_backend *cfg, const char *name, const char *value)
{
config_file_backend *b = GIT_CONTAINER_OF(cfg, config_file_backend, parent);
git_config_entries *entries;
git_config_entry *existing;
char *key, *esc_value = NULL;
int error;
if ((error = git_config__normalize_name(name, &key)) < 0)
return error;
if ((error = config_file_entries_take(&entries, b)) < 0)
return error;
/* Check whether we'd be modifying an included or multivar key */
if ((error = git_config_entries_get_unique(&existing, entries, key)) < 0) {
if (error != GIT_ENOTFOUND)
goto out;
error = 0;
} else if ((!existing->value && !value) ||
(existing->value && value && !strcmp(existing->value, value))) {
/* don't update if old and new values already match */
error = 0;
goto out;
}
/* No early returns due to sanity checks, let's write it out and refresh */
if (value) {
esc_value = escape_value(value);
GIT_ERROR_CHECK_ALLOC(esc_value);
}
if ((error = config_file_write(b, name, key, NULL, esc_value)) < 0)
goto out;
out:
git_config_entries_free(entries);
git__free(esc_value);
git__free(key);
return error;
}
/* release the map containing the entry as an equivalent to freeing it */
static void config_file_entry_free(git_config_entry *entry)
{
git_config_entries *entries = (git_config_entries *) entry->payload;
git_config_entries_free(entries);
}
/*
* Internal function that actually gets the value in string form
*/
static int config_file_get(git_config_backend *cfg, const char *key, git_config_entry **out)
{
config_file_backend *h = GIT_CONTAINER_OF(cfg, config_file_backend, parent);
git_config_entries *entries = NULL;
git_config_entry *entry;
int error = 0;
if (!h->parent.readonly && ((error = config_file_refresh(cfg)) < 0))
return error;
if ((error = config_file_entries_take(&entries, h)) < 0)
return error;
if ((error = (git_config_entries_get(&entry, entries, key))) < 0) {
git_config_entries_free(entries);
return error;
}
entry->free = config_file_entry_free;
entry->payload = entries;
*out = entry;
return 0;
}
static int config_file_set_multivar(
git_config_backend *cfg, const char *name, const char *regexp, const char *value)
{
config_file_backend *b = GIT_CONTAINER_OF(cfg, config_file_backend, parent);
git_regexp preg;
int result;
char *key;
GIT_ASSERT_ARG(regexp);
if ((result = git_config__normalize_name(name, &key)) < 0)
return result;
if ((result = git_regexp_compile(&preg, regexp, 0)) < 0)
goto out;
/* If we do have it, set call config_file_write() and reload */
if ((result = config_file_write(b, name, key, &preg, value)) < 0)
goto out;
out:
git__free(key);
git_regexp_dispose(&preg);
return result;
}
static int config_file_delete(git_config_backend *cfg, const char *name)
{
config_file_backend *b = GIT_CONTAINER_OF(cfg, config_file_backend, parent);
git_config_entries *entries = NULL;
git_config_entry *entry;
char *key = NULL;
int error;
if ((error = git_config__normalize_name(name, &key)) < 0)
goto out;
if ((error = config_file_entries_take(&entries, b)) < 0)
goto out;
/* Check whether we'd be modifying an included or multivar key */
if ((error = git_config_entries_get_unique(&entry, entries, key)) < 0) {
if (error == GIT_ENOTFOUND)
git_error_set(GIT_ERROR_CONFIG, "could not find key '%s' to delete", name);
goto out;
}
if ((error = config_file_write(b, name, entry->name, NULL, NULL)) < 0)
goto out;
out:
git_config_entries_free(entries);
git__free(key);
return error;
}
static int config_file_delete_multivar(git_config_backend *cfg, const char *name, const char *regexp)
{
config_file_backend *b = GIT_CONTAINER_OF(cfg, config_file_backend, parent);
git_config_entries *entries = NULL;
git_config_entry *entry = NULL;
git_regexp preg = GIT_REGEX_INIT;
char *key = NULL;
int result;
if ((result = git_config__normalize_name(name, &key)) < 0)
goto out;
if ((result = config_file_entries_take(&entries, b)) < 0)
goto out;
if ((result = git_config_entries_get(&entry, entries, key)) < 0) {
if (result == GIT_ENOTFOUND)
git_error_set(GIT_ERROR_CONFIG, "could not find key '%s' to delete", name);
goto out;
}
if ((result = git_regexp_compile(&preg, regexp, 0)) < 0)
goto out;
if ((result = config_file_write(b, name, key, &preg, NULL)) < 0)
goto out;
out:
git_config_entries_free(entries);
git__free(key);
git_regexp_dispose(&preg);
return result;
}
static int config_file_lock(git_config_backend *_cfg)
{
config_file_backend *cfg = GIT_CONTAINER_OF(_cfg, config_file_backend, parent);
int error;
if ((error = git_filebuf_open(&cfg->locked_buf, cfg->file.path, 0, GIT_CONFIG_FILE_MODE)) < 0)
return error;
error = git_futils_readbuffer(&cfg->locked_content, cfg->file.path);
if (error < 0 && error != GIT_ENOTFOUND) {
git_filebuf_cleanup(&cfg->locked_buf);
return error;
}
cfg->locked = true;
return 0;
}
static int config_file_unlock(git_config_backend *_cfg, int success)
{
config_file_backend *cfg = GIT_CONTAINER_OF(_cfg, config_file_backend, parent);
int error = 0;
if (success) {
git_filebuf_write(&cfg->locked_buf, cfg->locked_content.ptr, cfg->locked_content.size);
error = git_filebuf_commit(&cfg->locked_buf);
}
git_filebuf_cleanup(&cfg->locked_buf);
git_buf_dispose(&cfg->locked_content);
cfg->locked = false;
return error;
}
int git_config_backend_from_file(git_config_backend **out, const char *path)
{
config_file_backend *backend;
backend = git__calloc(1, sizeof(config_file_backend));
GIT_ERROR_CHECK_ALLOC(backend);
backend->parent.version = GIT_CONFIG_BACKEND_VERSION;
git_mutex_init(&backend->values_mutex);
backend->file.path = git__strdup(path);
GIT_ERROR_CHECK_ALLOC(backend->file.path);
git_array_init(backend->file.includes);
backend->parent.open = config_file_open;
backend->parent.get = config_file_get;
backend->parent.set = config_file_set;
backend->parent.set_multivar = config_file_set_multivar;
backend->parent.del = config_file_delete;
backend->parent.del_multivar = config_file_delete_multivar;
backend->parent.iterator = config_file_iterator;
backend->parent.snapshot = config_file_snapshot;
backend->parent.lock = config_file_lock;
backend->parent.unlock = config_file_unlock;
backend->parent.free = config_file_free;
*out = (git_config_backend *)backend;
return 0;
}
static int included_path(git_buf *out, const char *dir, const char *path)
{
/* From the user's home */
if (path[0] == '~' && path[1] == '/')
return git_sysdir_expand_global_file(out, &path[1]);
return git_path_join_unrooted(out, path, dir, NULL);
}
/* Escape the values to write them to the file */
static char *escape_value(const char *ptr)
{
git_buf buf;
size_t len;
const char *esc;
GIT_ASSERT_ARG_WITH_RETVAL(ptr, NULL);
len = strlen(ptr);
if (!len)
return git__calloc(1, sizeof(char));
if (git_buf_init(&buf, len) < 0)
return NULL;
while (*ptr != '\0') {
if ((esc = strchr(git_config_escaped, *ptr)) != NULL) {
git_buf_putc(&buf, '\\');
git_buf_putc(&buf, git_config_escapes[esc - git_config_escaped]);
} else {
git_buf_putc(&buf, *ptr);
}
ptr++;
}
if (git_buf_oom(&buf))
return NULL;
return git_buf_detach(&buf);
}
static int parse_include(config_file_parse_data *parse_data, const char *file)
{
config_file *include;
git_buf path = GIT_BUF_INIT;
char *dir;
int result;
if (!file)
return 0;
if ((result = git_path_dirname_r(&path, parse_data->file->path)) < 0)
return result;
dir = git_buf_detach(&path);
result = included_path(&path, dir, file);
git__free(dir);
if (result < 0)
return result;
include = git_array_alloc(parse_data->file->includes);
GIT_ERROR_CHECK_ALLOC(include);
memset(include, 0, sizeof(*include));
git_array_init(include->includes);
include->path = git_buf_detach(&path);
result = config_file_read(parse_data->entries, parse_data->repo, include,
parse_data->level, parse_data->depth+1);
if (result == GIT_ENOTFOUND) {
git_error_clear();
result = 0;
}
return result;
}
static int do_match_gitdir(
int *matches,
const git_repository *repo,
const char *cfg_file,
const char *condition,
bool case_insensitive)
{
git_buf pattern = GIT_BUF_INIT, gitdir = GIT_BUF_INIT;
int error;
if (condition[0] == '.' && git_path_is_dirsep(condition[1])) {
git_path_dirname_r(&pattern, cfg_file);
git_buf_joinpath(&pattern, pattern.ptr, condition + 2);
} else if (condition[0] == '~' && git_path_is_dirsep(condition[1]))
git_sysdir_expand_global_file(&pattern, condition + 1);
else if (!git_path_is_absolute(condition))
git_buf_joinpath(&pattern, "**", condition);
else
git_buf_sets(&pattern, condition);
if (git_path_is_dirsep(condition[strlen(condition) - 1]))
git_buf_puts(&pattern, "**");
if (git_buf_oom(&pattern)) {
error = -1;
goto out;
}
if ((error = git_repository_item_path(&gitdir, repo, GIT_REPOSITORY_ITEM_GITDIR)) < 0)
goto out;
if (git_path_is_dirsep(gitdir.ptr[gitdir.size - 1]))
git_buf_truncate(&gitdir, gitdir.size - 1);
*matches = wildmatch(pattern.ptr, gitdir.ptr,
WM_PATHNAME | (case_insensitive ? WM_CASEFOLD : 0)) == WM_MATCH;
out:
git_buf_dispose(&pattern);
git_buf_dispose(&gitdir);
return error;
}
static int conditional_match_gitdir(
int *matches,
const git_repository *repo,
const char *cfg_file,
const char *value)
{
return do_match_gitdir(matches, repo, cfg_file, value, false);
}
static int conditional_match_gitdir_i(
int *matches,
const git_repository *repo,
const char *cfg_file,
const char *value)
{
return do_match_gitdir(matches, repo, cfg_file, value, true);
}
static int conditional_match_onbranch(
int *matches,
const git_repository *repo,
const char *cfg_file,
const char *condition)
{
git_buf reference = GIT_BUF_INIT, buf = GIT_BUF_INIT;
int error;
GIT_UNUSED(cfg_file);
/*
* NOTE: you cannot use `git_repository_head` here. Looking up the
* HEAD reference will create the ODB, which causes us to read the
* repo's config for keys like core.precomposeUnicode. As we're
* just parsing the config right now, though, this would result in
* an endless recursion.
*/
if ((error = git_buf_joinpath(&buf, git_repository_path(repo), GIT_HEAD_FILE)) < 0 ||
(error = git_futils_readbuffer(&reference, buf.ptr)) < 0)
goto out;
git_buf_rtrim(&reference);
if (git__strncmp(reference.ptr, GIT_SYMREF, strlen(GIT_SYMREF)))
goto out;
git_buf_consume(&reference, reference.ptr + strlen(GIT_SYMREF));
if (git__strncmp(reference.ptr, GIT_REFS_HEADS_DIR, strlen(GIT_REFS_HEADS_DIR)))
goto out;
git_buf_consume(&reference, reference.ptr + strlen(GIT_REFS_HEADS_DIR));
/*
* If the condition ends with a '/', then we should treat it as if
* it had '**' appended.
*/
if ((error = git_buf_sets(&buf, condition)) < 0)
goto out;
if (git_path_is_dirsep(condition[strlen(condition) - 1]) &&
(error = git_buf_puts(&buf, "**")) < 0)
goto out;
*matches = wildmatch(buf.ptr, reference.ptr, WM_PATHNAME) == WM_MATCH;
out:
git_buf_dispose(&reference);
git_buf_dispose(&buf);
return error;
}
static const struct {
const char *prefix;
int (*matches)(int *matches, const git_repository *repo, const char *cfg, const char *value);
} conditions[] = {
{ "gitdir:", conditional_match_gitdir },
{ "gitdir/i:", conditional_match_gitdir_i },
{ "onbranch:", conditional_match_onbranch }
};
static int parse_conditional_include(config_file_parse_data *parse_data, const char *section, const char *file)
{
char *condition;
size_t i;
int error = 0, matches;
if (!parse_data->repo || !file)
return 0;
condition = git__substrdup(section + strlen("includeIf."),
strlen(section) - strlen("includeIf.") - strlen(".path"));
for (i = 0; i < ARRAY_SIZE(conditions); i++) {
if (git__prefixcmp(condition, conditions[i].prefix))
continue;
if ((error = conditions[i].matches(&matches,
parse_data->repo,
parse_data->file->path,
condition + strlen(conditions[i].prefix))) < 0)
break;
if (matches)
error = parse_include(parse_data, file);
break;
}
git__free(condition);
return error;
}
static int read_on_variable(
git_config_parser *reader,
const char *current_section,
const char *var_name,
const char *var_value,
const char *line,
size_t line_len,
void *data)
{
config_file_parse_data *parse_data = (config_file_parse_data *)data;
git_buf buf = GIT_BUF_INIT;
git_config_entry *entry;
const char *c;
int result = 0;
GIT_UNUSED(reader);
GIT_UNUSED(line);
GIT_UNUSED(line_len);
if (current_section) {
/* TODO: Once warnings lang, we should likely warn
* here. Git appears to warn in most cases if it sees
* un-namespaced config options.
*/
git_buf_puts(&buf, current_section);
git_buf_putc(&buf, '.');
}
for (c = var_name; *c; c++)
git_buf_putc(&buf, git__tolower(*c));
if (git_buf_oom(&buf))
return -1;
entry = git__calloc(1, sizeof(git_config_entry));
GIT_ERROR_CHECK_ALLOC(entry);
entry->name = git_buf_detach(&buf);
entry->value = var_value ? git__strdup(var_value) : NULL;
entry->level = parse_data->level;
entry->include_depth = parse_data->depth;
if ((result = git_config_entries_append(parse_data->entries, entry)) < 0)
return result;
result = 0;
/* Add or append the new config option */
if (!git__strcmp(entry->name, "include.path"))
result = parse_include(parse_data, entry->value);
else if (!git__prefixcmp(entry->name, "includeif.") &&
!git__suffixcmp(entry->name, ".path"))
result = parse_conditional_include(parse_data, entry->name, entry->value);
return result;
}
static int config_file_read_buffer(
git_config_entries *entries,
const git_repository *repo,
config_file *file,
git_config_level_t level,
int depth,
const char *buf,
size_t buflen)
{
config_file_parse_data parse_data;
git_config_parser reader;
int error;
if (depth >= MAX_INCLUDE_DEPTH) {
git_error_set(GIT_ERROR_CONFIG, "maximum config include depth reached");
return -1;
}
/* Initialize the reading position */
reader.path = file->path;
git_parse_ctx_init(&reader.ctx, buf, buflen);
/* If the file is empty, there's nothing for us to do */
if (!reader.ctx.content || *reader.ctx.content == '\0') {
error = 0;
goto out;
}
parse_data.repo = repo;
parse_data.file = file;
parse_data.entries = entries;
parse_data.level = level;
parse_data.depth = depth;
error = git_config_parse(&reader, NULL, read_on_variable, NULL, NULL, &parse_data);
out:
return error;
}
static int config_file_read(
git_config_entries *entries,
const git_repository *repo,
config_file *file,
git_config_level_t level,
int depth)
{
git_buf contents = GIT_BUF_INIT;
struct stat st;
int error;
if (p_stat(file->path, &st) < 0) {
error = git_path_set_error(errno, file->path, "stat");
goto out;
}
if ((error = git_futils_readbuffer(&contents, file->path)) < 0)
goto out;
git_futils_filestamp_set_from_stat(&file->stamp, &st);
if ((error = git_hash_buf(&file->checksum, contents.ptr, contents.size)) < 0)
goto out;
if ((error = config_file_read_buffer(entries, repo, file, level, depth,
contents.ptr, contents.size)) < 0)
goto out;
out:
git_buf_dispose(&contents);
return error;
}
static int write_section(git_buf *fbuf, const char *key)
{
int result;
const char *dot;
git_buf buf = GIT_BUF_INIT;
/* All of this just for [section "subsection"] */
dot = strchr(key, '.');
git_buf_putc(&buf, '[');
if (dot == NULL) {
git_buf_puts(&buf, key);
} else {
char *escaped;
git_buf_put(&buf, key, dot - key);
escaped = escape_value(dot + 1);
GIT_ERROR_CHECK_ALLOC(escaped);
git_buf_printf(&buf, " \"%s\"", escaped);
git__free(escaped);
}
git_buf_puts(&buf, "]\n");
if (git_buf_oom(&buf))
return -1;
result = git_buf_put(fbuf, git_buf_cstr(&buf), buf.size);
git_buf_dispose(&buf);
return result;
}
static const char *quotes_for_value(const char *value)
{
const char *ptr;
if (value[0] == ' ' || value[0] == '\0')
return "\"";
for (ptr = value; *ptr; ++ptr) {
if (*ptr == ';' || *ptr == '#')
return "\"";
}
if (ptr[-1] == ' ')
return "\"";
return "";
}
struct write_data {
git_buf *buf;
git_buf buffered_comment;
unsigned int in_section : 1,
preg_replaced : 1;
const char *orig_section;
const char *section;
const char *orig_name;
const char *name;
const git_regexp *preg;
const char *value;
};
static int write_line_to(git_buf *buf, const char *line, size_t line_len)
{
int result = git_buf_put(buf, line, line_len);
if (!result && line_len && line[line_len-1] != '\n')
result = git_buf_printf(buf, "\n");
return result;
}
static int write_line(struct write_data *write_data, const char *line, size_t line_len)
{
return write_line_to(write_data->buf, line, line_len);
}
static int write_value(struct write_data *write_data)
{
const char *q;
int result;
q = quotes_for_value(write_data->value);
result = git_buf_printf(write_data->buf,
"\t%s = %s%s%s\n", write_data->orig_name, q, write_data->value, q);
/* If we are updating a single name/value, we're done. Setting `value`
* to `NULL` will prevent us from trying to write it again later (in
* `write_on_section`) if we see the same section repeated.
*/
if (!write_data->preg)
write_data->value = NULL;
return result;
}
static int write_on_section(
git_config_parser *reader,
const char *current_section,
const char *line,
size_t line_len,
void *data)
{
struct write_data *write_data = (struct write_data *)data;
int result = 0;
GIT_UNUSED(reader);
/* If we were previously in the correct section (but aren't anymore)
* and haven't written our value (for a simple name/value set, not
* a multivar), then append it to the end of the section before writing
* the new one.
*/
if (write_data->in_section && !write_data->preg && write_data->value)
result = write_value(write_data);
write_data->in_section = strcmp(current_section, write_data->section) == 0;
/*
* If there were comments just before this section, dump them as well.
*/
if (!result) {
result = git_buf_put(write_data->buf, write_data->buffered_comment.ptr, write_data->buffered_comment.size);
git_buf_clear(&write_data->buffered_comment);
}
if (!result)
result = write_line(write_data, line, line_len);
return result;
}
static int write_on_variable(
git_config_parser *reader,
const char *current_section,
const char *var_name,
const char *var_value,
const char *line,
size_t line_len,
void *data)
{
struct write_data *write_data = (struct write_data *)data;
bool has_matched = false;
int error;
GIT_UNUSED(reader);
GIT_UNUSED(current_section);
/*
* If there were comments just before this variable, let's dump them as well.
*/
if ((error = git_buf_put(write_data->buf, write_data->buffered_comment.ptr, write_data->buffered_comment.size)) < 0)
return error;
git_buf_clear(&write_data->buffered_comment);
/* See if we are to update this name/value pair; first examine name */
if (write_data->in_section &&
strcasecmp(write_data->name, var_name) == 0)
has_matched = true;
/* If we have a regex to match the value, see if it matches */
if (has_matched && write_data->preg != NULL)
has_matched = (git_regexp_match(write_data->preg, var_value) == 0);
/* If this isn't the name/value we're looking for, simply dump the
* existing data back out and continue on.
*/
if (!has_matched)
return write_line(write_data, line, line_len);
write_data->preg_replaced = 1;
/* If value is NULL, we are deleting this value; write nothing. */
if (!write_data->value)
return 0;
return write_value(write_data);
}
static int write_on_comment(git_config_parser *reader, const char *line, size_t line_len, void *data)
{
struct write_data *write_data;
GIT_UNUSED(reader);
write_data = (struct write_data *)data;
return write_line_to(&write_data->buffered_comment, line, line_len);
}
static int write_on_eof(
git_config_parser *reader, const char *current_section, void *data)
{
struct write_data *write_data = (struct write_data *)data;
int result = 0;
GIT_UNUSED(reader);
/*
* If we've buffered comments when reaching EOF, make sure to dump them.
*/
if ((result = git_buf_put(write_data->buf, write_data->buffered_comment.ptr, write_data->buffered_comment.size)) < 0)
return result;
/* If we are at the EOF and have not written our value (again, for a
* simple name/value set, not a multivar) then we have never seen the
* section in question and should create a new section and write the
* value.
*/
if ((!write_data->preg || !write_data->preg_replaced) && write_data->value) {
/* write the section header unless we're already in it */
if (!current_section || strcmp(current_section, write_data->section))
result = write_section(write_data->buf, write_data->orig_section);
if (!result)
result = write_value(write_data);
}
return result;
}
/*
* This is pretty much the parsing, except we write out anything we don't have
*/
static int config_file_write(config_file_backend *cfg, const char *orig_key, const char *key, const git_regexp *preg, const char *value)
{
char *orig_section = NULL, *section = NULL, *orig_name, *name, *ldot;
git_buf buf = GIT_BUF_INIT, contents = GIT_BUF_INIT;
git_config_parser parser = GIT_CONFIG_PARSER_INIT;
git_filebuf file = GIT_FILEBUF_INIT;
struct write_data write_data;
int error;
memset(&write_data, 0, sizeof(write_data));
if (cfg->locked) {
error = git_buf_puts(&contents, git_buf_cstr(&cfg->locked_content) == NULL ? "" : git_buf_cstr(&cfg->locked_content));
} else {
if ((error = git_filebuf_open(&file, cfg->file.path, GIT_FILEBUF_HASH_CONTENTS,
GIT_CONFIG_FILE_MODE)) < 0)
goto done;
/* We need to read in our own config file */
error = git_futils_readbuffer(&contents, cfg->file.path);
}
if (error < 0 && error != GIT_ENOTFOUND)
goto done;
if ((git_config_parser_init(&parser, cfg->file.path, contents.ptr, contents.size)) < 0)
goto done;
ldot = strrchr(key, '.');
name = ldot + 1;
section = git__strndup(key, ldot - key);
GIT_ERROR_CHECK_ALLOC(section);
ldot = strrchr(orig_key, '.');
orig_name = ldot + 1;
orig_section = git__strndup(orig_key, ldot - orig_key);
GIT_ERROR_CHECK_ALLOC(orig_section);
write_data.buf = &buf;
write_data.orig_section = orig_section;
write_data.section = section;
write_data.orig_name = orig_name;
write_data.name = name;
write_data.preg = preg;
write_data.value = value;
if ((error = git_config_parse(&parser, write_on_section, write_on_variable,
write_on_comment, write_on_eof, &write_data)) < 0)
goto done;
if (cfg->locked) {
size_t len = buf.asize;
/* Update our copy with the modified contents */
git_buf_dispose(&cfg->locked_content);
git_buf_attach(&cfg->locked_content, git_buf_detach(&buf), len);
} else {
git_filebuf_write(&file, git_buf_cstr(&buf), git_buf_len(&buf));
if ((error = git_filebuf_commit(&file)) < 0)
goto done;
if ((error = config_file_refresh_from_buffer(&cfg->parent, buf.ptr, buf.size)) < 0)
goto done;
}
done:
git__free(section);
git__free(orig_section);
git_buf_dispose(&write_data.buffered_comment);
git_buf_dispose(&buf);
git_buf_dispose(&contents);
git_filebuf_cleanup(&file);
git_config_parser_dispose(&parser);
return error;
}
|
0 |
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2
|
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2/src/integer.h
|
/*
* Copyright (C) the libgit2 contributors. All rights reserved.
*
* This file is part of libgit2, distributed under the GNU GPL v2 with
* a Linking Exception. For full terms see the included COPYING file.
*/
#ifndef INCLUDE_integer_h__
#define INCLUDE_integer_h__
/** @return true if p fits into the range of a size_t */
GIT_INLINE(int) git__is_sizet(int64_t p)
{
size_t r = (size_t)p;
return p == (int64_t)r;
}
/** @return true if p fits into the range of an ssize_t */
GIT_INLINE(int) git__is_ssizet(size_t p)
{
ssize_t r = (ssize_t)p;
return p == (size_t)r;
}
/** @return true if p fits into the range of a uint16_t */
GIT_INLINE(int) git__is_uint16(size_t p)
{
uint16_t r = (uint16_t)p;
return p == (size_t)r;
}
/** @return true if p fits into the range of a uint32_t */
GIT_INLINE(int) git__is_uint32(size_t p)
{
uint32_t r = (uint32_t)p;
return p == (size_t)r;
}
/** @return true if p fits into the range of an unsigned long */
GIT_INLINE(int) git__is_ulong(int64_t p)
{
unsigned long r = (unsigned long)p;
return p == (int64_t)r;
}
/** @return true if p fits into the range of an int */
GIT_INLINE(int) git__is_int(int64_t p)
{
int r = (int)p;
return p == (int64_t)r;
}
/* Use clang/gcc compiler intrinsics whenever possible */
#if (__has_builtin(__builtin_add_overflow) || \
(defined(__GNUC__) && (__GNUC__ >= 5)))
# if (SIZE_MAX == UINT_MAX)
# define git__add_sizet_overflow(out, one, two) \
__builtin_uadd_overflow(one, two, out)
# define git__multiply_sizet_overflow(out, one, two) \
__builtin_umul_overflow(one, two, out)
# elif (SIZE_MAX == ULONG_MAX)
# define git__add_sizet_overflow(out, one, two) \
__builtin_uaddl_overflow(one, two, out)
# define git__multiply_sizet_overflow(out, one, two) \
__builtin_umull_overflow(one, two, out)
# elif (SIZE_MAX == ULLONG_MAX)
# define git__add_sizet_overflow(out, one, two) \
__builtin_uaddll_overflow(one, two, out)
# define git__multiply_sizet_overflow(out, one, two) \
__builtin_umulll_overflow(one, two, out)
# else
# error compiler has add with overflow intrinsics but SIZE_MAX is unknown
# endif
# define git__add_int_overflow(out, one, two) \
__builtin_sadd_overflow(one, two, out)
# define git__sub_int_overflow(out, one, two) \
__builtin_ssub_overflow(one, two, out)
# define git__add_int64_overflow(out, one, two) \
__builtin_add_overflow(one, two, out)
/* clang on 32-bit systems produces an undefined reference to `__mulodi4`. */
# if !defined(__clang__) || !defined(GIT_ARCH_32)
# define git__multiply_int64_overflow(out, one, two) \
__builtin_mul_overflow(one, two, out)
# endif
/* Use Microsoft's safe integer handling functions where available */
#elif defined(_MSC_VER)
# define ENABLE_INTSAFE_SIGNED_FUNCTIONS
# include <intsafe.h>
# define git__add_sizet_overflow(out, one, two) \
(SizeTAdd(one, two, out) != S_OK)
# define git__multiply_sizet_overflow(out, one, two) \
(SizeTMult(one, two, out) != S_OK)
#define git__add_int_overflow(out, one, two) \
(IntAdd(one, two, out) != S_OK)
#define git__sub_int_overflow(out, one, two) \
(IntSub(one, two, out) != S_OK)
#define git__add_int64_overflow(out, one, two) \
(LongLongAdd(one, two, out) != S_OK)
#define git__multiply_int64_overflow(out, one, two) \
(LongLongMult(one, two, out) != S_OK)
#else
/**
* Sets `one + two` into `out`, unless the arithmetic would overflow.
* @return false if the result fits in a `size_t`, true on overflow.
*/
GIT_INLINE(bool) git__add_sizet_overflow(size_t *out, size_t one, size_t two)
{
if (SIZE_MAX - one < two)
return true;
*out = one + two;
return false;
}
/**
* Sets `one * two` into `out`, unless the arithmetic would overflow.
* @return false if the result fits in a `size_t`, true on overflow.
*/
GIT_INLINE(bool) git__multiply_sizet_overflow(size_t *out, size_t one, size_t two)
{
if (one && SIZE_MAX / one < two)
return true;
*out = one * two;
return false;
}
GIT_INLINE(bool) git__add_int_overflow(int *out, int one, int two)
{
if ((two > 0 && one > (INT_MAX - two)) ||
(two < 0 && one < (INT_MIN - two)))
return true;
*out = one + two;
return false;
}
GIT_INLINE(bool) git__sub_int_overflow(int *out, int one, int two)
{
if ((two > 0 && one < (INT_MIN + two)) ||
(two < 0 && one > (INT_MAX + two)))
return true;
*out = one - two;
return false;
}
GIT_INLINE(bool) git__add_int64_overflow(int64_t *out, int64_t one, int64_t two)
{
if ((two > 0 && one > (INT64_MAX - two)) ||
(two < 0 && one < (INT64_MIN - two)))
return true;
*out = one + two;
return false;
}
#endif
/* If we could not provide an intrinsic implementation for this, provide a (slow) fallback. */
#if !defined(git__multiply_int64_overflow)
GIT_INLINE(bool) git__multiply_int64_overflow(int64_t *out, int64_t one, int64_t two)
{
/*
* Detects whether `INT64_MAX < (one * two) || INT64_MIN > (one * two)`,
* without incurring in undefined behavior. That is done by performing the
* comparison with a division instead of a multiplication, which translates
* to `INT64_MAX / one < two || INT64_MIN / one > two`. Some caveats:
*
* - The comparison sign is inverted when both sides of the inequality are
* multiplied/divided by a negative number, so if `one < 0` the comparison
* needs to be flipped.
* - `INT64_MAX / -1` itself overflows (or traps), so that case should be
* avoided.
* - Since the overflow flag is defined as the discrepance between the result
* of performing the multiplication in a signed integer at twice the width
* of the operands, and the truncated+sign-extended version of that same
* result, there are four cases where the result is the opposite of what
* would be expected:
* * `INT64_MIN * -1` / `-1 * INT64_MIN`
* * `INT64_MIN * 1 / `1 * INT64_MIN`
*/
if (one && two) {
if (one > 0 && two > 0) {
if (INT64_MAX / one < two)
return true;
} else if (one < 0 && two < 0) {
if ((one == -1 && two == INT64_MIN) ||
(two == -1 && one == INT64_MIN)) {
*out = INT64_MIN;
return false;
}
if (INT64_MAX / one > two)
return true;
} else if (one > 0 && two < 0) {
if ((one == 1 && two == INT64_MIN) ||
(INT64_MIN / one > two))
return true;
} else if (one == -1) {
if (INT64_MIN / two > one)
return true;
} else {
if ((one == INT64_MIN && two == 1) ||
(INT64_MIN / one < two))
return true;
}
}
*out = one * two;
return false;
}
#endif
#endif
|
0 |
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2
|
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2/src/tag.c
|
/*
* Copyright (C) the libgit2 contributors. All rights reserved.
*
* This file is part of libgit2, distributed under the GNU GPL v2 with
* a Linking Exception. For full terms see the included COPYING file.
*/
#include "tag.h"
#include "commit.h"
#include "signature.h"
#include "message.h"
#include "wildmatch.h"
#include "git2/object.h"
#include "git2/repository.h"
#include "git2/signature.h"
#include "git2/odb_backend.h"
void git_tag__free(void *_tag)
{
git_tag *tag = _tag;
git_signature_free(tag->tagger);
git__free(tag->message);
git__free(tag->tag_name);
git__free(tag);
}
int git_tag_target(git_object **target, const git_tag *t)
{
GIT_ASSERT_ARG(t);
return git_object_lookup(target, t->object.repo, &t->target, t->type);
}
const git_oid *git_tag_target_id(const git_tag *t)
{
GIT_ASSERT_ARG_WITH_RETVAL(t, NULL);
return &t->target;
}
git_object_t git_tag_target_type(const git_tag *t)
{
GIT_ASSERT_ARG_WITH_RETVAL(t, GIT_OBJECT_INVALID);
return t->type;
}
const char *git_tag_name(const git_tag *t)
{
GIT_ASSERT_ARG_WITH_RETVAL(t, NULL);
return t->tag_name;
}
const git_signature *git_tag_tagger(const git_tag *t)
{
return t->tagger;
}
const char *git_tag_message(const git_tag *t)
{
GIT_ASSERT_ARG_WITH_RETVAL(t, NULL);
return t->message;
}
static int tag_error(const char *str)
{
git_error_set(GIT_ERROR_TAG, "failed to parse tag: %s", str);
return -1;
}
static int tag_parse(git_tag *tag, const char *buffer, const char *buffer_end)
{
static const char *tag_types[] = {
NULL, "commit\n", "tree\n", "blob\n", "tag\n"
};
size_t text_len, alloc_len;
const char *search;
unsigned int i;
if (git_oid__parse(&tag->target, &buffer, buffer_end, "object ") < 0)
return tag_error("object field invalid");
if (buffer + 5 >= buffer_end)
return tag_error("object too short");
if (memcmp(buffer, "type ", 5) != 0)
return tag_error("type field not found");
buffer += 5;
tag->type = GIT_OBJECT_INVALID;
for (i = 1; i < ARRAY_SIZE(tag_types); ++i) {
size_t type_length = strlen(tag_types[i]);
if (buffer + type_length >= buffer_end)
return tag_error("object too short");
if (memcmp(buffer, tag_types[i], type_length) == 0) {
tag->type = i;
buffer += type_length;
break;
}
}
if (tag->type == GIT_OBJECT_INVALID)
return tag_error("invalid object type");
if (buffer + 4 >= buffer_end)
return tag_error("object too short");
if (memcmp(buffer, "tag ", 4) != 0)
return tag_error("tag field not found");
buffer += 4;
search = memchr(buffer, '\n', buffer_end - buffer);
if (search == NULL)
return tag_error("object too short");
text_len = search - buffer;
GIT_ERROR_CHECK_ALLOC_ADD(&alloc_len, text_len, 1);
tag->tag_name = git__malloc(alloc_len);
GIT_ERROR_CHECK_ALLOC(tag->tag_name);
memcpy(tag->tag_name, buffer, text_len);
tag->tag_name[text_len] = '\0';
buffer = search + 1;
tag->tagger = NULL;
if (buffer < buffer_end && *buffer != '\n') {
tag->tagger = git__malloc(sizeof(git_signature));
GIT_ERROR_CHECK_ALLOC(tag->tagger);
if (git_signature__parse(tag->tagger, &buffer, buffer_end, "tagger ", '\n') < 0)
return -1;
}
tag->message = NULL;
if (buffer < buffer_end) {
/* If we're not at the end of the header, search for it */
if(*buffer != '\n') {
search = git__memmem(buffer, buffer_end - buffer,
"\n\n", 2);
if (search)
buffer = search + 1;
else
return tag_error("tag contains no message");
}
text_len = buffer_end - ++buffer;
GIT_ERROR_CHECK_ALLOC_ADD(&alloc_len, text_len, 1);
tag->message = git__malloc(alloc_len);
GIT_ERROR_CHECK_ALLOC(tag->message);
memcpy(tag->message, buffer, text_len);
tag->message[text_len] = '\0';
}
return 0;
}
int git_tag__parse_raw(void *_tag, const char *data, size_t size)
{
return tag_parse(_tag, data, data + size);
}
int git_tag__parse(void *_tag, git_odb_object *odb_obj)
{
git_tag *tag = _tag;
const char *buffer = git_odb_object_data(odb_obj);
const char *buffer_end = buffer + git_odb_object_size(odb_obj);
return tag_parse(tag, buffer, buffer_end);
}
static int retrieve_tag_reference(
git_reference **tag_reference_out,
git_buf *ref_name_out,
git_repository *repo,
const char *tag_name)
{
git_reference *tag_ref;
int error;
*tag_reference_out = NULL;
if (git_buf_joinpath(ref_name_out, GIT_REFS_TAGS_DIR, tag_name) < 0)
return -1;
error = git_reference_lookup(&tag_ref, repo, ref_name_out->ptr);
if (error < 0)
return error; /* Be it not foundo or corrupted */
*tag_reference_out = tag_ref;
return 0;
}
static int retrieve_tag_reference_oid(
git_oid *oid,
git_buf *ref_name_out,
git_repository *repo,
const char *tag_name)
{
if (git_buf_joinpath(ref_name_out, GIT_REFS_TAGS_DIR, tag_name) < 0)
return -1;
return git_reference_name_to_id(oid, repo, ref_name_out->ptr);
}
static int write_tag_annotation(
git_oid *oid,
git_repository *repo,
const char *tag_name,
const git_object *target,
const git_signature *tagger,
const char *message)
{
git_buf tag = GIT_BUF_INIT;
git_odb *odb;
git_oid__writebuf(&tag, "object ", git_object_id(target));
git_buf_printf(&tag, "type %s\n", git_object_type2string(git_object_type(target)));
git_buf_printf(&tag, "tag %s\n", tag_name);
git_signature__writebuf(&tag, "tagger ", tagger);
git_buf_putc(&tag, '\n');
if (git_buf_puts(&tag, message) < 0)
goto on_error;
if (git_repository_odb__weakptr(&odb, repo) < 0)
goto on_error;
if (git_odb_write(oid, odb, tag.ptr, tag.size, GIT_OBJECT_TAG) < 0)
goto on_error;
git_buf_dispose(&tag);
return 0;
on_error:
git_buf_dispose(&tag);
git_error_set(GIT_ERROR_OBJECT, "failed to create tag annotation");
return -1;
}
static int git_tag_create__internal(
git_oid *oid,
git_repository *repo,
const char *tag_name,
const git_object *target,
const git_signature *tagger,
const char *message,
int allow_ref_overwrite,
int create_tag_annotation)
{
git_reference *new_ref = NULL;
git_buf ref_name = GIT_BUF_INIT;
int error;
GIT_ASSERT_ARG(repo);
GIT_ASSERT_ARG(tag_name);
GIT_ASSERT_ARG(target);
GIT_ASSERT_ARG(!create_tag_annotation || (tagger && message));
if (git_object_owner(target) != repo) {
git_error_set(GIT_ERROR_INVALID, "the given target does not belong to this repository");
return -1;
}
error = retrieve_tag_reference_oid(oid, &ref_name, repo, tag_name);
if (error < 0 && error != GIT_ENOTFOUND)
goto cleanup;
/** Ensure the tag name doesn't conflict with an already existing
* reference unless overwriting has explicitly been requested **/
if (error == 0 && !allow_ref_overwrite) {
git_buf_dispose(&ref_name);
git_error_set(GIT_ERROR_TAG, "tag already exists");
return GIT_EEXISTS;
}
if (create_tag_annotation) {
if (write_tag_annotation(oid, repo, tag_name, target, tagger, message) < 0)
return -1;
} else
git_oid_cpy(oid, git_object_id(target));
error = git_reference_create(&new_ref, repo, ref_name.ptr, oid, allow_ref_overwrite, NULL);
cleanup:
git_reference_free(new_ref);
git_buf_dispose(&ref_name);
return error;
}
int git_tag_create(
git_oid *oid,
git_repository *repo,
const char *tag_name,
const git_object *target,
const git_signature *tagger,
const char *message,
int allow_ref_overwrite)
{
return git_tag_create__internal(oid, repo, tag_name, target, tagger, message, allow_ref_overwrite, 1);
}
int git_tag_annotation_create(
git_oid *oid,
git_repository *repo,
const char *tag_name,
const git_object *target,
const git_signature *tagger,
const char *message)
{
GIT_ASSERT_ARG(oid);
GIT_ASSERT_ARG(repo);
GIT_ASSERT_ARG(tag_name);
GIT_ASSERT_ARG(target);
GIT_ASSERT_ARG(tagger);
GIT_ASSERT_ARG(message);
return write_tag_annotation(oid, repo, tag_name, target, tagger, message);
}
int git_tag_create_lightweight(
git_oid *oid,
git_repository *repo,
const char *tag_name,
const git_object *target,
int allow_ref_overwrite)
{
return git_tag_create__internal(oid, repo, tag_name, target, NULL, NULL, allow_ref_overwrite, 0);
}
int git_tag_create_from_buffer(git_oid *oid, git_repository *repo, const char *buffer, int allow_ref_overwrite)
{
git_tag tag;
int error;
git_odb *odb;
git_odb_stream *stream;
git_odb_object *target_obj;
git_reference *new_ref = NULL;
git_buf ref_name = GIT_BUF_INIT;
GIT_ASSERT_ARG(oid);
GIT_ASSERT_ARG(buffer);
memset(&tag, 0, sizeof(tag));
if (git_repository_odb__weakptr(&odb, repo) < 0)
return -1;
/* validate the buffer */
if (tag_parse(&tag, buffer, buffer + strlen(buffer)) < 0)
return -1;
/* validate the target */
if (git_odb_read(&target_obj, odb, &tag.target) < 0)
goto on_error;
if (tag.type != target_obj->cached.type) {
git_error_set(GIT_ERROR_TAG, "the type for the given target is invalid");
goto on_error;
}
error = retrieve_tag_reference_oid(oid, &ref_name, repo, tag.tag_name);
if (error < 0 && error != GIT_ENOTFOUND)
goto on_error;
/* We don't need these objects after this */
git_signature_free(tag.tagger);
git__free(tag.tag_name);
git__free(tag.message);
git_odb_object_free(target_obj);
/** Ensure the tag name doesn't conflict with an already existing
* reference unless overwriting has explicitly been requested **/
if (error == 0 && !allow_ref_overwrite) {
git_error_set(GIT_ERROR_TAG, "tag already exists");
return GIT_EEXISTS;
}
/* write the buffer */
if ((error = git_odb_open_wstream(
&stream, odb, strlen(buffer), GIT_OBJECT_TAG)) < 0)
return error;
if (!(error = git_odb_stream_write(stream, buffer, strlen(buffer))))
error = git_odb_stream_finalize_write(oid, stream);
git_odb_stream_free(stream);
if (error < 0) {
git_buf_dispose(&ref_name);
return error;
}
error = git_reference_create(
&new_ref, repo, ref_name.ptr, oid, allow_ref_overwrite, NULL);
git_reference_free(new_ref);
git_buf_dispose(&ref_name);
return error;
on_error:
git_signature_free(tag.tagger);
git__free(tag.tag_name);
git__free(tag.message);
git_odb_object_free(target_obj);
return -1;
}
int git_tag_delete(git_repository *repo, const char *tag_name)
{
git_reference *tag_ref;
git_buf ref_name = GIT_BUF_INIT;
int error;
error = retrieve_tag_reference(&tag_ref, &ref_name, repo, tag_name);
git_buf_dispose(&ref_name);
if (error < 0)
return error;
error = git_reference_delete(tag_ref);
git_reference_free(tag_ref);
return error;
}
typedef struct {
git_repository *repo;
git_tag_foreach_cb cb;
void *cb_data;
} tag_cb_data;
static int tags_cb(const char *ref, void *data)
{
int error;
git_oid oid;
tag_cb_data *d = (tag_cb_data *)data;
if (git__prefixcmp(ref, GIT_REFS_TAGS_DIR) != 0)
return 0; /* no tag */
if (!(error = git_reference_name_to_id(&oid, d->repo, ref))) {
if ((error = d->cb(ref, &oid, d->cb_data)) != 0)
git_error_set_after_callback_function(error, "git_tag_foreach");
}
return error;
}
int git_tag_foreach(git_repository *repo, git_tag_foreach_cb cb, void *cb_data)
{
tag_cb_data data;
GIT_ASSERT_ARG(repo);
GIT_ASSERT_ARG(cb);
data.cb = cb;
data.cb_data = cb_data;
data.repo = repo;
return git_reference_foreach_name(repo, &tags_cb, &data);
}
typedef struct {
git_vector *taglist;
const char *pattern;
} tag_filter_data;
#define GIT_REFS_TAGS_DIR_LEN strlen(GIT_REFS_TAGS_DIR)
static int tag_list_cb(const char *tag_name, git_oid *oid, void *data)
{
tag_filter_data *filter = (tag_filter_data *)data;
GIT_UNUSED(oid);
if (!*filter->pattern ||
wildmatch(filter->pattern, tag_name + GIT_REFS_TAGS_DIR_LEN, 0) == 0)
{
char *matched = git__strdup(tag_name + GIT_REFS_TAGS_DIR_LEN);
GIT_ERROR_CHECK_ALLOC(matched);
return git_vector_insert(filter->taglist, matched);
}
return 0;
}
int git_tag_list_match(git_strarray *tag_names, const char *pattern, git_repository *repo)
{
int error;
tag_filter_data filter;
git_vector taglist;
GIT_ASSERT_ARG(tag_names);
GIT_ASSERT_ARG(repo);
GIT_ASSERT_ARG(pattern);
if ((error = git_vector_init(&taglist, 8, NULL)) < 0)
return error;
filter.taglist = &taglist;
filter.pattern = pattern;
error = git_tag_foreach(repo, &tag_list_cb, (void *)&filter);
if (error < 0)
git_vector_free(&taglist);
tag_names->strings =
(char **)git_vector_detach(&tag_names->count, NULL, &taglist);
return 0;
}
int git_tag_list(git_strarray *tag_names, git_repository *repo)
{
return git_tag_list_match(tag_names, "", repo);
}
int git_tag_peel(git_object **tag_target, const git_tag *tag)
{
return git_object_peel(tag_target, (const git_object *)tag, GIT_OBJECT_ANY);
}
int git_tag_name_is_valid(int *valid, const char *name)
{
git_buf ref_name = GIT_BUF_INIT;
int error = 0;
GIT_ASSERT(valid);
/*
* Discourage tag name starting with dash,
* https://github.com/git/git/commit/4f0accd638b8d2
*/
if (!name || name[0] == '-')
goto done;
if ((error = git_buf_puts(&ref_name, GIT_REFS_TAGS_DIR)) < 0 ||
(error = git_buf_puts(&ref_name, name)) < 0)
goto done;
error = git_reference_name_is_valid(valid, ref_name.ptr);
done:
git_buf_dispose(&ref_name);
return error;
}
/* Deprecated Functions */
#ifndef GIT_DEPRECATE_HARD
int git_tag_create_frombuffer(git_oid *oid, git_repository *repo, const char *buffer, int allow_ref_overwrite)
{
return git_tag_create_from_buffer(oid, repo, buffer, allow_ref_overwrite);
}
#endif
|
0 |
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2
|
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2/src/sortedcache.c
|
/*
* Copyright (C) the libgit2 contributors. All rights reserved.
*
* This file is part of libgit2, distributed under the GNU GPL v2 with
* a Linking Exception. For full terms see the included COPYING file.
*/
#include "sortedcache.h"
int git_sortedcache_new(
git_sortedcache **out,
size_t item_path_offset,
git_sortedcache_free_item_fn free_item,
void *free_item_payload,
git_vector_cmp item_cmp,
const char *path)
{
git_sortedcache *sc;
size_t pathlen, alloclen;
pathlen = path ? strlen(path) : 0;
GIT_ERROR_CHECK_ALLOC_ADD(&alloclen, sizeof(git_sortedcache), pathlen);
GIT_ERROR_CHECK_ALLOC_ADD(&alloclen, alloclen, 1);
sc = git__calloc(1, alloclen);
GIT_ERROR_CHECK_ALLOC(sc);
if (git_pool_init(&sc->pool, 1) < 0 ||
git_vector_init(&sc->items, 4, item_cmp) < 0 ||
git_strmap_new(&sc->map) < 0)
goto fail;
if (git_rwlock_init(&sc->lock)) {
git_error_set(GIT_ERROR_OS, "failed to initialize lock");
goto fail;
}
sc->item_path_offset = item_path_offset;
sc->free_item = free_item;
sc->free_item_payload = free_item_payload;
GIT_REFCOUNT_INC(sc);
if (pathlen)
memcpy(sc->path, path, pathlen);
*out = sc;
return 0;
fail:
git_strmap_free(sc->map);
git_vector_free(&sc->items);
git_pool_clear(&sc->pool);
git__free(sc);
return -1;
}
void git_sortedcache_incref(git_sortedcache *sc)
{
GIT_REFCOUNT_INC(sc);
}
const char *git_sortedcache_path(git_sortedcache *sc)
{
return sc->path;
}
static void sortedcache_clear(git_sortedcache *sc)
{
git_strmap_clear(sc->map);
if (sc->free_item) {
size_t i;
void *item;
git_vector_foreach(&sc->items, i, item) {
sc->free_item(sc->free_item_payload, item);
}
}
git_vector_clear(&sc->items);
git_pool_clear(&sc->pool);
}
static void sortedcache_free(git_sortedcache *sc)
{
/* acquire write lock to make sure everyone else is done */
if (git_sortedcache_wlock(sc) < 0)
return;
sortedcache_clear(sc);
git_vector_free(&sc->items);
git_strmap_free(sc->map);
git_sortedcache_wunlock(sc);
git_rwlock_free(&sc->lock);
git__free(sc);
}
void git_sortedcache_free(git_sortedcache *sc)
{
if (!sc)
return;
GIT_REFCOUNT_DEC(sc, sortedcache_free);
}
static int sortedcache_copy_item(void *payload, void *tgt_item, void *src_item)
{
git_sortedcache *sc = payload;
/* path will already have been copied by upsert */
memcpy(tgt_item, src_item, sc->item_path_offset);
return 0;
}
/* copy a sorted cache */
int git_sortedcache_copy(
git_sortedcache **out,
git_sortedcache *src,
bool lock,
int (*copy_item)(void *payload, void *tgt_item, void *src_item),
void *payload)
{
int error = 0;
git_sortedcache *tgt;
size_t i;
void *src_item, *tgt_item;
/* just use memcpy if no special copy fn is passed in */
if (!copy_item) {
copy_item = sortedcache_copy_item;
payload = src;
}
if ((error = git_sortedcache_new(
&tgt, src->item_path_offset,
src->free_item, src->free_item_payload,
src->items._cmp, src->path)) < 0)
return error;
if (lock && git_sortedcache_rlock(src) < 0) {
git_sortedcache_free(tgt);
return -1;
}
git_vector_foreach(&src->items, i, src_item) {
char *path = ((char *)src_item) + src->item_path_offset;
if ((error = git_sortedcache_upsert(&tgt_item, tgt, path)) < 0 ||
(error = copy_item(payload, tgt_item, src_item)) < 0)
break;
}
if (lock)
git_sortedcache_runlock(src);
if (error)
git_sortedcache_free(tgt);
*out = !error ? tgt : NULL;
return error;
}
/* lock sortedcache while making modifications */
int git_sortedcache_wlock(git_sortedcache *sc)
{
GIT_UNUSED(sc); /* prevent warning when compiled w/o threads */
if (git_rwlock_wrlock(&sc->lock) < 0) {
git_error_set(GIT_ERROR_OS, "unable to acquire write lock on cache");
return -1;
}
return 0;
}
/* unlock sorted cache when done with modifications */
void git_sortedcache_wunlock(git_sortedcache *sc)
{
git_vector_sort(&sc->items);
git_rwlock_wrunlock(&sc->lock);
}
/* lock sortedcache for read */
int git_sortedcache_rlock(git_sortedcache *sc)
{
GIT_UNUSED(sc); /* prevent warning when compiled w/o threads */
if (git_rwlock_rdlock(&sc->lock) < 0) {
git_error_set(GIT_ERROR_OS, "unable to acquire read lock on cache");
return -1;
}
return 0;
}
/* unlock sorted cache when done reading */
void git_sortedcache_runlock(git_sortedcache *sc)
{
GIT_UNUSED(sc); /* prevent warning when compiled w/o threads */
git_rwlock_rdunlock(&sc->lock);
}
/* if the file has changed, lock cache and load file contents into buf;
* returns <0 on error, >0 if file has not changed
*/
int git_sortedcache_lockandload(git_sortedcache *sc, git_buf *buf)
{
int error, fd;
struct stat st;
if ((error = git_sortedcache_wlock(sc)) < 0)
return error;
if ((error = git_futils_filestamp_check(&sc->stamp, sc->path)) <= 0)
goto unlock;
if ((fd = git_futils_open_ro(sc->path)) < 0) {
error = fd;
goto unlock;
}
if (p_fstat(fd, &st) < 0) {
git_error_set(GIT_ERROR_OS, "failed to stat file");
error = -1;
(void)p_close(fd);
goto unlock;
}
if (!git__is_sizet(st.st_size)) {
git_error_set(GIT_ERROR_INVALID, "unable to load file larger than size_t");
error = -1;
(void)p_close(fd);
goto unlock;
}
if (buf)
error = git_futils_readbuffer_fd(buf, fd, (size_t)st.st_size);
(void)p_close(fd);
if (error < 0)
goto unlock;
return 1; /* return 1 -> file needs reload and was successfully loaded */
unlock:
git_sortedcache_wunlock(sc);
return error;
}
void git_sortedcache_updated(git_sortedcache *sc)
{
/* update filestamp to latest value */
git_futils_filestamp_check(&sc->stamp, sc->path);
}
/* release all items in sorted cache */
int git_sortedcache_clear(git_sortedcache *sc, bool wlock)
{
if (wlock && git_sortedcache_wlock(sc) < 0)
return -1;
sortedcache_clear(sc);
if (wlock)
git_sortedcache_wunlock(sc);
return 0;
}
/* find and/or insert item, returning pointer to item data */
int git_sortedcache_upsert(void **out, git_sortedcache *sc, const char *key)
{
size_t keylen, itemlen;
int error = 0;
char *item_key;
void *item;
if ((item = git_strmap_get(sc->map, key)) != NULL)
goto done;
keylen = strlen(key);
itemlen = sc->item_path_offset + keylen + 1;
itemlen = (itemlen + 7) & ~7;
if ((item = git_pool_mallocz(&sc->pool, itemlen)) == NULL) {
/* don't use GIT_ERROR_CHECK_ALLOC b/c of lock */
error = -1;
goto done;
}
/* one strange thing is that even if the vector or hash table insert
* fail, there is no way to free the pool item so we just abandon it
*/
item_key = ((char *)item) + sc->item_path_offset;
memcpy(item_key, key, keylen);
if ((error = git_strmap_set(sc->map, item_key, item)) < 0)
goto done;
if ((error = git_vector_insert(&sc->items, item)) < 0)
git_strmap_delete(sc->map, item_key);
done:
if (out)
*out = !error ? item : NULL;
return error;
}
/* lookup item by key */
void *git_sortedcache_lookup(const git_sortedcache *sc, const char *key)
{
return git_strmap_get(sc->map, key);
}
/* find out how many items are in the cache */
size_t git_sortedcache_entrycount(const git_sortedcache *sc)
{
return git_vector_length(&sc->items);
}
/* lookup item by index */
void *git_sortedcache_entry(git_sortedcache *sc, size_t pos)
{
/* make sure the items are sorted so this gets the correct item */
if (!git_vector_is_sorted(&sc->items))
git_vector_sort(&sc->items);
return git_vector_get(&sc->items, pos);
}
/* helper struct so bsearch callback can know offset + key value for cmp */
struct sortedcache_magic_key {
size_t offset;
const char *key;
};
static int sortedcache_magic_cmp(const void *key, const void *value)
{
const struct sortedcache_magic_key *magic = key;
const char *value_key = ((const char *)value) + magic->offset;
return strcmp(magic->key, value_key);
}
/* lookup index of item by key */
int git_sortedcache_lookup_index(
size_t *out, git_sortedcache *sc, const char *key)
{
struct sortedcache_magic_key magic;
magic.offset = sc->item_path_offset;
magic.key = key;
return git_vector_bsearch2(out, &sc->items, sortedcache_magic_cmp, &magic);
}
/* remove entry from cache */
int git_sortedcache_remove(git_sortedcache *sc, size_t pos)
{
char *item;
/*
* Because of pool allocation, this can't actually remove the item,
* but we can remove it from the items vector and the hash table.
*/
if ((item = git_vector_get(&sc->items, pos)) == NULL) {
git_error_set(GIT_ERROR_INVALID, "removing item out of range");
return GIT_ENOTFOUND;
}
(void)git_vector_remove(&sc->items, pos);
git_strmap_delete(sc->map, item + sc->item_path_offset);
if (sc->free_item)
sc->free_item(sc->free_item_payload, item);
return 0;
}
|
0 |
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2
|
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2/src/config.h
|
/*
* Copyright (C) the libgit2 contributors. All rights reserved.
*
* This file is part of libgit2, distributed under the GNU GPL v2 with
* a Linking Exception. For full terms see the included COPYING file.
*/
#ifndef INCLUDE_config_h__
#define INCLUDE_config_h__
#include "common.h"
#include "git2.h"
#include "git2/config.h"
#include "vector.h"
#include "repository.h"
#define GIT_CONFIG_FILENAME_PROGRAMDATA "config"
#define GIT_CONFIG_FILENAME_SYSTEM "gitconfig"
#define GIT_CONFIG_FILENAME_GLOBAL ".gitconfig"
#define GIT_CONFIG_FILENAME_XDG "config"
#define GIT_CONFIG_FILENAME_INREPO "config"
#define GIT_CONFIG_FILE_MODE 0666
struct git_config {
git_refcount rc;
git_vector backends;
};
extern int git_config__global_location(git_buf *buf);
extern int git_config_rename_section(
git_repository *repo,
const char *old_section_name, /* eg "branch.dummy" */
const char *new_section_name); /* NULL to drop the old section */
extern int git_config__normalize_name(const char *in, char **out);
/* internal only: does not normalize key and sets out to NULL if not found */
extern int git_config__lookup_entry(
git_config_entry **out,
const git_config *cfg,
const char *key,
bool no_errors);
/* internal only: update and/or delete entry string with constraints */
extern int git_config__update_entry(
git_config *cfg,
const char *key,
const char *value,
bool overwrite_existing,
bool only_if_existing);
/*
* Lookup functions that cannot fail. These functions look up a config
* value and return a fallback value if the value is missing or if any
* failures occur while trying to access the value.
*/
extern char *git_config__get_string_force(
const git_config *cfg, const char *key, const char *fallback_value);
extern int git_config__get_bool_force(
const git_config *cfg, const char *key, int fallback_value);
extern int git_config__get_int_force(
const git_config *cfg, const char *key, int fallback_value);
/* API for repository configmap-style lookups from config - not cached, but
* uses configmap value maps and fallbacks
*/
extern int git_config__configmap_lookup(
int *out, git_config *config, git_configmap_item item);
/**
* The opposite of git_config_lookup_map_value, we take an enum value
* and map it to the string or bool value on the config.
*/
int git_config_lookup_map_enum(git_configmap_t *type_out,
const char **str_out, const git_configmap *maps,
size_t map_n, int enum_val);
/**
* Unlock the backend with the highest priority
*
* Unlocking will allow other writers to updat the configuration
* file. Optionally, any changes performed since the lock will be
* applied to the configuration.
*
* @param cfg the configuration
* @param commit boolean which indicates whether to commit any changes
* done since locking
* @return 0 or an error code
*/
GIT_EXTERN(int) git_config_unlock(git_config *cfg, int commit);
#endif
|
0 |
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2
|
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2/src/describe.c
|
/*
* Copyright (C) the libgit2 contributors. All rights reserved.
*
* This file is part of libgit2, distributed under the GNU GPL v2 with
* a Linking Exception. For full terms see the included COPYING file.
*/
#include "common.h"
#include "git2/describe.h"
#include "git2/strarray.h"
#include "git2/diff.h"
#include "git2/status.h"
#include "commit.h"
#include "commit_list.h"
#include "oidmap.h"
#include "refs.h"
#include "repository.h"
#include "revwalk.h"
#include "tag.h"
#include "vector.h"
#include "wildmatch.h"
/* Ported from https://github.com/git/git/blob/89dde7882f71f846ccd0359756d27bebc31108de/builtin/describe.c */
struct commit_name {
git_tag *tag;
unsigned prio:2; /* annotated tag = 2, tag = 1, head = 0 */
unsigned name_checked:1;
git_oid sha1;
char *path;
/* Khash workaround. They original key has to still be reachable */
git_oid peeled;
};
static void *oidmap_value_bykey(git_oidmap *map, const git_oid *key)
{
return git_oidmap_get(map, key);
}
static struct commit_name *find_commit_name(
git_oidmap *names,
const git_oid *peeled)
{
return (struct commit_name *)(oidmap_value_bykey(names, peeled));
}
static int replace_name(
git_tag **tag,
git_repository *repo,
struct commit_name *e,
unsigned int prio,
const git_oid *sha1)
{
git_time_t e_time = 0, t_time = 0;
if (!e || e->prio < prio)
return 1;
if (e->prio == 2 && prio == 2) {
/* Multiple annotated tags point to the same commit.
* Select one to keep based upon their tagger date.
*/
git_tag *t = NULL;
if (!e->tag) {
if (git_tag_lookup(&t, repo, &e->sha1) < 0)
return 1;
e->tag = t;
}
if (git_tag_lookup(&t, repo, sha1) < 0)
return 0;
*tag = t;
if (e->tag->tagger)
e_time = e->tag->tagger->when.time;
if (t->tagger)
t_time = t->tagger->when.time;
if (e_time < t_time)
return 1;
}
return 0;
}
static int add_to_known_names(
git_repository *repo,
git_oidmap *names,
const char *path,
const git_oid *peeled,
unsigned int prio,
const git_oid *sha1)
{
struct commit_name *e = find_commit_name(names, peeled);
bool found = (e != NULL);
git_tag *tag = NULL;
if (replace_name(&tag, repo, e, prio, sha1)) {
if (!found) {
e = git__malloc(sizeof(struct commit_name));
GIT_ERROR_CHECK_ALLOC(e);
e->path = NULL;
e->tag = NULL;
}
if (e->tag)
git_tag_free(e->tag);
e->tag = tag;
e->prio = prio;
e->name_checked = 0;
git_oid_cpy(&e->sha1, sha1);
git__free(e->path);
e->path = git__strdup(path);
git_oid_cpy(&e->peeled, peeled);
if (!found && git_oidmap_set(names, &e->peeled, e) < 0)
return -1;
}
else
git_tag_free(tag);
return 0;
}
static int retrieve_peeled_tag_or_object_oid(
git_oid *peeled_out,
git_oid *ref_target_out,
git_repository *repo,
const char *refname)
{
git_reference *ref;
git_object *peeled = NULL;
int error;
if ((error = git_reference_lookup_resolved(&ref, repo, refname, -1)) < 0)
return error;
if ((error = git_reference_peel(&peeled, ref, GIT_OBJECT_ANY)) < 0)
goto cleanup;
git_oid_cpy(ref_target_out, git_reference_target(ref));
git_oid_cpy(peeled_out, git_object_id(peeled));
if (git_oid_cmp(ref_target_out, peeled_out) != 0)
error = 1; /* The reference was pointing to a annotated tag */
else
error = 0; /* Any other object */
cleanup:
git_reference_free(ref);
git_object_free(peeled);
return error;
}
struct git_describe_result {
int dirty;
int exact_match;
int fallback_to_id;
git_oid commit_id;
git_repository *repo;
struct commit_name *name;
struct possible_tag *tag;
};
struct get_name_data
{
git_describe_options *opts;
git_repository *repo;
git_oidmap *names;
git_describe_result *result;
};
static int commit_name_dup(struct commit_name **out, struct commit_name *in)
{
struct commit_name *name;
name = git__malloc(sizeof(struct commit_name));
GIT_ERROR_CHECK_ALLOC(name);
memcpy(name, in, sizeof(struct commit_name));
name->tag = NULL;
name->path = NULL;
if (in->tag && git_tag_dup(&name->tag, in->tag) < 0)
return -1;
name->path = git__strdup(in->path);
GIT_ERROR_CHECK_ALLOC(name->path);
*out = name;
return 0;
}
static int get_name(const char *refname, void *payload)
{
struct get_name_data *data;
bool is_tag, is_annotated, all;
git_oid peeled, sha1;
unsigned int prio;
int error = 0;
data = (struct get_name_data *)payload;
is_tag = !git__prefixcmp(refname, GIT_REFS_TAGS_DIR);
all = data->opts->describe_strategy == GIT_DESCRIBE_ALL;
/* Reject anything outside refs/tags/ unless --all */
if (!all && !is_tag)
return 0;
/* Accept only tags that match the pattern, if given */
if (data->opts->pattern && (!is_tag || wildmatch(data->opts->pattern,
refname + strlen(GIT_REFS_TAGS_DIR), 0)))
return 0;
/* Is it annotated? */
if ((error = retrieve_peeled_tag_or_object_oid(
&peeled, &sha1, data->repo, refname)) < 0)
return error;
is_annotated = error;
/*
* By default, we only use annotated tags, but with --tags
* we fall back to lightweight ones (even without --tags,
* we still remember lightweight ones, only to give hints
* in an error message). --all allows any refs to be used.
*/
if (is_annotated)
prio = 2;
else if (is_tag)
prio = 1;
else
prio = 0;
add_to_known_names(data->repo, data->names,
all ? refname + strlen(GIT_REFS_DIR) : refname + strlen(GIT_REFS_TAGS_DIR),
&peeled, prio, &sha1);
return 0;
}
struct possible_tag {
struct commit_name *name;
int depth;
int found_order;
unsigned flag_within;
};
static int possible_tag_dup(struct possible_tag **out, struct possible_tag *in)
{
struct possible_tag *tag;
int error;
tag = git__malloc(sizeof(struct possible_tag));
GIT_ERROR_CHECK_ALLOC(tag);
memcpy(tag, in, sizeof(struct possible_tag));
tag->name = NULL;
if ((error = commit_name_dup(&tag->name, in->name)) < 0) {
git__free(tag);
*out = NULL;
return error;
}
*out = tag;
return 0;
}
static int compare_pt(const void *a_, const void *b_)
{
struct possible_tag *a = (struct possible_tag *)a_;
struct possible_tag *b = (struct possible_tag *)b_;
if (a->depth != b->depth)
return a->depth - b->depth;
if (a->found_order != b->found_order)
return a->found_order - b->found_order;
return 0;
}
#define SEEN (1u << 0)
static unsigned long finish_depth_computation(
git_pqueue *list,
git_revwalk *walk,
struct possible_tag *best)
{
unsigned long seen_commits = 0;
int error, i;
while (git_pqueue_size(list) > 0) {
git_commit_list_node *c = git_pqueue_pop(list);
seen_commits++;
if (c->flags & best->flag_within) {
size_t index = 0;
while (git_pqueue_size(list) > index) {
git_commit_list_node *i = git_pqueue_get(list, index);
if (!(i->flags & best->flag_within))
break;
index++;
}
if (index > git_pqueue_size(list))
break;
} else
best->depth++;
for (i = 0; i < c->out_degree; i++) {
git_commit_list_node *p = c->parents[i];
if ((error = git_commit_list_parse(walk, p)) < 0)
return error;
if (!(p->flags & SEEN))
if ((error = git_pqueue_insert(list, p)) < 0)
return error;
p->flags |= c->flags;
}
}
return seen_commits;
}
static int display_name(git_buf *buf, git_repository *repo, struct commit_name *n)
{
if (n->prio == 2 && !n->tag) {
if (git_tag_lookup(&n->tag, repo, &n->sha1) < 0) {
git_error_set(GIT_ERROR_TAG, "annotated tag '%s' not available", n->path);
return -1;
}
}
if (n->tag && !n->name_checked) {
if (!git_tag_name(n->tag)) {
git_error_set(GIT_ERROR_TAG, "annotated tag '%s' has no embedded name", n->path);
return -1;
}
/* TODO: Cope with warnings
if (strcmp(n->tag->tag, all ? n->path + 5 : n->path))
warning(_("tag '%s' is really '%s' here"), n->tag->tag, n->path);
*/
n->name_checked = 1;
}
if (n->tag)
git_buf_printf(buf, "%s", git_tag_name(n->tag));
else
git_buf_printf(buf, "%s", n->path);
return 0;
}
static int find_unique_abbrev_size(
int *out,
git_repository *repo,
const git_oid *oid_in,
unsigned int abbreviated_size)
{
size_t size = abbreviated_size;
git_odb *odb;
git_oid dummy;
int error;
if ((error = git_repository_odb__weakptr(&odb, repo)) < 0)
return error;
while (size < GIT_OID_HEXSZ) {
if ((error = git_odb_exists_prefix(&dummy, odb, oid_in, size)) == 0) {
*out = (int) size;
return 0;
}
/* If the error wasn't that it's not unique, then it's a proper error */
if (error != GIT_EAMBIGUOUS)
return error;
/* Try again with a larger size */
size++;
}
/* If we didn't find any shorter prefix, we have to do the whole thing */
*out = GIT_OID_HEXSZ;
return 0;
}
static int show_suffix(
git_buf *buf,
int depth,
git_repository *repo,
const git_oid *id,
unsigned int abbrev_size)
{
int error, size = 0;
char hex_oid[GIT_OID_HEXSZ];
if ((error = find_unique_abbrev_size(&size, repo, id, abbrev_size)) < 0)
return error;
git_oid_fmt(hex_oid, id);
git_buf_printf(buf, "-%d-g", depth);
git_buf_put(buf, hex_oid, size);
return git_buf_oom(buf) ? -1 : 0;
}
#define MAX_CANDIDATES_TAGS FLAG_BITS - 1
static int describe_not_found(const git_oid *oid, const char *message_format) {
char oid_str[GIT_OID_HEXSZ + 1];
git_oid_tostr(oid_str, sizeof(oid_str), oid);
git_error_set(GIT_ERROR_DESCRIBE, message_format, oid_str);
return GIT_ENOTFOUND;
}
static int describe(
struct get_name_data *data,
git_commit *commit)
{
struct commit_name *n;
struct possible_tag *best;
bool all, tags;
git_revwalk *walk = NULL;
git_pqueue list;
git_commit_list_node *cmit, *gave_up_on = NULL;
git_vector all_matches = GIT_VECTOR_INIT;
unsigned int match_cnt = 0, annotated_cnt = 0, cur_match;
unsigned long seen_commits = 0; /* TODO: Check long */
unsigned int unannotated_cnt = 0;
int error;
if (git_vector_init(&all_matches, MAX_CANDIDATES_TAGS, compare_pt) < 0)
return -1;
if ((error = git_pqueue_init(&list, 0, 2, git_commit_list_time_cmp)) < 0)
goto cleanup;
all = data->opts->describe_strategy == GIT_DESCRIBE_ALL;
tags = data->opts->describe_strategy == GIT_DESCRIBE_TAGS;
git_oid_cpy(&data->result->commit_id, git_commit_id(commit));
n = find_commit_name(data->names, git_commit_id(commit));
if (n && (tags || all || n->prio == 2)) {
/*
* Exact match to an existing ref.
*/
data->result->exact_match = 1;
if ((error = commit_name_dup(&data->result->name, n)) < 0)
goto cleanup;
goto cleanup;
}
if (!data->opts->max_candidates_tags) {
error = describe_not_found(
git_commit_id(commit),
"cannot describe - no tag exactly matches '%s'");
goto cleanup;
}
if ((error = git_revwalk_new(&walk, git_commit_owner(commit))) < 0)
goto cleanup;
if ((cmit = git_revwalk__commit_lookup(walk, git_commit_id(commit))) == NULL)
goto cleanup;
if ((error = git_commit_list_parse(walk, cmit)) < 0)
goto cleanup;
cmit->flags = SEEN;
if ((error = git_pqueue_insert(&list, cmit)) < 0)
goto cleanup;
while (git_pqueue_size(&list) > 0)
{
int i;
git_commit_list_node *c = (git_commit_list_node *)git_pqueue_pop(&list);
seen_commits++;
n = find_commit_name(data->names, &c->oid);
if (n) {
if (!tags && !all && n->prio < 2) {
unannotated_cnt++;
} else if (match_cnt < data->opts->max_candidates_tags) {
struct possible_tag *t = git__malloc(sizeof(struct commit_name));
GIT_ERROR_CHECK_ALLOC(t);
if ((error = git_vector_insert(&all_matches, t)) < 0)
goto cleanup;
match_cnt++;
t->name = n;
t->depth = seen_commits - 1;
t->flag_within = 1u << match_cnt;
t->found_order = match_cnt;
c->flags |= t->flag_within;
if (n->prio == 2)
annotated_cnt++;
}
else {
gave_up_on = c;
break;
}
}
for (cur_match = 0; cur_match < match_cnt; cur_match++) {
struct possible_tag *t = git_vector_get(&all_matches, cur_match);
if (!(c->flags & t->flag_within))
t->depth++;
}
if (annotated_cnt && (git_pqueue_size(&list) == 0)) {
/*
if (debug) {
char oid_str[GIT_OID_HEXSZ + 1];
git_oid_tostr(oid_str, sizeof(oid_str), &c->oid);
fprintf(stderr, "finished search at %s\n", oid_str);
}
*/
break;
}
for (i = 0; i < c->out_degree; i++) {
git_commit_list_node *p = c->parents[i];
if ((error = git_commit_list_parse(walk, p)) < 0)
goto cleanup;
if (!(p->flags & SEEN))
if ((error = git_pqueue_insert(&list, p)) < 0)
goto cleanup;
p->flags |= c->flags;
if (data->opts->only_follow_first_parent)
break;
}
}
if (!match_cnt) {
if (data->opts->show_commit_oid_as_fallback) {
data->result->fallback_to_id = 1;
git_oid_cpy(&data->result->commit_id, &cmit->oid);
goto cleanup;
}
if (unannotated_cnt) {
error = describe_not_found(git_commit_id(commit),
"cannot describe - "
"no annotated tags can describe '%s'; "
"however, there were unannotated tags.");
goto cleanup;
}
else {
error = describe_not_found(git_commit_id(commit),
"cannot describe - "
"no tags can describe '%s'.");
goto cleanup;
}
}
git_vector_sort(&all_matches);
best = (struct possible_tag *)git_vector_get(&all_matches, 0);
if (gave_up_on) {
if ((error = git_pqueue_insert(&list, gave_up_on)) < 0)
goto cleanup;
seen_commits--;
}
if ((error = finish_depth_computation(
&list, walk, best)) < 0)
goto cleanup;
seen_commits += error;
if ((error = possible_tag_dup(&data->result->tag, best)) < 0)
goto cleanup;
/*
{
static const char *prio_names[] = {
"head", "lightweight", "annotated",
};
char oid_str[GIT_OID_HEXSZ + 1];
if (debug) {
for (cur_match = 0; cur_match < match_cnt; cur_match++) {
struct possible_tag *t = (struct possible_tag *)git_vector_get(&all_matches, cur_match);
fprintf(stderr, " %-11s %8d %s\n",
prio_names[t->name->prio],
t->depth, t->name->path);
}
fprintf(stderr, "traversed %lu commits\n", seen_commits);
if (gave_up_on) {
git_oid_tostr(oid_str, sizeof(oid_str), &gave_up_on->oid);
fprintf(stderr,
"more than %i tags found; listed %i most recent\n"
"gave up search at %s\n",
data->opts->max_candidates_tags, data->opts->max_candidates_tags,
oid_str);
}
}
}
*/
git_oid_cpy(&data->result->commit_id, &cmit->oid);
cleanup:
{
size_t i;
struct possible_tag *match;
git_vector_foreach(&all_matches, i, match) {
git__free(match);
}
}
git_vector_free(&all_matches);
git_pqueue_free(&list);
git_revwalk_free(walk);
return error;
}
static int normalize_options(
git_describe_options *dst,
const git_describe_options *src)
{
git_describe_options default_options = GIT_DESCRIBE_OPTIONS_INIT;
if (!src) src = &default_options;
*dst = *src;
if (dst->max_candidates_tags > GIT_DESCRIBE_DEFAULT_MAX_CANDIDATES_TAGS)
dst->max_candidates_tags = GIT_DESCRIBE_DEFAULT_MAX_CANDIDATES_TAGS;
return 0;
}
int git_describe_commit(
git_describe_result **result,
git_object *committish,
git_describe_options *opts)
{
struct get_name_data data;
struct commit_name *name;
git_commit *commit;
int error = -1;
git_describe_options normalized;
GIT_ASSERT_ARG(result);
GIT_ASSERT_ARG(committish);
data.result = git__calloc(1, sizeof(git_describe_result));
GIT_ERROR_CHECK_ALLOC(data.result);
data.result->repo = git_object_owner(committish);
data.repo = git_object_owner(committish);
if ((error = normalize_options(&normalized, opts)) < 0)
return error;
GIT_ERROR_CHECK_VERSION(
&normalized,
GIT_DESCRIBE_OPTIONS_VERSION,
"git_describe_options");
data.opts = &normalized;
if ((error = git_oidmap_new(&data.names)) < 0)
return error;
/** TODO: contains to be implemented */
if ((error = git_object_peel((git_object **)(&commit), committish, GIT_OBJECT_COMMIT)) < 0)
goto cleanup;
if ((error = git_reference_foreach_name(
git_object_owner(committish),
get_name, &data)) < 0)
goto cleanup;
if (git_oidmap_size(data.names) == 0 && !normalized.show_commit_oid_as_fallback) {
git_error_set(GIT_ERROR_DESCRIBE, "cannot describe - "
"no reference found, cannot describe anything.");
error = -1;
goto cleanup;
}
if ((error = describe(&data, commit)) < 0)
goto cleanup;
cleanup:
git_commit_free(commit);
git_oidmap_foreach_value(data.names, name, {
git_tag_free(name->tag);
git__free(name->path);
git__free(name);
});
git_oidmap_free(data.names);
if (error < 0)
git_describe_result_free(data.result);
else
*result = data.result;
return error;
}
int git_describe_workdir(
git_describe_result **out,
git_repository *repo,
git_describe_options *opts)
{
int error;
git_oid current_id;
git_status_list *status = NULL;
git_status_options status_opts = GIT_STATUS_OPTIONS_INIT;
git_describe_result *result = NULL;
git_object *commit;
if ((error = git_reference_name_to_id(¤t_id, repo, GIT_HEAD_FILE)) < 0)
return error;
if ((error = git_object_lookup(&commit, repo, ¤t_id, GIT_OBJECT_COMMIT)) < 0)
return error;
/* The first step is to perform a describe of HEAD, so we can leverage this */
if ((error = git_describe_commit(&result, commit, opts)) < 0)
goto out;
if ((error = git_status_list_new(&status, repo, &status_opts)) < 0)
goto out;
if (git_status_list_entrycount(status) > 0)
result->dirty = 1;
out:
git_object_free(commit);
git_status_list_free(status);
if (error < 0)
git_describe_result_free(result);
else
*out = result;
return error;
}
static int normalize_format_options(
git_describe_format_options *dst,
const git_describe_format_options *src)
{
if (!src) {
git_describe_format_options_init(dst, GIT_DESCRIBE_FORMAT_OPTIONS_VERSION);
return 0;
}
memcpy(dst, src, sizeof(git_describe_format_options));
return 0;
}
int git_describe_format(git_buf *out, const git_describe_result *result, const git_describe_format_options *given)
{
int error;
git_repository *repo;
struct commit_name *name;
git_describe_format_options opts;
GIT_ASSERT_ARG(out);
GIT_ASSERT_ARG(result);
GIT_ERROR_CHECK_VERSION(given, GIT_DESCRIBE_FORMAT_OPTIONS_VERSION, "git_describe_format_options");
normalize_format_options(&opts, given);
if ((error = git_buf_sanitize(out)) < 0)
return error;
if (opts.always_use_long_format && opts.abbreviated_size == 0) {
git_error_set(GIT_ERROR_DESCRIBE, "cannot describe - "
"'always_use_long_format' is incompatible with a zero"
"'abbreviated_size'");
return -1;
}
repo = result->repo;
/* If we did find an exact match, then it's the easier method */
if (result->exact_match) {
name = result->name;
if ((error = display_name(out, repo, name)) < 0)
return error;
if (opts.always_use_long_format) {
const git_oid *id = name->tag ? git_tag_target_id(name->tag) : &result->commit_id;
if ((error = show_suffix(out, 0, repo, id, opts.abbreviated_size)) < 0)
return error;
}
if (result->dirty && opts.dirty_suffix)
git_buf_puts(out, opts.dirty_suffix);
return git_buf_oom(out) ? -1 : 0;
}
/* If we didn't find *any* tags, we fall back to the commit's id */
if (result->fallback_to_id) {
char hex_oid[GIT_OID_HEXSZ + 1] = {0};
int size = 0;
if ((error = find_unique_abbrev_size(
&size, repo, &result->commit_id, opts.abbreviated_size)) < 0)
return -1;
git_oid_fmt(hex_oid, &result->commit_id);
git_buf_put(out, hex_oid, size);
if (result->dirty && opts.dirty_suffix)
git_buf_puts(out, opts.dirty_suffix);
return git_buf_oom(out) ? -1 : 0;
}
/* Lastly, if we found a matching tag, we show that */
name = result->tag->name;
if ((error = display_name(out, repo, name)) < 0)
return error;
if (opts.abbreviated_size) {
if ((error = show_suffix(out, result->tag->depth, repo,
&result->commit_id, opts.abbreviated_size)) < 0)
return error;
}
if (result->dirty && opts.dirty_suffix) {
git_buf_puts(out, opts.dirty_suffix);
}
return git_buf_oom(out) ? -1 : 0;
}
void git_describe_result_free(git_describe_result *result)
{
if (result == NULL)
return;
if (result->name) {
git_tag_free(result->name->tag);
git__free(result->name->path);
git__free(result->name);
}
if (result->tag) {
git_tag_free(result->tag->name->tag);
git__free(result->tag->name->path);
git__free(result->tag->name);
git__free(result->tag);
}
git__free(result);
}
int git_describe_options_init(git_describe_options *opts, unsigned int version)
{
GIT_INIT_STRUCTURE_FROM_TEMPLATE(
opts, version, git_describe_options, GIT_DESCRIBE_OPTIONS_INIT);
return 0;
}
#ifndef GIT_DEPRECATE_HARD
int git_describe_init_options(git_describe_options *opts, unsigned int version)
{
return git_describe_options_init(opts, version);
}
#endif
int git_describe_format_options_init(git_describe_format_options *opts, unsigned int version)
{
GIT_INIT_STRUCTURE_FROM_TEMPLATE(
opts, version, git_describe_format_options, GIT_DESCRIBE_FORMAT_OPTIONS_INIT);
return 0;
}
#ifndef GIT_DEPRECATE_HARD
int git_describe_init_format_options(git_describe_format_options *opts, unsigned int version)
{
return git_describe_format_options_init(opts, version);
}
#endif
|
0 |
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2
|
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2/src/object.c
|
/*
* Copyright (C) the libgit2 contributors. All rights reserved.
*
* This file is part of libgit2, distributed under the GNU GPL v2 with
* a Linking Exception. For full terms see the included COPYING file.
*/
#include "object.h"
#include "git2/object.h"
#include "repository.h"
#include "commit.h"
#include "hash.h"
#include "tree.h"
#include "blob.h"
#include "oid.h"
#include "tag.h"
bool git_object__strict_input_validation = true;
extern int git_odb_hash(git_oid *out, const void *data, size_t len, git_object_t type);
size_t git_object__size(git_object_t type);
typedef struct {
const char *str; /* type name string */
size_t size; /* size in bytes of the object structure */
int (*parse)(void *self, git_odb_object *obj);
int (*parse_raw)(void *self, const char *data, size_t size);
void (*free)(void *self);
} git_object_def;
static git_object_def git_objects_table[] = {
/* 0 = GIT_OBJECT__EXT1 */
{ "", 0, NULL, NULL, NULL },
/* 1 = GIT_OBJECT_COMMIT */
{ "commit", sizeof(git_commit), git_commit__parse, git_commit__parse_raw, git_commit__free },
/* 2 = GIT_OBJECT_TREE */
{ "tree", sizeof(git_tree), git_tree__parse, git_tree__parse_raw, git_tree__free },
/* 3 = GIT_OBJECT_BLOB */
{ "blob", sizeof(git_blob), git_blob__parse, git_blob__parse_raw, git_blob__free },
/* 4 = GIT_OBJECT_TAG */
{ "tag", sizeof(git_tag), git_tag__parse, git_tag__parse_raw, git_tag__free },
/* 5 = GIT_OBJECT__EXT2 */
{ "", 0, NULL, NULL, NULL },
/* 6 = GIT_OBJECT_OFS_DELTA */
{ "OFS_DELTA", 0, NULL, NULL, NULL },
/* 7 = GIT_OBJECT_REF_DELTA */
{ "REF_DELTA", 0, NULL, NULL, NULL },
};
int git_object__from_raw(
git_object **object_out,
const char *data,
size_t size,
git_object_t type)
{
git_object_def *def;
git_object *object;
size_t object_size;
int error;
GIT_ASSERT_ARG(object_out);
*object_out = NULL;
/* Validate type match */
if (type != GIT_OBJECT_BLOB && type != GIT_OBJECT_TREE && type != GIT_OBJECT_COMMIT && type != GIT_OBJECT_TAG) {
git_error_set(GIT_ERROR_INVALID, "the requested type is invalid");
return GIT_ENOTFOUND;
}
if ((object_size = git_object__size(type)) == 0) {
git_error_set(GIT_ERROR_INVALID, "the requested type is invalid");
return GIT_ENOTFOUND;
}
/* Allocate and initialize base object */
object = git__calloc(1, object_size);
GIT_ERROR_CHECK_ALLOC(object);
object->cached.flags = GIT_CACHE_STORE_PARSED;
object->cached.type = type;
if ((error = git_odb_hash(&object->cached.oid, data, size, type)) < 0)
return error;
/* Parse raw object data */
def = &git_objects_table[type];
GIT_ASSERT(def->free && def->parse_raw);
if ((error = def->parse_raw(object, data, size)) < 0) {
def->free(object);
return error;
}
git_cached_obj_incref(object);
*object_out = object;
return 0;
}
int git_object__from_odb_object(
git_object **object_out,
git_repository *repo,
git_odb_object *odb_obj,
git_object_t type)
{
int error;
size_t object_size;
git_object_def *def;
git_object *object = NULL;
GIT_ASSERT_ARG(object_out);
*object_out = NULL;
/* Validate type match */
if (type != GIT_OBJECT_ANY && type != odb_obj->cached.type) {
git_error_set(GIT_ERROR_INVALID,
"the requested type does not match the type in the ODB");
return GIT_ENOTFOUND;
}
if ((object_size = git_object__size(odb_obj->cached.type)) == 0) {
git_error_set(GIT_ERROR_INVALID, "the requested type is invalid");
return GIT_ENOTFOUND;
}
/* Allocate and initialize base object */
object = git__calloc(1, object_size);
GIT_ERROR_CHECK_ALLOC(object);
git_oid_cpy(&object->cached.oid, &odb_obj->cached.oid);
object->cached.type = odb_obj->cached.type;
object->cached.size = odb_obj->cached.size;
object->repo = repo;
/* Parse raw object data */
def = &git_objects_table[odb_obj->cached.type];
GIT_ASSERT(def->free && def->parse);
if ((error = def->parse(object, odb_obj)) < 0)
def->free(object);
else
*object_out = git_cache_store_parsed(&repo->objects, object);
return error;
}
void git_object__free(void *obj)
{
git_object_t type = ((git_object *)obj)->cached.type;
if (type < 0 || ((size_t)type) >= ARRAY_SIZE(git_objects_table) ||
!git_objects_table[type].free)
git__free(obj);
else
git_objects_table[type].free(obj);
}
int git_object_lookup_prefix(
git_object **object_out,
git_repository *repo,
const git_oid *id,
size_t len,
git_object_t type)
{
git_object *object = NULL;
git_odb *odb = NULL;
git_odb_object *odb_obj = NULL;
int error = 0;
GIT_ASSERT_ARG(repo);
GIT_ASSERT_ARG(object_out);
GIT_ASSERT_ARG(id);
if (len < GIT_OID_MINPREFIXLEN) {
git_error_set(GIT_ERROR_OBJECT, "ambiguous lookup - OID prefix is too short");
return GIT_EAMBIGUOUS;
}
error = git_repository_odb__weakptr(&odb, repo);
if (error < 0)
return error;
if (len > GIT_OID_HEXSZ)
len = GIT_OID_HEXSZ;
if (len == GIT_OID_HEXSZ) {
git_cached_obj *cached = NULL;
/* We want to match the full id : we can first look up in the cache,
* since there is no need to check for non ambiguousity
*/
cached = git_cache_get_any(&repo->objects, id);
if (cached != NULL) {
if (cached->flags == GIT_CACHE_STORE_PARSED) {
object = (git_object *)cached;
if (type != GIT_OBJECT_ANY && type != object->cached.type) {
git_object_free(object);
git_error_set(GIT_ERROR_INVALID,
"the requested type does not match the type in the ODB");
return GIT_ENOTFOUND;
}
*object_out = object;
return 0;
} else if (cached->flags == GIT_CACHE_STORE_RAW) {
odb_obj = (git_odb_object *)cached;
} else {
GIT_ASSERT(!"Wrong caching type in the global object cache");
}
} else {
/* Object was not found in the cache, let's explore the backends.
* We could just use git_odb_read_unique_short_oid,
* it is the same cost for packed and loose object backends,
* but it may be much more costly for sqlite and hiredis.
*/
error = git_odb_read(&odb_obj, odb, id);
}
} else {
git_oid short_oid = {{ 0 }};
git_oid__cpy_prefix(&short_oid, id, len);
/* If len < GIT_OID_HEXSZ (a strict short oid was given), we have
* 2 options :
* - We always search in the cache first. If we find that short oid is
* ambiguous, we can stop. But in all the other cases, we must then
* explore all the backends (to find an object if there was match,
* or to check that oid is not ambiguous if we have found 1 match in
* the cache)
* - We never explore the cache, go right to exploring the backends
* We chose the latter : we explore directly the backends.
*/
error = git_odb_read_prefix(&odb_obj, odb, &short_oid, len);
}
if (error < 0)
return error;
error = git_object__from_odb_object(object_out, repo, odb_obj, type);
git_odb_object_free(odb_obj);
return error;
}
int git_object_lookup(git_object **object_out, git_repository *repo, const git_oid *id, git_object_t type) {
return git_object_lookup_prefix(object_out, repo, id, GIT_OID_HEXSZ, type);
}
void git_object_free(git_object *object)
{
if (object == NULL)
return;
git_cached_obj_decref(object);
}
const git_oid *git_object_id(const git_object *obj)
{
GIT_ASSERT_ARG_WITH_RETVAL(obj, NULL);
return &obj->cached.oid;
}
git_object_t git_object_type(const git_object *obj)
{
GIT_ASSERT_ARG_WITH_RETVAL(obj, GIT_OBJECT_INVALID);
return obj->cached.type;
}
git_repository *git_object_owner(const git_object *obj)
{
GIT_ASSERT_ARG_WITH_RETVAL(obj, NULL);
return obj->repo;
}
const char *git_object_type2string(git_object_t type)
{
if (type < 0 || ((size_t) type) >= ARRAY_SIZE(git_objects_table))
return "";
return git_objects_table[type].str;
}
git_object_t git_object_string2type(const char *str)
{
if (!str)
return GIT_OBJECT_INVALID;
return git_object_stringn2type(str, strlen(str));
}
git_object_t git_object_stringn2type(const char *str, size_t len)
{
size_t i;
if (!str || !len || !*str)
return GIT_OBJECT_INVALID;
for (i = 0; i < ARRAY_SIZE(git_objects_table); i++)
if (*git_objects_table[i].str &&
!git__prefixncmp(str, len, git_objects_table[i].str))
return (git_object_t)i;
return GIT_OBJECT_INVALID;
}
int git_object_typeisloose(git_object_t type)
{
if (type < 0 || ((size_t) type) >= ARRAY_SIZE(git_objects_table))
return 0;
return (git_objects_table[type].size > 0) ? 1 : 0;
}
size_t git_object__size(git_object_t type)
{
if (type < 0 || ((size_t) type) >= ARRAY_SIZE(git_objects_table))
return 0;
return git_objects_table[type].size;
}
static int dereference_object(git_object **dereferenced, git_object *obj)
{
git_object_t type = git_object_type(obj);
switch (type) {
case GIT_OBJECT_COMMIT:
return git_commit_tree((git_tree **)dereferenced, (git_commit*)obj);
case GIT_OBJECT_TAG:
return git_tag_target(dereferenced, (git_tag*)obj);
case GIT_OBJECT_BLOB:
case GIT_OBJECT_TREE:
return GIT_EPEEL;
default:
return GIT_EINVALIDSPEC;
}
}
static int peel_error(int error, const git_oid *oid, git_object_t type)
{
const char *type_name;
char hex_oid[GIT_OID_HEXSZ + 1];
type_name = git_object_type2string(type);
git_oid_fmt(hex_oid, oid);
hex_oid[GIT_OID_HEXSZ] = '\0';
git_error_set(GIT_ERROR_OBJECT, "the git_object of id '%s' can not be "
"successfully peeled into a %s (git_object_t=%i).", hex_oid, type_name, type);
return error;
}
static int check_type_combination(git_object_t type, git_object_t target)
{
if (type == target)
return 0;
switch (type) {
case GIT_OBJECT_BLOB:
case GIT_OBJECT_TREE:
/* a blob or tree can never be peeled to anything but themselves */
return GIT_EINVALIDSPEC;
break;
case GIT_OBJECT_COMMIT:
/* a commit can only be peeled to a tree */
if (target != GIT_OBJECT_TREE && target != GIT_OBJECT_ANY)
return GIT_EINVALIDSPEC;
break;
case GIT_OBJECT_TAG:
/* a tag may point to anything, so we let anything through */
break;
default:
return GIT_EINVALIDSPEC;
}
return 0;
}
int git_object_peel(
git_object **peeled,
const git_object *object,
git_object_t target_type)
{
git_object *source, *deref = NULL;
int error;
GIT_ASSERT_ARG(object);
GIT_ASSERT_ARG(peeled);
GIT_ASSERT_ARG(target_type == GIT_OBJECT_TAG ||
target_type == GIT_OBJECT_COMMIT ||
target_type == GIT_OBJECT_TREE ||
target_type == GIT_OBJECT_BLOB ||
target_type == GIT_OBJECT_ANY);
if ((error = check_type_combination(git_object_type(object), target_type)) < 0)
return peel_error(error, git_object_id(object), target_type);
if (git_object_type(object) == target_type)
return git_object_dup(peeled, (git_object *)object);
source = (git_object *)object;
while (!(error = dereference_object(&deref, source))) {
if (source != object)
git_object_free(source);
if (git_object_type(deref) == target_type) {
*peeled = deref;
return 0;
}
if (target_type == GIT_OBJECT_ANY &&
git_object_type(deref) != git_object_type(object))
{
*peeled = deref;
return 0;
}
source = deref;
deref = NULL;
}
if (source != object)
git_object_free(source);
git_object_free(deref);
if (error)
error = peel_error(error, git_object_id(object), target_type);
return error;
}
int git_object_dup(git_object **dest, git_object *source)
{
git_cached_obj_incref(source);
*dest = source;
return 0;
}
int git_object_lookup_bypath(
git_object **out,
const git_object *treeish,
const char *path,
git_object_t type)
{
int error = -1;
git_tree *tree = NULL;
git_tree_entry *entry = NULL;
GIT_ASSERT_ARG(out);
GIT_ASSERT_ARG(treeish);
GIT_ASSERT_ARG(path);
if ((error = git_object_peel((git_object**)&tree, treeish, GIT_OBJECT_TREE)) < 0 ||
(error = git_tree_entry_bypath(&entry, tree, path)) < 0)
{
goto cleanup;
}
if (type != GIT_OBJECT_ANY && git_tree_entry_type(entry) != type)
{
git_error_set(GIT_ERROR_OBJECT,
"object at path '%s' is not of the asked-for type %d",
path, type);
error = GIT_EINVALIDSPEC;
goto cleanup;
}
error = git_tree_entry_to_object(out, git_object_owner(treeish), entry);
cleanup:
git_tree_entry_free(entry);
git_tree_free(tree);
return error;
}
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;
GIT_ASSERT_ARG(out);
GIT_ASSERT_ARG(obj);
if ((error = git_buf_sanitize(out)) < 0)
return error;
repo = git_object_owner(obj);
if ((error = git_repository__configmap_lookup(&len, repo, GIT_CONFIGMAP_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;
git_error_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;
}
bool git_object__is_valid(
git_repository *repo, const git_oid *id, git_object_t expected_type)
{
git_odb *odb;
git_object_t actual_type;
size_t len;
int error;
if (!git_object__strict_input_validation)
return true;
if ((error = git_repository_odb__weakptr(&odb, repo)) < 0 ||
(error = git_odb_read_header(&len, &actual_type, odb, id)) < 0)
return false;
if (expected_type != GIT_OBJECT_ANY && expected_type != actual_type) {
git_error_set(GIT_ERROR_INVALID,
"the requested type does not match the type in the ODB");
return false;
}
return true;
}
|
0 |
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2
|
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2/src/config_cache.c
|
/*
* Copyright (C) the libgit2 contributors. All rights reserved.
*
* This file is part of libgit2, distributed under the GNU GPL v2 with
* a Linking Exception. For full terms see the included COPYING file.
*/
#include "common.h"
#include "futils.h"
#include "repository.h"
#include "config.h"
#include "git2/config.h"
#include "vector.h"
#include "filter.h"
struct map_data {
const char *name;
git_configmap *maps;
size_t map_count;
int default_value;
};
/*
* core.eol
* Sets the line ending type to use in the working directory for
* files that have the text property set. Alternatives are lf, crlf
* and native, which uses the platform's native line ending. The default
* value is native. See gitattributes(5) for more information on
* end-of-line conversion.
*/
static git_configmap _configmap_eol[] = {
{GIT_CONFIGMAP_FALSE, NULL, GIT_EOL_UNSET},
{GIT_CONFIGMAP_STRING, "lf", GIT_EOL_LF},
{GIT_CONFIGMAP_STRING, "crlf", GIT_EOL_CRLF},
{GIT_CONFIGMAP_STRING, "native", GIT_EOL_NATIVE}
};
/*
* core.autocrlf
* Setting this variable to "true" is almost the same as setting
* the text attribute to "auto" on all files except that text files are
* not guaranteed to be normalized: files that contain CRLF in the
* repository will not be touched. Use this setting if you want to have
* CRLF line endings in your working directory even though the repository
* does not have normalized line endings. This variable can be set to input,
* in which case no output conversion is performed.
*/
static git_configmap _configmap_autocrlf[] = {
{GIT_CONFIGMAP_FALSE, NULL, GIT_AUTO_CRLF_FALSE},
{GIT_CONFIGMAP_TRUE, NULL, GIT_AUTO_CRLF_TRUE},
{GIT_CONFIGMAP_STRING, "input", GIT_AUTO_CRLF_INPUT}
};
static git_configmap _configmap_safecrlf[] = {
{GIT_CONFIGMAP_FALSE, NULL, GIT_SAFE_CRLF_FALSE},
{GIT_CONFIGMAP_TRUE, NULL, GIT_SAFE_CRLF_FAIL},
{GIT_CONFIGMAP_STRING, "warn", GIT_SAFE_CRLF_WARN}
};
static git_configmap _configmap_logallrefupdates[] = {
{GIT_CONFIGMAP_FALSE, NULL, GIT_LOGALLREFUPDATES_FALSE},
{GIT_CONFIGMAP_TRUE, NULL, GIT_LOGALLREFUPDATES_TRUE},
{GIT_CONFIGMAP_STRING, "always", GIT_LOGALLREFUPDATES_ALWAYS},
};
/*
* Generic map for integer values
*/
static git_configmap _configmap_int[] = {
{GIT_CONFIGMAP_INT32, NULL, 0},
};
static struct map_data _configmaps[] = {
{"core.autocrlf", _configmap_autocrlf, ARRAY_SIZE(_configmap_autocrlf), GIT_AUTO_CRLF_DEFAULT},
{"core.eol", _configmap_eol, ARRAY_SIZE(_configmap_eol), GIT_EOL_DEFAULT},
{"core.symlinks", NULL, 0, GIT_SYMLINKS_DEFAULT },
{"core.ignorecase", NULL, 0, GIT_IGNORECASE_DEFAULT },
{"core.filemode", NULL, 0, GIT_FILEMODE_DEFAULT },
{"core.ignorestat", NULL, 0, GIT_IGNORESTAT_DEFAULT },
{"core.trustctime", NULL, 0, GIT_TRUSTCTIME_DEFAULT },
{"core.abbrev", _configmap_int, 1, GIT_ABBREV_DEFAULT },
{"core.precomposeunicode", NULL, 0, GIT_PRECOMPOSE_DEFAULT },
{"core.safecrlf", _configmap_safecrlf, ARRAY_SIZE(_configmap_safecrlf), GIT_SAFE_CRLF_DEFAULT},
{"core.logallrefupdates", _configmap_logallrefupdates, ARRAY_SIZE(_configmap_logallrefupdates), GIT_LOGALLREFUPDATES_DEFAULT},
{"core.protecthfs", NULL, 0, GIT_PROTECTHFS_DEFAULT },
{"core.protectntfs", NULL, 0, GIT_PROTECTNTFS_DEFAULT },
{"core.fsyncobjectfiles", NULL, 0, GIT_FSYNCOBJECTFILES_DEFAULT },
{"core.longpaths", NULL, 0, GIT_LONGPATHS_DEFAULT },
};
int git_config__configmap_lookup(int *out, git_config *config, git_configmap_item item)
{
int error = 0;
struct map_data *data = &_configmaps[(int)item];
git_config_entry *entry;
if ((error = git_config__lookup_entry(&entry, config, data->name, false)) < 0)
return error;
if (!entry)
*out = data->default_value;
else if (data->maps)
error = git_config_lookup_map_value(
out, data->maps, data->map_count, entry->value);
else
error = git_config_parse_bool(out, entry->value);
git_config_entry_free(entry);
return error;
}
int git_repository__configmap_lookup(int *out, git_repository *repo, git_configmap_item item)
{
intptr_t value = (intptr_t)git_atomic_load(repo->configmap_cache[(int)item]);
*out = (int)value;
if (value == GIT_CONFIGMAP_NOT_CACHED) {
git_config *config;
intptr_t oldval = value;
int error;
if ((error = git_repository_config__weakptr(&config, repo)) < 0 ||
(error = git_config__configmap_lookup(out, config, item)) < 0)
return error;
value = *out;
git_atomic_compare_and_swap(&repo->configmap_cache[(int)item], (void *)oldval, (void *)value);
}
return 0;
}
void git_repository__configmap_lookup_cache_clear(git_repository *repo)
{
int i;
for (i = 0; i < GIT_CONFIGMAP_CACHE_MAX; ++i)
repo->configmap_cache[i] = GIT_CONFIGMAP_NOT_CACHED;
}
|
0 |
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2
|
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2/src/iterator.h
|
/*
* Copyright (C) the libgit2 contributors. All rights reserved.
*
* This file is part of libgit2, distributed under the GNU GPL v2 with
* a Linking Exception. For full terms see the included COPYING file.
*/
#ifndef INCLUDE_iterator_h__
#define INCLUDE_iterator_h__
#include "common.h"
#include "git2/index.h"
#include "vector.h"
#include "buffer.h"
#include "ignore.h"
typedef struct git_iterator git_iterator;
typedef enum {
GIT_ITERATOR_EMPTY = 0,
GIT_ITERATOR_TREE = 1,
GIT_ITERATOR_INDEX = 2,
GIT_ITERATOR_WORKDIR = 3,
GIT_ITERATOR_FS = 4,
} git_iterator_t;
typedef enum {
/** ignore case for entry sort order */
GIT_ITERATOR_IGNORE_CASE = (1u << 0),
/** force case sensitivity for entry sort order */
GIT_ITERATOR_DONT_IGNORE_CASE = (1u << 1),
/** return tree items in addition to blob items */
GIT_ITERATOR_INCLUDE_TREES = (1u << 2),
/** don't flatten trees, requiring advance_into (implies INCLUDE_TREES) */
GIT_ITERATOR_DONT_AUTOEXPAND = (1u << 3),
/** convert precomposed unicode to decomposed unicode */
GIT_ITERATOR_PRECOMPOSE_UNICODE = (1u << 4),
/** never convert precomposed unicode to decomposed unicode */
GIT_ITERATOR_DONT_PRECOMPOSE_UNICODE = (1u << 5),
/** include conflicts */
GIT_ITERATOR_INCLUDE_CONFLICTS = (1u << 6),
/** descend into symlinked directories */
GIT_ITERATOR_DESCEND_SYMLINKS = (1u << 7),
/** hash files in workdir or filesystem iterators */
GIT_ITERATOR_INCLUDE_HASH = (1u << 8),
} git_iterator_flag_t;
typedef enum {
GIT_ITERATOR_STATUS_NORMAL = 0,
GIT_ITERATOR_STATUS_IGNORED = 1,
GIT_ITERATOR_STATUS_EMPTY = 2,
GIT_ITERATOR_STATUS_FILTERED = 3
} git_iterator_status_t;
typedef struct {
const char *start;
const char *end;
/* paths to include in the iterator (literal). if set, any paths not
* listed here will be excluded from iteration.
*/
git_strarray pathlist;
/* flags, from above */
unsigned int flags;
} git_iterator_options;
#define GIT_ITERATOR_OPTIONS_INIT {0}
typedef struct {
int (*current)(const git_index_entry **, git_iterator *);
int (*advance)(const git_index_entry **, git_iterator *);
int (*advance_into)(const git_index_entry **, git_iterator *);
int (*advance_over)(
const git_index_entry **, git_iterator_status_t *, git_iterator *);
int (*reset)(git_iterator *);
void (*free)(git_iterator *);
} git_iterator_callbacks;
struct git_iterator {
git_iterator_t type;
git_iterator_callbacks *cb;
git_repository *repo;
git_index *index;
char *start;
size_t start_len;
char *end;
size_t end_len;
bool started;
bool ended;
git_vector pathlist;
size_t pathlist_walk_idx;
int (*strcomp)(const char *a, const char *b);
int (*strncomp)(const char *a, const char *b, size_t n);
int (*prefixcomp)(const char *str, const char *prefix);
int (*entry_srch)(const void *key, const void *array_member);
size_t stat_calls;
unsigned int flags;
};
extern int git_iterator_for_nothing(
git_iterator **out,
git_iterator_options *options);
/* tree iterators will match the ignore_case value from the index of the
* repository, unless you override with a non-zero flag value
*/
extern int git_iterator_for_tree(
git_iterator **out,
git_tree *tree,
git_iterator_options *options);
/* index iterators will take the ignore_case value from the index; the
* ignore_case flags are not used
*/
extern int git_iterator_for_index(
git_iterator **out,
git_repository *repo,
git_index *index,
git_iterator_options *options);
extern int git_iterator_for_workdir_ext(
git_iterator **out,
git_repository *repo,
const char *repo_workdir,
git_index *index,
git_tree *tree,
git_iterator_options *options);
/* workdir iterators will match the ignore_case value from the index of the
* repository, unless you override with a non-zero flag value
*/
GIT_INLINE(int) git_iterator_for_workdir(
git_iterator **out,
git_repository *repo,
git_index *index,
git_tree *tree,
git_iterator_options *options)
{
return git_iterator_for_workdir_ext(out, repo, NULL, index, tree, options);
}
/* for filesystem iterators, you have to explicitly pass in the ignore_case
* behavior that you desire
*/
extern int git_iterator_for_filesystem(
git_iterator **out,
const char *root,
git_iterator_options *options);
extern void git_iterator_free(git_iterator *iter);
/* Return a git_index_entry structure for the current value the iterator
* is looking at or NULL if the iterator is at the end.
*
* The entry may noy be fully populated. Tree iterators will only have a
* value mode, OID, and path. Workdir iterators will not have an OID (but
* you can use `git_iterator_current_oid()` to calculate it on demand).
*
* You do not need to free the entry. It is still "owned" by the iterator.
* Once you call `git_iterator_advance()` then the old entry is no longer
* guaranteed to be valid - it may be freed or just overwritten in place.
*/
GIT_INLINE(int) git_iterator_current(
const git_index_entry **entry, git_iterator *iter)
{
return iter->cb->current(entry, iter);
}
/**
* Advance to the next item for the iterator.
*
* If GIT_ITERATOR_INCLUDE_TREES is set, this may be a tree item. If
* GIT_ITERATOR_DONT_AUTOEXPAND is set, calling this again when on a tree
* item will skip over all the items under that tree.
*/
GIT_INLINE(int) git_iterator_advance(
const git_index_entry **entry, git_iterator *iter)
{
return iter->cb->advance(entry, iter);
}
/**
* Iterate into a tree item (when GIT_ITERATOR_DONT_AUTOEXPAND is set).
*
* git_iterator_advance() steps through all items being iterated over
* (either with or without trees, depending on GIT_ITERATOR_INCLUDE_TREES),
* but if GIT_ITERATOR_DONT_AUTOEXPAND is set, it will skip to the next
* sibling of a tree instead of going to the first child of the tree. In
* that case, use this function to advance to the first child of the tree.
*
* If the current item is not a tree, this is a no-op.
*
* For filesystem and working directory iterators, a tree (i.e. directory)
* can be empty. In that case, this function returns GIT_ENOTFOUND and
* does not advance. That can't happen for tree and index iterators.
*/
GIT_INLINE(int) git_iterator_advance_into(
const git_index_entry **entry, git_iterator *iter)
{
return iter->cb->advance_into(entry, iter);
}
/* Advance over a directory and check if it contains no files or just
* ignored files.
*
* In a tree or the index, all directories will contain files, but in the
* working directory it is possible to have an empty directory tree or a
* tree that only contains ignored files. Many Git operations treat these
* cases specially. This advances over a directory (presumably an
* untracked directory) but checks during the scan if there are any files
* and any non-ignored files.
*/
GIT_INLINE(int) git_iterator_advance_over(
const git_index_entry **entry,
git_iterator_status_t *status,
git_iterator *iter)
{
return iter->cb->advance_over(entry, status, iter);
}
/**
* Go back to the start of the iteration.
*/
GIT_INLINE(int) git_iterator_reset(git_iterator *iter)
{
return iter->cb->reset(iter);
}
/**
* Go back to the start of the iteration after updating the `start` and
* `end` pathname boundaries of the iteration.
*/
extern int git_iterator_reset_range(
git_iterator *iter, const char *start, const char *end);
GIT_INLINE(git_iterator_t) git_iterator_type(git_iterator *iter)
{
return iter->type;
}
GIT_INLINE(git_repository *) git_iterator_owner(git_iterator *iter)
{
return iter->repo;
}
GIT_INLINE(git_index *) git_iterator_index(git_iterator *iter)
{
return iter->index;
}
GIT_INLINE(git_iterator_flag_t) git_iterator_flags(git_iterator *iter)
{
return iter->flags;
}
GIT_INLINE(bool) git_iterator_ignore_case(git_iterator *iter)
{
return ((iter->flags & GIT_ITERATOR_IGNORE_CASE) != 0);
}
extern int git_iterator_set_ignore_case(
git_iterator *iter, bool ignore_case);
extern int git_iterator_current_tree_entry(
const git_tree_entry **entry_out, git_iterator *iter);
extern int git_iterator_current_parent_tree(
const git_tree **tree_out, git_iterator *iter, size_t depth);
extern bool git_iterator_current_is_ignored(git_iterator *iter);
extern bool git_iterator_current_tree_is_ignored(git_iterator *iter);
/**
* Get full path of the current item from a workdir iterator. This will
* return NULL for a non-workdir iterator. The git_buf is still owned by
* the iterator; this is exposed just for efficiency.
*/
extern int git_iterator_current_workdir_path(
git_buf **path, git_iterator *iter);
/**
* Retrieve the index stored in the iterator.
*
* Only implemented for the workdir and index iterators.
*/
extern git_index *git_iterator_index(git_iterator *iter);
typedef int (*git_iterator_foreach_cb)(
const git_index_entry *entry,
void *data);
/**
* Walk the given iterator and invoke the callback for each path
* contained in the iterator.
*/
extern int git_iterator_foreach(
git_iterator *iterator,
git_iterator_foreach_cb cb,
void *data);
typedef int (*git_iterator_walk_cb)(
const git_index_entry **entries,
void *data);
/**
* Walk the given iterators in lock-step. The given callback will be
* called for each unique path, with the index entry in each iterator
* (or NULL if the given iterator does not contain that path).
*/
extern int git_iterator_walk(
git_iterator **iterators,
size_t cnt,
git_iterator_walk_cb cb,
void *data);
#endif
|
0 |
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2
|
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2/src/idxmap.c
|
/*
* Copyright (C) the libgit2 contributors. All rights reserved.
*
* This file is part of libgit2, distributed under the GNU GPL v2 with
* a Linking Exception. For full terms see the included COPYING file.
*/
#include "idxmap.h"
#define kmalloc git__malloc
#define kcalloc git__calloc
#define krealloc git__realloc
#define kreallocarray git__reallocarray
#define kfree git__free
#include "khash.h"
__KHASH_TYPE(idx, const git_index_entry *, git_index_entry *)
__KHASH_TYPE(idxicase, const git_index_entry *, git_index_entry *)
/* This is __ac_X31_hash_string but with tolower and it takes the entry's stage into account */
static kh_inline khint_t idxentry_hash(const git_index_entry *e)
{
const char *s = e->path;
khint_t h = (khint_t)git__tolower(*s);
if (h) for (++s ; *s; ++s) h = (h << 5) - h + (khint_t)git__tolower(*s);
return h + GIT_INDEX_ENTRY_STAGE(e);
}
#define idxentry_equal(a, b) (GIT_INDEX_ENTRY_STAGE(a) == GIT_INDEX_ENTRY_STAGE(b) && strcmp(a->path, b->path) == 0)
#define idxentry_icase_equal(a, b) (GIT_INDEX_ENTRY_STAGE(a) == GIT_INDEX_ENTRY_STAGE(b) && strcasecmp(a->path, b->path) == 0)
__KHASH_IMPL(idx, static kh_inline, const git_index_entry *, git_index_entry *, 1, idxentry_hash, idxentry_equal)
__KHASH_IMPL(idxicase, static kh_inline, const git_index_entry *, git_index_entry *, 1, idxentry_hash, idxentry_icase_equal)
int git_idxmap_new(git_idxmap **out)
{
*out = kh_init(idx);
GIT_ERROR_CHECK_ALLOC(*out);
return 0;
}
int git_idxmap_icase_new(git_idxmap_icase **out)
{
*out = kh_init(idxicase);
GIT_ERROR_CHECK_ALLOC(*out);
return 0;
}
void git_idxmap_free(git_idxmap *map)
{
kh_destroy(idx, map);
}
void git_idxmap_icase_free(git_idxmap_icase *map)
{
kh_destroy(idxicase, map);
}
void git_idxmap_clear(git_idxmap *map)
{
kh_clear(idx, map);
}
void git_idxmap_icase_clear(git_idxmap_icase *map)
{
kh_clear(idxicase, map);
}
int git_idxmap_resize(git_idxmap *map, size_t size)
{
if (!git__is_uint32(size) ||
kh_resize(idx, map, (khiter_t)size) < 0) {
git_error_set_oom();
return -1;
}
return 0;
}
int git_idxmap_icase_resize(git_idxmap_icase *map, size_t size)
{
if (!git__is_uint32(size) ||
kh_resize(idxicase, map, (khiter_t)size) < 0) {
git_error_set_oom();
return -1;
}
return 0;
}
void *git_idxmap_get(git_idxmap *map, const git_index_entry *key)
{
size_t idx = kh_get(idx, map, key);
if (idx == kh_end(map) || !kh_exist(map, idx))
return NULL;
return kh_val(map, idx);
}
int git_idxmap_set(git_idxmap *map, const git_index_entry *key, void *value)
{
size_t idx;
int rval;
idx = kh_put(idx, map, key, &rval);
if (rval < 0)
return -1;
if (rval == 0)
kh_key(map, idx) = key;
kh_val(map, idx) = value;
return 0;
}
int git_idxmap_icase_set(git_idxmap_icase *map, const git_index_entry *key, void *value)
{
size_t idx;
int rval;
idx = kh_put(idxicase, map, key, &rval);
if (rval < 0)
return -1;
if (rval == 0)
kh_key(map, idx) = key;
kh_val(map, idx) = value;
return 0;
}
void *git_idxmap_icase_get(git_idxmap_icase *map, const git_index_entry *key)
{
size_t idx = kh_get(idxicase, map, key);
if (idx == kh_end(map) || !kh_exist(map, idx))
return NULL;
return kh_val(map, idx);
}
int git_idxmap_delete(git_idxmap *map, const git_index_entry *key)
{
khiter_t idx = kh_get(idx, map, key);
if (idx == kh_end(map))
return GIT_ENOTFOUND;
kh_del(idx, map, idx);
return 0;
}
int git_idxmap_icase_delete(git_idxmap_icase *map, const git_index_entry *key)
{
khiter_t idx = kh_get(idxicase, map, key);
if (idx == kh_end(map))
return GIT_ENOTFOUND;
kh_del(idxicase, map, idx);
return 0;
}
|
0 |
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2
|
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2/src/hash.c
|
/*
* Copyright (C) the libgit2 contributors. All rights reserved.
*
* This file is part of libgit2, distributed under the GNU GPL v2 with
* a Linking Exception. For full terms see the included COPYING file.
*/
#include "hash.h"
int git_hash_global_init(void)
{
return git_hash_sha1_global_init();
}
int git_hash_ctx_init(git_hash_ctx *ctx)
{
int error;
if ((error = git_hash_sha1_ctx_init(&ctx->ctx.sha1)) < 0)
return error;
ctx->algo = GIT_HASH_ALGO_SHA1;
return 0;
}
void git_hash_ctx_cleanup(git_hash_ctx *ctx)
{
switch (ctx->algo) {
case GIT_HASH_ALGO_SHA1:
git_hash_sha1_ctx_cleanup(&ctx->ctx.sha1);
return;
default:
/* unreachable */ ;
}
}
int git_hash_init(git_hash_ctx *ctx)
{
switch (ctx->algo) {
case GIT_HASH_ALGO_SHA1:
return git_hash_sha1_init(&ctx->ctx.sha1);
default:
/* unreachable */ ;
}
GIT_ASSERT(0);
return -1;
}
int git_hash_update(git_hash_ctx *ctx, const void *data, size_t len)
{
switch (ctx->algo) {
case GIT_HASH_ALGO_SHA1:
return git_hash_sha1_update(&ctx->ctx.sha1, data, len);
default:
/* unreachable */ ;
}
GIT_ASSERT(0);
return -1;
}
int git_hash_final(git_oid *out, git_hash_ctx *ctx)
{
switch (ctx->algo) {
case GIT_HASH_ALGO_SHA1:
return git_hash_sha1_final(out, &ctx->ctx.sha1);
default:
/* unreachable */ ;
}
GIT_ASSERT(0);
return -1;
}
int git_hash_buf(git_oid *out, const void *data, size_t len)
{
git_hash_ctx ctx;
int error = 0;
if (git_hash_ctx_init(&ctx) < 0)
return -1;
if ((error = git_hash_update(&ctx, data, len)) >= 0)
error = git_hash_final(out, &ctx);
git_hash_ctx_cleanup(&ctx);
return error;
}
int git_hash_vec(git_oid *out, git_buf_vec *vec, size_t n)
{
git_hash_ctx ctx;
size_t i;
int error = 0;
if (git_hash_ctx_init(&ctx) < 0)
return -1;
for (i = 0; i < n; i++) {
if ((error = git_hash_update(&ctx, vec[i].data, vec[i].len)) < 0)
goto done;
}
error = git_hash_final(out, &ctx);
done:
git_hash_ctx_cleanup(&ctx);
return error;
}
|
0 |
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2
|
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2/src/diff_xdiff.c
|
/*
* Copyright (C) the libgit2 contributors. All rights reserved.
*
* This file is part of libgit2, distributed under the GNU GPL v2 with
* a Linking Exception. For full terms see the included COPYING file.
*/
#include "diff_xdiff.h"
#include "git2/errors.h"
#include "diff.h"
#include "diff_driver.h"
#include "patch_generate.h"
static int git_xdiff_scan_int(const char **str, int *value)
{
const char *scan = *str;
int v = 0, digits = 0;
/* find next digit */
for (scan = *str; *scan && !git__isdigit(*scan); scan++);
/* parse next number */
for (; git__isdigit(*scan); scan++, digits++)
v = (v * 10) + (*scan - '0');
*str = scan;
*value = v;
return (digits > 0) ? 0 : -1;
}
static int git_xdiff_parse_hunk(git_diff_hunk *hunk, const char *header)
{
/* expect something of the form "@@ -%d[,%d] +%d[,%d] @@" */
if (*header != '@')
goto fail;
if (git_xdiff_scan_int(&header, &hunk->old_start) < 0)
goto fail;
if (*header == ',') {
if (git_xdiff_scan_int(&header, &hunk->old_lines) < 0)
goto fail;
} else
hunk->old_lines = 1;
if (git_xdiff_scan_int(&header, &hunk->new_start) < 0)
goto fail;
if (*header == ',') {
if (git_xdiff_scan_int(&header, &hunk->new_lines) < 0)
goto fail;
} else
hunk->new_lines = 1;
if (hunk->old_start < 0 || hunk->new_start < 0)
goto fail;
return 0;
fail:
git_error_set(GIT_ERROR_INVALID, "malformed hunk header from xdiff");
return -1;
}
typedef struct {
git_xdiff_output *xo;
git_patch_generated *patch;
git_diff_hunk hunk;
int old_lineno, new_lineno;
mmfile_t xd_old_data, xd_new_data;
} git_xdiff_info;
static int diff_update_lines(
git_xdiff_info *info,
git_diff_line *line,
const char *content,
size_t content_len)
{
const char *scan = content, *scan_end = content + content_len;
for (line->num_lines = 0; scan < scan_end; ++scan)
if (*scan == '\n')
++line->num_lines;
line->content = content;
line->content_len = content_len;
/* expect " "/"-"/"+", then data */
switch (line->origin) {
case GIT_DIFF_LINE_ADDITION:
case GIT_DIFF_LINE_DEL_EOFNL:
line->old_lineno = -1;
line->new_lineno = info->new_lineno;
info->new_lineno += (int)line->num_lines;
break;
case GIT_DIFF_LINE_DELETION:
case GIT_DIFF_LINE_ADD_EOFNL:
line->old_lineno = info->old_lineno;
line->new_lineno = -1;
info->old_lineno += (int)line->num_lines;
break;
case GIT_DIFF_LINE_CONTEXT:
case GIT_DIFF_LINE_CONTEXT_EOFNL:
line->old_lineno = info->old_lineno;
line->new_lineno = info->new_lineno;
info->old_lineno += (int)line->num_lines;
info->new_lineno += (int)line->num_lines;
break;
default:
git_error_set(GIT_ERROR_INVALID, "unknown diff line origin %02x",
(unsigned int)line->origin);
return -1;
}
return 0;
}
static int git_xdiff_cb(void *priv, mmbuffer_t *bufs, int len)
{
git_xdiff_info *info = priv;
git_patch_generated *patch = info->patch;
const git_diff_delta *delta = patch->base.delta;
git_patch_generated_output *output = &info->xo->output;
git_diff_line line;
size_t buffer_len;
if (len == 1) {
output->error = git_xdiff_parse_hunk(&info->hunk, bufs[0].ptr);
if (output->error < 0)
return output->error;
info->hunk.header_len = bufs[0].size;
if (info->hunk.header_len >= sizeof(info->hunk.header))
info->hunk.header_len = sizeof(info->hunk.header) - 1;
/* Sanitize the hunk header in case there is invalid Unicode */
buffer_len = git_utf8_valid_buf_length(bufs[0].ptr, info->hunk.header_len);
/* Sanitizing the hunk header may delete the newline, so add it back again if there is room */
if (buffer_len < info->hunk.header_len) {
bufs[0].ptr[buffer_len] = '\n';
buffer_len += 1;
info->hunk.header_len = buffer_len;
}
memcpy(info->hunk.header, bufs[0].ptr, info->hunk.header_len);
info->hunk.header[info->hunk.header_len] = '\0';
if (output->hunk_cb != NULL &&
(output->error = output->hunk_cb(
delta, &info->hunk, output->payload)))
return output->error;
info->old_lineno = info->hunk.old_start;
info->new_lineno = info->hunk.new_start;
}
if (len == 2 || len == 3) {
/* expect " "/"-"/"+", then data */
line.origin =
(*bufs[0].ptr == '+') ? GIT_DIFF_LINE_ADDITION :
(*bufs[0].ptr == '-') ? GIT_DIFF_LINE_DELETION :
GIT_DIFF_LINE_CONTEXT;
if (line.origin == GIT_DIFF_LINE_ADDITION)
line.content_offset = bufs[1].ptr - info->xd_new_data.ptr;
else if (line.origin == GIT_DIFF_LINE_DELETION)
line.content_offset = bufs[1].ptr - info->xd_old_data.ptr;
else
line.content_offset = -1;
output->error = diff_update_lines(
info, &line, bufs[1].ptr, bufs[1].size);
if (!output->error && output->data_cb != NULL)
output->error = output->data_cb(
delta, &info->hunk, &line, output->payload);
}
if (len == 3 && !output->error) {
/* If we have a '+' and a third buf, then we have added a line
* without a newline and the old code had one, so DEL_EOFNL.
* If we have a '-' and a third buf, then we have removed a line
* with out a newline but added a blank line, so ADD_EOFNL.
*/
line.origin =
(*bufs[0].ptr == '+') ? GIT_DIFF_LINE_DEL_EOFNL :
(*bufs[0].ptr == '-') ? GIT_DIFF_LINE_ADD_EOFNL :
GIT_DIFF_LINE_CONTEXT_EOFNL;
line.content_offset = -1;
output->error = diff_update_lines(
info, &line, bufs[2].ptr, bufs[2].size);
if (!output->error && output->data_cb != NULL)
output->error = output->data_cb(
delta, &info->hunk, &line, output->payload);
}
return output->error;
}
static int git_xdiff(git_patch_generated_output *output, git_patch_generated *patch)
{
git_xdiff_output *xo = (git_xdiff_output *)output;
git_xdiff_info info;
git_diff_find_context_payload findctxt;
memset(&info, 0, sizeof(info));
info.patch = patch;
info.xo = xo;
xo->callback.priv = &info;
git_diff_find_context_init(
&xo->config.find_func, &findctxt, git_patch_generated_driver(patch));
xo->config.find_func_priv = &findctxt;
if (xo->config.find_func != NULL)
xo->config.flags |= XDL_EMIT_FUNCNAMES;
else
xo->config.flags &= ~XDL_EMIT_FUNCNAMES;
/* TODO: check ofile.opts_flags to see if driver-specific per-file
* updates are needed to xo->params.flags
*/
git_patch_generated_old_data(&info.xd_old_data.ptr, &info.xd_old_data.size, patch);
git_patch_generated_new_data(&info.xd_new_data.ptr, &info.xd_new_data.size, patch);
if (info.xd_old_data.size > GIT_XDIFF_MAX_SIZE ||
info.xd_new_data.size > GIT_XDIFF_MAX_SIZE) {
git_error_set(GIT_ERROR_INVALID, "files too large for diff");
return -1;
}
xdl_diff(&info.xd_old_data, &info.xd_new_data,
&xo->params, &xo->config, &xo->callback);
git_diff_find_context_clear(&findctxt);
return xo->output.error;
}
void git_xdiff_init(git_xdiff_output *xo, const git_diff_options *opts)
{
uint32_t flags = opts ? opts->flags : 0;
xo->output.diff_cb = git_xdiff;
xo->config.ctxlen = opts ? opts->context_lines : 3;
xo->config.interhunkctxlen = opts ? opts->interhunk_lines : 0;
if (flags & GIT_DIFF_IGNORE_WHITESPACE)
xo->params.flags |= XDF_WHITESPACE_FLAGS;
if (flags & GIT_DIFF_IGNORE_WHITESPACE_CHANGE)
xo->params.flags |= XDF_IGNORE_WHITESPACE_CHANGE;
if (flags & GIT_DIFF_IGNORE_WHITESPACE_EOL)
xo->params.flags |= XDF_IGNORE_WHITESPACE_AT_EOL;
if (flags & GIT_DIFF_INDENT_HEURISTIC)
xo->params.flags |= XDF_INDENT_HEURISTIC;
if (flags & GIT_DIFF_PATIENCE)
xo->params.flags |= XDF_PATIENCE_DIFF;
if (flags & GIT_DIFF_MINIMAL)
xo->params.flags |= XDF_NEED_MINIMAL;
if (flags & GIT_DIFF_IGNORE_BLANK_LINES)
xo->params.flags |= XDF_IGNORE_BLANK_LINES;
xo->callback.outf = git_xdiff_cb;
}
|
0 |
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2
|
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2/src/notes.c
|
/*
* Copyright (C) the libgit2 contributors. All rights reserved.
*
* This file is part of libgit2, distributed under the GNU GPL v2 with
* a Linking Exception. For full terms see the included COPYING file.
*/
#include "notes.h"
#include "git2.h"
#include "refs.h"
#include "config.h"
#include "iterator.h"
#include "signature.h"
#include "blob.h"
static int note_error_notfound(void)
{
git_error_set(GIT_ERROR_INVALID, "note could not be found");
return GIT_ENOTFOUND;
}
static int find_subtree_in_current_level(
git_tree **out,
git_repository *repo,
git_tree *parent,
const char *annotated_object_sha,
int fanout)
{
size_t i;
const git_tree_entry *entry;
*out = NULL;
if (parent == NULL)
return note_error_notfound();
for (i = 0; i < git_tree_entrycount(parent); i++) {
entry = git_tree_entry_byindex(parent, i);
if (!git__ishex(git_tree_entry_name(entry)))
continue;
if (S_ISDIR(git_tree_entry_filemode(entry))
&& strlen(git_tree_entry_name(entry)) == 2
&& !strncmp(git_tree_entry_name(entry), annotated_object_sha + fanout, 2))
return git_tree_lookup(out, repo, git_tree_entry_id(entry));
/* Not a DIR, so do we have an already existing blob? */
if (!strcmp(git_tree_entry_name(entry), annotated_object_sha + fanout))
return GIT_EEXISTS;
}
return note_error_notfound();
}
static int find_subtree_r(git_tree **out, git_tree *root,
git_repository *repo, const char *target, int *fanout)
{
int error;
git_tree *subtree = NULL;
*out = NULL;
error = find_subtree_in_current_level(&subtree, repo, root, target, *fanout);
if (error == GIT_EEXISTS)
return git_tree_lookup(out, repo, git_tree_id(root));
if (error < 0)
return error;
*fanout += 2;
error = find_subtree_r(out, subtree, repo, target, fanout);
git_tree_free(subtree);
return error;
}
static int find_blob(git_oid *blob, git_tree *tree, const char *target)
{
size_t i;
const git_tree_entry *entry;
for (i=0; i<git_tree_entrycount(tree); i++) {
entry = git_tree_entry_byindex(tree, i);
if (!strcmp(git_tree_entry_name(entry), target)) {
/* found matching note object - return */
git_oid_cpy(blob, git_tree_entry_id(entry));
return 0;
}
}
return note_error_notfound();
}
static int tree_write(
git_tree **out,
git_repository *repo,
git_tree *source_tree,
const git_oid *object_oid,
const char *treeentry_name,
unsigned int attributes)
{
int error;
git_treebuilder *tb = NULL;
const git_tree_entry *entry;
git_oid tree_oid;
if ((error = git_treebuilder_new(&tb, repo, source_tree)) < 0)
goto cleanup;
if (object_oid) {
if ((error = git_treebuilder_insert(
&entry, tb, treeentry_name, object_oid, attributes)) < 0)
goto cleanup;
} else {
if ((error = git_treebuilder_remove(tb, treeentry_name)) < 0)
goto cleanup;
}
if ((error = git_treebuilder_write(&tree_oid, tb)) < 0)
goto cleanup;
error = git_tree_lookup(out, repo, &tree_oid);
cleanup:
git_treebuilder_free(tb);
return error;
}
static int manipulate_note_in_tree_r(
git_tree **out,
git_repository *repo,
git_tree *parent,
git_oid *note_oid,
const char *annotated_object_sha,
int fanout,
int (*note_exists_cb)(
git_tree **out,
git_repository *repo,
git_tree *parent,
git_oid *note_oid,
const char *annotated_object_sha,
int fanout,
int current_error),
int (*note_notfound_cb)(
git_tree **out,
git_repository *repo,
git_tree *parent,
git_oid *note_oid,
const char *annotated_object_sha,
int fanout,
int current_error))
{
int error;
git_tree *subtree = NULL, *new = NULL;
char subtree_name[3];
error = find_subtree_in_current_level(
&subtree, repo, parent, annotated_object_sha, fanout);
if (error == GIT_EEXISTS) {
error = note_exists_cb(
out, repo, parent, note_oid, annotated_object_sha, fanout, error);
goto cleanup;
}
if (error == GIT_ENOTFOUND) {
error = note_notfound_cb(
out, repo, parent, note_oid, annotated_object_sha, fanout, error);
goto cleanup;
}
if (error < 0)
goto cleanup;
/* An existing fanout has been found, let's dig deeper */
error = manipulate_note_in_tree_r(
&new, repo, subtree, note_oid, annotated_object_sha,
fanout + 2, note_exists_cb, note_notfound_cb);
if (error < 0)
goto cleanup;
strncpy(subtree_name, annotated_object_sha + fanout, 2);
subtree_name[2] = '\0';
error = tree_write(out, repo, parent, git_tree_id(new),
subtree_name, GIT_FILEMODE_TREE);
cleanup:
git_tree_free(new);
git_tree_free(subtree);
return error;
}
static int remove_note_in_tree_eexists_cb(
git_tree **out,
git_repository *repo,
git_tree *parent,
git_oid *note_oid,
const char *annotated_object_sha,
int fanout,
int current_error)
{
GIT_UNUSED(note_oid);
GIT_UNUSED(current_error);
return tree_write(out, repo, parent, NULL, annotated_object_sha + fanout, 0);
}
static int remove_note_in_tree_enotfound_cb(
git_tree **out,
git_repository *repo,
git_tree *parent,
git_oid *note_oid,
const char *annotated_object_sha,
int fanout,
int current_error)
{
GIT_UNUSED(out);
GIT_UNUSED(repo);
GIT_UNUSED(parent);
GIT_UNUSED(note_oid);
GIT_UNUSED(fanout);
git_error_set(GIT_ERROR_REPOSITORY, "object '%s' has no note", annotated_object_sha);
return current_error;
}
static int insert_note_in_tree_eexists_cb(git_tree **out,
git_repository *repo,
git_tree *parent,
git_oid *note_oid,
const char *annotated_object_sha,
int fanout,
int current_error)
{
GIT_UNUSED(out);
GIT_UNUSED(repo);
GIT_UNUSED(parent);
GIT_UNUSED(note_oid);
GIT_UNUSED(fanout);
git_error_set(GIT_ERROR_REPOSITORY, "note for '%s' exists already", annotated_object_sha);
return current_error;
}
static int insert_note_in_tree_enotfound_cb(git_tree **out,
git_repository *repo,
git_tree *parent,
git_oid *note_oid,
const char *annotated_object_sha,
int fanout,
int current_error)
{
GIT_UNUSED(current_error);
/* No existing fanout at this level, insert in place */
return tree_write(
out,
repo,
parent,
note_oid,
annotated_object_sha + fanout,
GIT_FILEMODE_BLOB);
}
static int note_write(
git_oid *notes_commit_out,
git_oid *notes_blob_out,
git_repository *repo,
const git_signature *author,
const git_signature *committer,
const char *notes_ref,
const char *note,
git_tree *commit_tree,
const char *target,
git_commit **parents,
int allow_note_overwrite)
{
int error;
git_oid oid;
git_tree *tree = NULL;
/* TODO: should we apply filters? */
/* create note object */
if ((error = git_blob_create_from_buffer(&oid, repo, note, strlen(note))) < 0)
goto cleanup;
if ((error = manipulate_note_in_tree_r(
&tree, repo, commit_tree, &oid, target, 0,
allow_note_overwrite ? insert_note_in_tree_enotfound_cb : insert_note_in_tree_eexists_cb,
insert_note_in_tree_enotfound_cb)) < 0)
goto cleanup;
if (notes_blob_out)
git_oid_cpy(notes_blob_out, &oid);
error = git_commit_create(&oid, repo, notes_ref, author, committer,
NULL, GIT_NOTES_DEFAULT_MSG_ADD,
tree, *parents == NULL ? 0 : 1, (const git_commit **) parents);
if (notes_commit_out)
git_oid_cpy(notes_commit_out, &oid);
cleanup:
git_tree_free(tree);
return error;
}
static int note_new(
git_note **out,
git_oid *note_oid,
git_commit *commit,
git_blob *blob)
{
git_note *note = NULL;
git_object_size_t blobsize;
note = git__malloc(sizeof(git_note));
GIT_ERROR_CHECK_ALLOC(note);
git_oid_cpy(¬e->id, note_oid);
if (git_signature_dup(¬e->author, git_commit_author(commit)) < 0 ||
git_signature_dup(¬e->committer, git_commit_committer(commit)) < 0)
return -1;
blobsize = git_blob_rawsize(blob);
GIT_ERROR_CHECK_BLOBSIZE(blobsize);
note->message = git__strndup(git_blob_rawcontent(blob), (size_t)blobsize);
GIT_ERROR_CHECK_ALLOC(note->message);
*out = note;
return 0;
}
static int note_lookup(
git_note **out,
git_repository *repo,
git_commit *commit,
git_tree *tree,
const char *target)
{
int error, fanout = 0;
git_oid oid;
git_blob *blob = NULL;
git_note *note = NULL;
git_tree *subtree = NULL;
if ((error = find_subtree_r(&subtree, tree, repo, target, &fanout)) < 0)
goto cleanup;
if ((error = find_blob(&oid, subtree, target + fanout)) < 0)
goto cleanup;
if ((error = git_blob_lookup(&blob, repo, &oid)) < 0)
goto cleanup;
if ((error = note_new(¬e, &oid, commit, blob)) < 0)
goto cleanup;
*out = note;
cleanup:
git_tree_free(subtree);
git_blob_free(blob);
return error;
}
static int note_remove(
git_oid *notes_commit_out,
git_repository *repo,
const git_signature *author, const git_signature *committer,
const char *notes_ref, git_tree *tree,
const char *target, git_commit **parents)
{
int error;
git_tree *tree_after_removal = NULL;
git_oid oid;
if ((error = manipulate_note_in_tree_r(
&tree_after_removal, repo, tree, NULL, target, 0,
remove_note_in_tree_eexists_cb, remove_note_in_tree_enotfound_cb)) < 0)
goto cleanup;
error = git_commit_create(&oid, repo, notes_ref, author, committer,
NULL, GIT_NOTES_DEFAULT_MSG_RM,
tree_after_removal,
*parents == NULL ? 0 : 1,
(const git_commit **) parents);
if (error < 0)
goto cleanup;
if (notes_commit_out)
git_oid_cpy(notes_commit_out, &oid);
cleanup:
git_tree_free(tree_after_removal);
return error;
}
static int note_get_default_ref(git_buf *out, git_repository *repo)
{
git_config *cfg;
int error;
if ((error = git_repository_config__weakptr(&cfg, repo)) < 0)
return error;
error = git_config_get_string_buf(out, cfg, "core.notesref");
if (error == GIT_ENOTFOUND)
error = git_buf_puts(out, GIT_NOTES_DEFAULT_REF);
return error;
}
static int normalize_namespace(git_buf *out, git_repository *repo, const char *notes_ref)
{
if (notes_ref)
return git_buf_puts(out, notes_ref);
return note_get_default_ref(out, repo);
}
static int retrieve_note_commit(
git_commit **commit_out,
git_buf *notes_ref_out,
git_repository *repo,
const char *notes_ref)
{
int error;
git_oid oid;
if ((error = normalize_namespace(notes_ref_out, repo, notes_ref)) < 0)
return error;
if ((error = git_reference_name_to_id(&oid, repo, notes_ref_out->ptr)) < 0)
return error;
if (git_commit_lookup(commit_out, repo, &oid) < 0)
return error;
return 0;
}
int git_note_commit_read(
git_note **out,
git_repository *repo,
git_commit *notes_commit,
const git_oid *oid)
{
int error;
git_tree *tree = NULL;
char target[GIT_OID_HEXSZ + 1];
git_oid_tostr(target, sizeof(target), oid);
if ((error = git_commit_tree(&tree, notes_commit)) < 0)
goto cleanup;
error = note_lookup(out, repo, notes_commit, tree, target);
cleanup:
git_tree_free(tree);
return error;
}
int git_note_read(git_note **out, git_repository *repo,
const char *notes_ref_in, const git_oid *oid)
{
int error;
git_buf notes_ref = GIT_BUF_INIT;
git_commit *commit = NULL;
error = retrieve_note_commit(&commit, ¬es_ref, repo, notes_ref_in);
if (error < 0)
goto cleanup;
error = git_note_commit_read(out, repo, commit, oid);
cleanup:
git_buf_dispose(¬es_ref);
git_commit_free(commit);
return error;
}
int git_note_commit_create(
git_oid *notes_commit_out,
git_oid *notes_blob_out,
git_repository *repo,
git_commit *parent,
const git_signature *author,
const git_signature *committer,
const git_oid *oid,
const char *note,
int allow_note_overwrite)
{
int error;
git_tree *tree = NULL;
char target[GIT_OID_HEXSZ + 1];
git_oid_tostr(target, sizeof(target), oid);
if (parent != NULL && (error = git_commit_tree(&tree, parent)) < 0)
goto cleanup;
error = note_write(notes_commit_out, notes_blob_out, repo, author,
committer, NULL, note, tree, target, &parent, allow_note_overwrite);
if (error < 0)
goto cleanup;
cleanup:
git_tree_free(tree);
return error;
}
int git_note_create(
git_oid *out,
git_repository *repo,
const char *notes_ref_in,
const git_signature *author,
const git_signature *committer,
const git_oid *oid,
const char *note,
int allow_note_overwrite)
{
int error;
git_buf notes_ref = GIT_BUF_INIT;
git_commit *existing_notes_commit = NULL;
git_reference *ref = NULL;
git_oid notes_blob_oid, notes_commit_oid;
error = retrieve_note_commit(&existing_notes_commit, ¬es_ref,
repo, notes_ref_in);
if (error < 0 && error != GIT_ENOTFOUND)
goto cleanup;
error = git_note_commit_create(¬es_commit_oid,
¬es_blob_oid,
repo, existing_notes_commit, author,
committer, oid, note,
allow_note_overwrite);
if (error < 0)
goto cleanup;
error = git_reference_create(&ref, repo, notes_ref.ptr,
¬es_commit_oid, 1, NULL);
if (out != NULL)
git_oid_cpy(out, ¬es_blob_oid);
cleanup:
git_buf_dispose(¬es_ref);
git_commit_free(existing_notes_commit);
git_reference_free(ref);
return error;
}
int git_note_commit_remove(
git_oid *notes_commit_out,
git_repository *repo,
git_commit *notes_commit,
const git_signature *author,
const git_signature *committer,
const git_oid *oid)
{
int error;
git_tree *tree = NULL;
char target[GIT_OID_HEXSZ + 1];
git_oid_tostr(target, sizeof(target), oid);
if ((error = git_commit_tree(&tree, notes_commit)) < 0)
goto cleanup;
error = note_remove(notes_commit_out,
repo, author, committer, NULL, tree, target, ¬es_commit);
cleanup:
git_tree_free(tree);
return error;
}
int git_note_remove(git_repository *repo, const char *notes_ref_in,
const git_signature *author, const git_signature *committer,
const git_oid *oid)
{
int error;
git_buf notes_ref_target = GIT_BUF_INIT;
git_commit *existing_notes_commit = NULL;
git_oid new_notes_commit;
git_reference *notes_ref = NULL;
error = retrieve_note_commit(&existing_notes_commit, ¬es_ref_target,
repo, notes_ref_in);
if (error < 0)
goto cleanup;
error = git_note_commit_remove(&new_notes_commit, repo,
existing_notes_commit, author, committer, oid);
if (error < 0)
goto cleanup;
error = git_reference_create(¬es_ref, repo, notes_ref_target.ptr,
&new_notes_commit, 1, NULL);
cleanup:
git_buf_dispose(¬es_ref_target);
git_reference_free(notes_ref);
git_commit_free(existing_notes_commit);
return error;
}
int git_note_default_ref(git_buf *out, git_repository *repo)
{
int error;
GIT_ASSERT_ARG(out);
GIT_ASSERT_ARG(repo);
if ((error = git_buf_sanitize(out)) < 0 ||
(error = note_get_default_ref(out, repo)) < 0)
git_buf_dispose(out);
return error;
}
const git_signature *git_note_committer(const git_note *note)
{
GIT_ASSERT_ARG_WITH_RETVAL(note, NULL);
return note->committer;
}
const git_signature *git_note_author(const git_note *note)
{
GIT_ASSERT_ARG_WITH_RETVAL(note, NULL);
return note->author;
}
const char *git_note_message(const git_note *note)
{
GIT_ASSERT_ARG_WITH_RETVAL(note, NULL);
return note->message;
}
const git_oid *git_note_id(const git_note *note)
{
GIT_ASSERT_ARG_WITH_RETVAL(note, NULL);
return ¬e->id;
}
void git_note_free(git_note *note)
{
if (note == NULL)
return;
git_signature_free(note->committer);
git_signature_free(note->author);
git__free(note->message);
git__free(note);
}
static int process_entry_path(
const char *entry_path,
git_oid *annotated_object_id)
{
int error = 0;
size_t i = 0, j = 0, len;
git_buf buf = GIT_BUF_INIT;
if ((error = git_buf_puts(&buf, entry_path)) < 0)
goto cleanup;
len = git_buf_len(&buf);
while (i < len) {
if (buf.ptr[i] == '/') {
i++;
continue;
}
if (git__fromhex(buf.ptr[i]) < 0) {
/* This is not a note entry */
goto cleanup;
}
if (i != j)
buf.ptr[j] = buf.ptr[i];
i++;
j++;
}
buf.ptr[j] = '\0';
buf.size = j;
if (j != GIT_OID_HEXSZ) {
/* This is not a note entry */
goto cleanup;
}
error = git_oid_fromstr(annotated_object_id, buf.ptr);
cleanup:
git_buf_dispose(&buf);
return error;
}
int git_note_foreach(
git_repository *repo,
const char *notes_ref,
git_note_foreach_cb note_cb,
void *payload)
{
int error;
git_note_iterator *iter = NULL;
git_oid note_id, annotated_id;
if ((error = git_note_iterator_new(&iter, repo, notes_ref)) < 0)
return error;
while (!(error = git_note_next(¬e_id, &annotated_id, iter))) {
if ((error = note_cb(¬e_id, &annotated_id, payload)) != 0) {
git_error_set_after_callback(error);
break;
}
}
if (error == GIT_ITEROVER)
error = 0;
git_note_iterator_free(iter);
return error;
}
void git_note_iterator_free(git_note_iterator *it)
{
if (it == NULL)
return;
git_iterator_free(it);
}
int git_note_commit_iterator_new(
git_note_iterator **it,
git_commit *notes_commit)
{
int error;
git_tree *tree;
if ((error = git_commit_tree(&tree, notes_commit)) < 0)
goto cleanup;
if ((error = git_iterator_for_tree(it, tree, NULL)) < 0)
git_iterator_free(*it);
cleanup:
git_tree_free(tree);
return error;
}
int git_note_iterator_new(
git_note_iterator **it,
git_repository *repo,
const char *notes_ref_in)
{
int error;
git_commit *commit = NULL;
git_buf notes_ref = GIT_BUF_INIT;
error = retrieve_note_commit(&commit, ¬es_ref, repo, notes_ref_in);
if (error < 0)
goto cleanup;
error = git_note_commit_iterator_new(it, commit);
cleanup:
git_buf_dispose(¬es_ref);
git_commit_free(commit);
return error;
}
int git_note_next(
git_oid *note_id,
git_oid *annotated_id,
git_note_iterator *it)
{
int error;
const git_index_entry *item;
if ((error = git_iterator_current(&item, it)) < 0)
return error;
git_oid_cpy(note_id, &item->id);
if ((error = process_entry_path(item->path, annotated_id)) < 0)
return error;
if ((error = git_iterator_advance(NULL, it)) < 0 && error != GIT_ITEROVER)
return error;
return 0;
}
|
0 |
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2
|
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2/src/regexp.c
|
/*
* Copyright (C) the libgit2 contributors. All rights reserved.
*
* This file is part of libgit2, distributed under the GNU GPL v2 with
* a Linking Exception. For full terms see the included COPYING file.
*/
#include "regexp.h"
#if defined(GIT_REGEX_BUILTIN) || defined(GIT_REGEX_PCRE)
int git_regexp_compile(git_regexp *r, const char *pattern, int flags)
{
int erroffset, cflags = 0;
const char *error = NULL;
if (flags & GIT_REGEXP_ICASE)
cflags |= PCRE_CASELESS;
if ((*r = pcre_compile(pattern, cflags, &error, &erroffset, NULL)) == NULL) {
git_error_set_str(GIT_ERROR_REGEX, error);
return GIT_EINVALIDSPEC;
}
return 0;
}
void git_regexp_dispose(git_regexp *r)
{
pcre_free(*r);
*r = NULL;
}
int git_regexp_match(const git_regexp *r, const char *string)
{
int error;
if ((error = pcre_exec(*r, NULL, string, (int) strlen(string), 0, 0, NULL, 0)) < 0)
return (error == PCRE_ERROR_NOMATCH) ? GIT_ENOTFOUND : GIT_EINVALIDSPEC;
return 0;
}
int git_regexp_search(const git_regexp *r, const char *string, size_t nmatches, git_regmatch *matches)
{
int static_ovec[9] = {0}, *ovec;
int error;
size_t i;
/* The ovec array always needs to be a mutiple of three */
if (nmatches <= ARRAY_SIZE(static_ovec) / 3)
ovec = static_ovec;
else
ovec = git__calloc(nmatches * 3, sizeof(*ovec));
GIT_ERROR_CHECK_ALLOC(ovec);
if ((error = pcre_exec(*r, NULL, string, (int) strlen(string), 0, 0, ovec, (int) nmatches * 3)) < 0)
goto out;
if (error == 0)
error = (int) nmatches;
for (i = 0; i < (unsigned int) error; i++) {
matches[i].start = (ovec[i * 2] < 0) ? -1 : ovec[i * 2];
matches[i].end = (ovec[i * 2 + 1] < 0) ? -1 : ovec[i * 2 + 1];
}
for (i = (unsigned int) error; i < nmatches; i++)
matches[i].start = matches[i].end = -1;
out:
if (nmatches > ARRAY_SIZE(static_ovec) / 3)
git__free(ovec);
if (error < 0)
return (error == PCRE_ERROR_NOMATCH) ? GIT_ENOTFOUND : GIT_EINVALIDSPEC;
return 0;
}
#elif defined(GIT_REGEX_PCRE2)
int git_regexp_compile(git_regexp *r, const char *pattern, int flags)
{
unsigned char errmsg[1024];
PCRE2_SIZE erroff;
int error, cflags = 0;
if (flags & GIT_REGEXP_ICASE)
cflags |= PCRE2_CASELESS;
if ((*r = pcre2_compile((const unsigned char *) pattern, PCRE2_ZERO_TERMINATED,
cflags, &error, &erroff, NULL)) == NULL) {
pcre2_get_error_message(error, errmsg, sizeof(errmsg));
git_error_set_str(GIT_ERROR_REGEX, (char *) errmsg);
return GIT_EINVALIDSPEC;
}
return 0;
}
void git_regexp_dispose(git_regexp *r)
{
pcre2_code_free(*r);
*r = NULL;
}
int git_regexp_match(const git_regexp *r, const char *string)
{
pcre2_match_data *data;
int error;
data = pcre2_match_data_create(1, NULL);
GIT_ERROR_CHECK_ALLOC(data);
if ((error = pcre2_match(*r, (const unsigned char *) string, strlen(string),
0, 0, data, NULL)) < 0)
return (error == PCRE2_ERROR_NOMATCH) ? GIT_ENOTFOUND : GIT_EINVALIDSPEC;
pcre2_match_data_free(data);
return 0;
}
int git_regexp_search(const git_regexp *r, const char *string, size_t nmatches, git_regmatch *matches)
{
pcre2_match_data *data = NULL;
PCRE2_SIZE *ovec;
int error;
size_t i;
if ((data = pcre2_match_data_create(nmatches, NULL)) == NULL) {
git_error_set_oom();
goto out;
}
if ((error = pcre2_match(*r, (const unsigned char *) string, strlen(string),
0, 0, data, NULL)) < 0)
goto out;
if (error == 0 || (unsigned int) error > nmatches)
error = nmatches;
ovec = pcre2_get_ovector_pointer(data);
for (i = 0; i < (unsigned int) error; i++) {
matches[i].start = (ovec[i * 2] == PCRE2_UNSET) ? -1 : (ssize_t) ovec[i * 2];
matches[i].end = (ovec[i * 2 + 1] == PCRE2_UNSET) ? -1 : (ssize_t) ovec[i * 2 + 1];
}
for (i = (unsigned int) error; i < nmatches; i++)
matches[i].start = matches[i].end = -1;
out:
pcre2_match_data_free(data);
if (error < 0)
return (error == PCRE2_ERROR_NOMATCH) ? GIT_ENOTFOUND : GIT_EINVALIDSPEC;
return 0;
}
#elif defined(GIT_REGEX_REGCOMP) || defined(GIT_REGEX_REGCOMP_L)
#if defined(GIT_REGEX_REGCOMP_L)
# include <xlocale.h>
#endif
int git_regexp_compile(git_regexp *r, const char *pattern, int flags)
{
int cflags = REG_EXTENDED, error;
char errmsg[1024];
if (flags & GIT_REGEXP_ICASE)
cflags |= REG_ICASE;
# if defined(GIT_REGEX_REGCOMP)
if ((error = regcomp(r, pattern, cflags)) != 0)
# else
if ((error = regcomp_l(r, pattern, cflags, (locale_t) 0)) != 0)
# endif
{
regerror(error, r, errmsg, sizeof(errmsg));
git_error_set_str(GIT_ERROR_REGEX, errmsg);
return GIT_EINVALIDSPEC;
}
return 0;
}
void git_regexp_dispose(git_regexp *r)
{
regfree(r);
}
int git_regexp_match(const git_regexp *r, const char *string)
{
int error;
if ((error = regexec(r, string, 0, NULL, 0)) != 0)
return (error == REG_NOMATCH) ? GIT_ENOTFOUND : GIT_EINVALIDSPEC;
return 0;
}
int git_regexp_search(const git_regexp *r, const char *string, size_t nmatches, git_regmatch *matches)
{
regmatch_t static_m[3], *m;
int error;
size_t i;
if (nmatches <= ARRAY_SIZE(static_m))
m = static_m;
else
m = git__calloc(nmatches, sizeof(*m));
if ((error = regexec(r, string, nmatches, m, 0)) != 0)
goto out;
for (i = 0; i < nmatches; i++) {
matches[i].start = (m[i].rm_so < 0) ? -1 : m[i].rm_so;
matches[i].end = (m[i].rm_eo < 0) ? -1 : m[i].rm_eo;
}
out:
if (nmatches > ARRAY_SIZE(static_m))
git__free(m);
if (error)
return (error == REG_NOMATCH) ? GIT_ENOTFOUND : GIT_EINVALIDSPEC;
return 0;
}
#endif
|
0 |
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2
|
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2/src/mwindow.h
|
/*
* Copyright (C) the libgit2 contributors. All rights reserved.
*
* This file is part of libgit2, distributed under the GNU GPL v2 with
* a Linking Exception. For full terms see the included COPYING file.
*/
#ifndef INCLUDE_mwindow__
#define INCLUDE_mwindow__
#include "common.h"
#include "map.h"
#include "vector.h"
typedef struct git_mwindow {
struct git_mwindow *next;
git_map window_map;
off64_t offset;
size_t last_used;
size_t inuse_cnt;
} git_mwindow;
typedef struct git_mwindow_file {
git_mutex lock; /* protects updates to fd */
git_mwindow *windows;
int fd;
off64_t size;
} git_mwindow_file;
typedef struct git_mwindow_ctl {
size_t mapped;
unsigned int open_windows;
unsigned int mmap_calls;
unsigned int peak_open_windows;
size_t peak_mapped;
size_t used_ctr;
git_vector windowfiles;
} git_mwindow_ctl;
int git_mwindow_contains(git_mwindow *win, off64_t offset);
int git_mwindow_free_all(git_mwindow_file *mwf); /* locks */
unsigned char *git_mwindow_open(git_mwindow_file *mwf, git_mwindow **cursor, off64_t offset, size_t extra, unsigned int *left);
int git_mwindow_file_register(git_mwindow_file *mwf);
void git_mwindow_file_deregister(git_mwindow_file *mwf);
void git_mwindow_close(git_mwindow **w_cursor);
extern int git_mwindow_global_init(void);
struct git_pack_file; /* just declaration to avoid cyclical includes */
int git_mwindow_get_pack(struct git_pack_file **out, const char *path);
int git_mwindow_put_pack(struct git_pack_file *pack);
#endif
|
0 |
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2
|
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2/src/zstream.h
|
/*
* Copyright (C) the libgit2 contributors. All rights reserved.
*
* This file is part of libgit2, distributed under the GNU GPL v2 with
* a Linking Exception. For full terms see the included COPYING file.
*/
#ifndef INCLUDE_zstream_h__
#define INCLUDE_zstream_h__
#include "common.h"
#include <zlib.h>
#include "buffer.h"
typedef enum {
GIT_ZSTREAM_INFLATE,
GIT_ZSTREAM_DEFLATE,
} git_zstream_t;
typedef struct {
z_stream z;
git_zstream_t type;
const char *in;
size_t in_len;
int flush;
int zerr;
} git_zstream;
#define GIT_ZSTREAM_INIT {{0}}
int git_zstream_init(git_zstream *zstream, git_zstream_t type);
void git_zstream_free(git_zstream *zstream);
int git_zstream_set_input(git_zstream *zstream, const void *in, size_t in_len);
size_t git_zstream_suggest_output_len(git_zstream *zstream);
/* get as much output as is available in the input buffer */
int git_zstream_get_output_chunk(
void *out, size_t *out_len, git_zstream *zstream);
/* get all the output from the entire input buffer */
int git_zstream_get_output(void *out, size_t *out_len, git_zstream *zstream);
bool git_zstream_done(git_zstream *zstream);
bool git_zstream_eos(git_zstream *zstream);
void git_zstream_reset(git_zstream *zstream);
int git_zstream_deflatebuf(git_buf *out, const void *in, size_t in_len);
int git_zstream_inflatebuf(git_buf *out, const void *in, size_t in_len);
#endif
|
0 |
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2
|
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2/src/posix.h
|
/*
* Copyright (C) the libgit2 contributors. All rights reserved.
*
* This file is part of libgit2, distributed under the GNU GPL v2 with
* a Linking Exception. For full terms see the included COPYING file.
*/
#ifndef INCLUDE_posix_h__
#define INCLUDE_posix_h__
#include "common.h"
#include <fcntl.h>
#include <time.h>
/* stat: file mode type testing macros */
#ifndef S_IFGITLINK
#define S_IFGITLINK 0160000
#define S_ISGITLINK(m) (((m) & S_IFMT) == S_IFGITLINK)
#endif
#ifndef S_IFLNK
#define S_IFLNK 0120000
#undef _S_IFLNK
#define _S_IFLNK S_IFLNK
#endif
#ifndef S_IWUSR
#define S_IWUSR 00200
#endif
#ifndef S_IXUSR
#define S_IXUSR 00100
#endif
#ifndef S_ISLNK
#define S_ISLNK(m) (((m) & _S_IFMT) == _S_IFLNK)
#endif
#ifndef S_ISDIR
#define S_ISDIR(m) (((m) & _S_IFMT) == _S_IFDIR)
#endif
#ifndef S_ISREG
#define S_ISREG(m) (((m) & _S_IFMT) == _S_IFREG)
#endif
#ifndef S_ISFIFO
#define S_ISFIFO(m) (((m) & _S_IFMT) == _S_IFIFO)
#endif
/* if S_ISGID is not defined, then don't try to set it */
#ifndef S_ISGID
#define S_ISGID 0
#endif
#ifndef O_BINARY
#define O_BINARY 0
#endif
#ifndef O_CLOEXEC
#define O_CLOEXEC 0
#endif
#ifndef SOCK_CLOEXEC
#define SOCK_CLOEXEC 0
#endif
/* access() mode parameter #defines */
#ifndef F_OK
#define F_OK 0 /* existence check */
#endif
#ifndef W_OK
#define W_OK 2 /* write mode check */
#endif
#ifndef R_OK
#define R_OK 4 /* read mode check */
#endif
/* Determine whether an errno value indicates that a read or write failed
* because the descriptor is blocked.
*/
#if defined(EWOULDBLOCK)
#define GIT_ISBLOCKED(e) ((e) == EAGAIN || (e) == EWOULDBLOCK)
#else
#define GIT_ISBLOCKED(e) ((e) == EAGAIN)
#endif
/* define some standard errnos that the runtime may be missing. for example,
* mingw lacks EAFNOSUPPORT. */
#ifndef EAFNOSUPPORT
#define EAFNOSUPPORT (INT_MAX-1)
#endif
/* Compiler independent macro to handle signal interrpted system calls */
#define HANDLE_EINTR(result, x) do { \
result = (x); \
} while (result == -1 && errno == EINTR);
/* Provide a 64-bit size for offsets. */
#if defined(_MSC_VER)
typedef __int64 off64_t;
#elif defined(__HAIKU__)
typedef __haiku_std_int64 off64_t;
#elif defined(__APPLE__)
typedef __int64_t off64_t;
#else
typedef int64_t off64_t;
#endif
typedef int git_file;
/**
* Standard POSIX Methods
*
* All the methods starting with the `p_` prefix are
* direct ports of the standard POSIX methods.
*
* Some of the methods are slightly wrapped to provide
* saner defaults. Some of these methods are emulated
* in Windows platforms.
*
* Use your manpages to check the docs on these.
*/
extern ssize_t p_read(git_file fd, void *buf, size_t cnt);
extern int p_write(git_file fd, const void *buf, size_t cnt);
extern ssize_t p_pread(int fd, void *data, size_t size, off64_t offset);
extern ssize_t p_pwrite(int fd, const void *data, size_t size, off64_t offset);
#define p_close(fd) close(fd)
#define p_umask(m) umask(m)
extern int p_open(const char *path, int flags, ...);
extern int p_creat(const char *path, mode_t mode);
extern int p_getcwd(char *buffer_out, size_t size);
extern int p_rename(const char *from, const char *to);
extern int git__page_size(size_t *page_size);
extern int git__mmap_alignment(size_t *page_size);
/* The number of times `p_fsync` has been called. Note that this is for
* test code only; it it not necessarily thread-safe and should not be
* relied upon in production.
*/
extern size_t p_fsync__cnt;
/**
* Platform-dependent methods
*/
#ifdef GIT_WIN32
# include "win32/posix.h"
#else
# include "unix/posix.h"
#endif
#include "strnlen.h"
#ifdef NO_READDIR_R
GIT_INLINE(int) p_readdir_r(DIR *dirp, struct dirent *entry, struct dirent **result)
{
GIT_UNUSED(entry);
*result = readdir(dirp);
return 0;
}
#else /* NO_READDIR_R */
# define p_readdir_r(d,e,r) readdir_r(d,e,r)
#endif
#ifdef NO_ADDRINFO
# include <netdb.h>
struct addrinfo {
struct hostent *ai_hostent;
struct servent *ai_servent;
struct sockaddr_in ai_addr_in;
struct sockaddr *ai_addr;
size_t ai_addrlen;
int ai_family;
int ai_socktype;
int ai_protocol;
long ai_port;
struct addrinfo *ai_next;
};
extern int p_getaddrinfo(const char *host, const char *port,
struct addrinfo *hints, struct addrinfo **info);
extern void p_freeaddrinfo(struct addrinfo *info);
extern const char *p_gai_strerror(int ret);
#else
# define p_getaddrinfo(a, b, c, d) getaddrinfo(a, b, c, d)
# define p_freeaddrinfo(a) freeaddrinfo(a)
# define p_gai_strerror(c) gai_strerror(c)
#endif /* NO_ADDRINFO */
#endif
|
0 |
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2
|
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2/src/commit_list.h
|
/*
* Copyright (C) the libgit2 contributors. All rights reserved.
*
* This file is part of libgit2, distributed under the GNU GPL v2 with
* a Linking Exception. For full terms see the included COPYING file.
*/
#ifndef INCLUDE_commit_list_h__
#define INCLUDE_commit_list_h__
#include "common.h"
#include "git2/oid.h"
#define PARENT1 (1 << 0)
#define PARENT2 (1 << 1)
#define RESULT (1 << 2)
#define STALE (1 << 3)
#define ALL_FLAGS (PARENT1 | PARENT2 | STALE | RESULT)
#define PARENTS_PER_COMMIT 2
#define COMMIT_ALLOC \
(sizeof(git_commit_list_node) + PARENTS_PER_COMMIT * sizeof(git_commit_list_node *))
#define FLAG_BITS 4
typedef struct git_commit_list_node {
git_oid oid;
int64_t time;
uint32_t generation;
unsigned int seen:1,
uninteresting:1,
topo_delay:1,
parsed:1,
added:1,
flags : FLAG_BITS;
uint16_t in_degree;
uint16_t out_degree;
struct git_commit_list_node **parents;
} git_commit_list_node;
typedef struct git_commit_list {
git_commit_list_node *item;
struct git_commit_list *next;
} git_commit_list;
git_commit_list_node *git_commit_list_alloc_node(git_revwalk *walk);
int git_commit_list_generation_cmp(const void *a, const void *b);
int git_commit_list_time_cmp(const void *a, const void *b);
void git_commit_list_free(git_commit_list **list_p);
git_commit_list *git_commit_list_insert(git_commit_list_node *item, git_commit_list **list_p);
git_commit_list *git_commit_list_insert_by_date(git_commit_list_node *item, git_commit_list **list_p);
int git_commit_list_parse(git_revwalk *walk, git_commit_list_node *commit);
git_commit_list_node *git_commit_list_pop(git_commit_list **stack);
#endif
|
0 |
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2
|
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2/src/revert.c
|
/*
* Copyright (C) the libgit2 contributors. All rights reserved.
*
* This file is part of libgit2, distributed under the GNU GPL v2 with
* a Linking Exception. For full terms see the included COPYING file.
*/
#include "common.h"
#include "repository.h"
#include "filebuf.h"
#include "merge.h"
#include "index.h"
#include "git2/types.h"
#include "git2/merge.h"
#include "git2/revert.h"
#include "git2/commit.h"
#include "git2/sys/commit.h"
#define GIT_REVERT_FILE_MODE 0666
static int write_revert_head(
git_repository *repo,
const char *commit_oidstr)
{
git_filebuf file = GIT_FILEBUF_INIT;
git_buf file_path = GIT_BUF_INIT;
int error = 0;
if ((error = git_buf_joinpath(&file_path, repo->gitdir, GIT_REVERT_HEAD_FILE)) >= 0 &&
(error = git_filebuf_open(&file, file_path.ptr, GIT_FILEBUF_CREATE_LEADING_DIRS, GIT_REVERT_FILE_MODE)) >= 0 &&
(error = git_filebuf_printf(&file, "%s\n", commit_oidstr)) >= 0)
error = git_filebuf_commit(&file);
if (error < 0)
git_filebuf_cleanup(&file);
git_buf_dispose(&file_path);
return error;
}
static int write_merge_msg(
git_repository *repo,
const char *commit_oidstr,
const char *commit_msgline)
{
git_filebuf file = GIT_FILEBUF_INIT;
git_buf file_path = GIT_BUF_INIT;
int error = 0;
if ((error = git_buf_joinpath(&file_path, repo->gitdir, GIT_MERGE_MSG_FILE)) < 0 ||
(error = git_filebuf_open(&file, file_path.ptr, GIT_FILEBUF_CREATE_LEADING_DIRS, GIT_REVERT_FILE_MODE)) < 0 ||
(error = git_filebuf_printf(&file, "Revert \"%s\"\n\nThis reverts commit %s.\n",
commit_msgline, commit_oidstr)) < 0)
goto cleanup;
error = git_filebuf_commit(&file);
cleanup:
if (error < 0)
git_filebuf_cleanup(&file);
git_buf_dispose(&file_path);
return error;
}
static int revert_normalize_opts(
git_repository *repo,
git_revert_options *opts,
const git_revert_options *given,
const char *their_label)
{
int error = 0;
unsigned int default_checkout_strategy = GIT_CHECKOUT_SAFE |
GIT_CHECKOUT_ALLOW_CONFLICTS;
GIT_UNUSED(repo);
if (given != NULL)
memcpy(opts, given, sizeof(git_revert_options));
else {
git_revert_options default_opts = GIT_REVERT_OPTIONS_INIT;
memcpy(opts, &default_opts, sizeof(git_revert_options));
}
if (!opts->checkout_opts.checkout_strategy)
opts->checkout_opts.checkout_strategy = default_checkout_strategy;
if (!opts->checkout_opts.our_label)
opts->checkout_opts.our_label = "HEAD";
if (!opts->checkout_opts.their_label)
opts->checkout_opts.their_label = their_label;
return error;
}
static int revert_state_cleanup(git_repository *repo)
{
const char *state_files[] = { GIT_REVERT_HEAD_FILE, GIT_MERGE_MSG_FILE };
return git_repository__cleanup_files(repo, state_files, ARRAY_SIZE(state_files));
}
static int revert_seterr(git_commit *commit, const char *fmt)
{
char commit_oidstr[GIT_OID_HEXSZ + 1];
git_oid_fmt(commit_oidstr, git_commit_id(commit));
commit_oidstr[GIT_OID_HEXSZ] = '\0';
git_error_set(GIT_ERROR_REVERT, fmt, commit_oidstr);
return -1;
}
int git_revert_commit(
git_index **out,
git_repository *repo,
git_commit *revert_commit,
git_commit *our_commit,
unsigned int mainline,
const git_merge_options *merge_opts)
{
git_commit *parent_commit = NULL;
git_tree *parent_tree = NULL, *our_tree = NULL, *revert_tree = NULL;
int parent = 0, error = 0;
GIT_ASSERT_ARG(out);
GIT_ASSERT_ARG(repo);
GIT_ASSERT_ARG(revert_commit);
GIT_ASSERT_ARG(our_commit);
if (git_commit_parentcount(revert_commit) > 1) {
if (!mainline)
return revert_seterr(revert_commit,
"mainline branch is not specified but %s is a merge commit");
parent = mainline;
} else {
if (mainline)
return revert_seterr(revert_commit,
"mainline branch specified but %s is not a merge commit");
parent = git_commit_parentcount(revert_commit);
}
if (parent &&
((error = git_commit_parent(&parent_commit, revert_commit, (parent - 1))) < 0 ||
(error = git_commit_tree(&parent_tree, parent_commit)) < 0))
goto done;
if ((error = git_commit_tree(&revert_tree, revert_commit)) < 0 ||
(error = git_commit_tree(&our_tree, our_commit)) < 0)
goto done;
error = git_merge_trees(out, repo, revert_tree, our_tree, parent_tree, merge_opts);
done:
git_tree_free(parent_tree);
git_tree_free(our_tree);
git_tree_free(revert_tree);
git_commit_free(parent_commit);
return error;
}
int git_revert(
git_repository *repo,
git_commit *commit,
const git_revert_options *given_opts)
{
git_revert_options opts;
git_reference *our_ref = NULL;
git_commit *our_commit = NULL;
char commit_oidstr[GIT_OID_HEXSZ + 1];
const char *commit_msg;
git_buf their_label = GIT_BUF_INIT;
git_index *index = NULL;
git_indexwriter indexwriter = GIT_INDEXWRITER_INIT;
int error;
GIT_ASSERT_ARG(repo);
GIT_ASSERT_ARG(commit);
GIT_ERROR_CHECK_VERSION(given_opts, GIT_REVERT_OPTIONS_VERSION, "git_revert_options");
if ((error = git_repository__ensure_not_bare(repo, "revert")) < 0)
return error;
git_oid_fmt(commit_oidstr, git_commit_id(commit));
commit_oidstr[GIT_OID_HEXSZ] = '\0';
if ((commit_msg = git_commit_summary(commit)) == NULL) {
error = -1;
goto on_error;
}
if ((error = git_buf_printf(&their_label, "parent of %.7s... %s", commit_oidstr, commit_msg)) < 0 ||
(error = revert_normalize_opts(repo, &opts, given_opts, git_buf_cstr(&their_label))) < 0 ||
(error = git_indexwriter_init_for_operation(&indexwriter, repo, &opts.checkout_opts.checkout_strategy)) < 0 ||
(error = write_revert_head(repo, commit_oidstr)) < 0 ||
(error = write_merge_msg(repo, commit_oidstr, commit_msg)) < 0 ||
(error = git_repository_head(&our_ref, repo)) < 0 ||
(error = git_reference_peel((git_object **)&our_commit, our_ref, GIT_OBJECT_COMMIT)) < 0 ||
(error = git_revert_commit(&index, repo, commit, our_commit, opts.mainline, &opts.merge_opts)) < 0 ||
(error = git_merge__check_result(repo, index)) < 0 ||
(error = git_merge__append_conflicts_to_merge_msg(repo, index)) < 0 ||
(error = git_checkout_index(repo, index, &opts.checkout_opts)) < 0 ||
(error = git_indexwriter_commit(&indexwriter)) < 0)
goto on_error;
goto done;
on_error:
revert_state_cleanup(repo);
done:
git_indexwriter_cleanup(&indexwriter);
git_index_free(index);
git_commit_free(our_commit);
git_reference_free(our_ref);
git_buf_dispose(&their_label);
return error;
}
int git_revert_options_init(git_revert_options *opts, unsigned int version)
{
GIT_INIT_STRUCTURE_FROM_TEMPLATE(
opts, version, git_revert_options, GIT_REVERT_OPTIONS_INIT);
return 0;
}
#ifndef GIT_DEPRECATE_HARD
int git_revert_init_options(git_revert_options *opts, unsigned int version)
{
return git_revert_options_init(opts, version);
}
#endif
|
0 |
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2
|
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2/src/worktree.h
|
/*
* Copyright (C) the libgit2 contributors. All rights reserved.
*
* This file is part of libgit2, distributed under the GNU GPL v2 with
* a Linking Exception. For full terms see the included COPYING file.
*/
#ifndef INCLUDE_worktree_h__
#define INCLUDE_worktree_h__
#include "common.h"
#include "git2/common.h"
#include "git2/worktree.h"
struct git_worktree {
/* Name of the working tree. This is the name of the
* containing directory in the `$PARENT/.git/worktrees/`
* directory. */
char *name;
/* Path to the where the worktree lives in the filesystem */
char *worktree_path;
/* Path to the .git file in the working tree's repository */
char *gitlink_path;
/* Path to the .git directory inside the parent's
* worktrees directory */
char *gitdir_path;
/* Path to the common directory contained in the parent
* repository */
char *commondir_path;
/* Path to the parent's working directory */
char *parent_path;
int locked:1;
};
char *git_worktree__read_link(const char *base, const char *file);
#endif
|
0 |
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2
|
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2/src/khash.h
|
/* The MIT License
Copyright (c) 2008, 2009, 2011 by Attractive Chaos <[email protected]>
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
/*
An example:
#include "khash.h"
KHASH_MAP_INIT_INT(32, char)
int main() {
int ret, is_missing;
khiter_t k;
khash_t(32) *h = kh_init(32);
k = kh_put(32, h, 5, &ret);
kh_value(h, k) = 10;
k = kh_get(32, h, 10);
is_missing = (k == kh_end(h));
k = kh_get(32, h, 5);
kh_del(32, h, k);
for (k = kh_begin(h); k != kh_end(h); ++k)
if (kh_exist(h, k)) kh_value(h, k) = 1;
kh_destroy(32, h);
return 0;
}
*/
/*
2013-05-02 (0.2.8):
* Use quadratic probing. When the capacity is power of 2, stepping function
i*(i+1)/2 guarantees to traverse each bucket. It is better than double
hashing on cache performance and is more robust than linear probing.
In theory, double hashing should be more robust than quadratic probing.
However, my implementation is probably not for large hash tables, because
the second hash function is closely tied to the first hash function,
which reduce the effectiveness of double hashing.
Reference: http://research.cs.vt.edu/AVresearch/hashing/quadratic.php
2011-12-29 (0.2.7):
* Minor code clean up; no actual effect.
2011-09-16 (0.2.6):
* The capacity is a power of 2. This seems to dramatically improve the
speed for simple keys. Thank Zilong Tan for the suggestion. Reference:
- http://code.google.com/p/ulib/
- http://nothings.org/computer/judy/
* Allow to optionally use linear probing which usually has better
performance for random input. Double hashing is still the default as it
is more robust to certain non-random input.
* Added Wang's integer hash function (not used by default). This hash
function is more robust to certain non-random input.
2011-02-14 (0.2.5):
* Allow to declare global functions.
2009-09-26 (0.2.4):
* Improve portability
2008-09-19 (0.2.3):
* Corrected the example
* Improved interfaces
2008-09-11 (0.2.2):
* Improved speed a little in kh_put()
2008-09-10 (0.2.1):
* Added kh_clear()
* Fixed a compiling error
2008-09-02 (0.2.0):
* Changed to token concatenation which increases flexibility.
2008-08-31 (0.1.2):
* Fixed a bug in kh_get(), which has not been tested previously.
2008-08-31 (0.1.1):
* Added destructor
*/
#ifndef __AC_KHASH_H
#define __AC_KHASH_H
/*!
@header
Generic hash table library.
*/
#define AC_VERSION_KHASH_H "0.2.8"
#include <stdlib.h>
#include <string.h>
#include <limits.h>
/* compiler specific configuration */
typedef uint32_t khint32_t;
typedef uint64_t khint64_t;
#ifndef kh_inline
#ifdef _MSC_VER
#define kh_inline __inline
#elif defined(__GNUC__)
#define kh_inline __inline__
#else
#define kh_inline
#endif
#endif /* kh_inline */
typedef khint32_t khint_t;
typedef khint_t khiter_t;
#define __ac_isempty(flag, i) ((flag[i>>4]>>((i&0xfU)<<1))&2)
#define __ac_isdel(flag, i) ((flag[i>>4]>>((i&0xfU)<<1))&1)
#define __ac_iseither(flag, i) ((flag[i>>4]>>((i&0xfU)<<1))&3)
#define __ac_set_isdel_false(flag, i) (flag[i>>4]&=~(1ul<<((i&0xfU)<<1)))
#define __ac_set_isempty_false(flag, i) (flag[i>>4]&=~(2ul<<((i&0xfU)<<1)))
#define __ac_set_isboth_false(flag, i) (flag[i>>4]&=~(3ul<<((i&0xfU)<<1)))
#define __ac_set_isdel_true(flag, i) (flag[i>>4]|=1ul<<((i&0xfU)<<1))
#define __ac_fsize(m) ((m) < 16? 1 : (m)>>4)
#ifndef kroundup32
#define kroundup32(x) (--(x), (x)|=(x)>>1, (x)|=(x)>>2, (x)|=(x)>>4, (x)|=(x)>>8, (x)|=(x)>>16, ++(x))
#endif
#ifndef kcalloc
#define kcalloc(N,Z) calloc(N,Z)
#endif
#ifndef kmalloc
#define kmalloc(Z) malloc(Z)
#endif
#ifndef krealloc
#define krealloc(P,Z) realloc(P,Z)
#endif
#ifndef kreallocarray
#define kreallocarray(P,N,Z) ((SIZE_MAX - N < Z) ? NULL : krealloc(P, (N*Z)))
#endif
#ifndef kfree
#define kfree(P) free(P)
#endif
static const double __ac_HASH_UPPER = 0.77;
#define __KHASH_TYPE(name, khkey_t, khval_t) \
typedef struct kh_##name##_s { \
khint_t n_buckets, size, n_occupied, upper_bound; \
khint32_t *flags; \
khkey_t *keys; \
khval_t *vals; \
} kh_##name##_t;
#define __KHASH_PROTOTYPES(name, khkey_t, khval_t) \
extern kh_##name##_t *kh_init_##name(void); \
extern void kh_destroy_##name(kh_##name##_t *h); \
extern void kh_clear_##name(kh_##name##_t *h); \
extern khint_t kh_get_##name(const kh_##name##_t *h, khkey_t key); \
extern int kh_resize_##name(kh_##name##_t *h, khint_t new_n_buckets); \
extern khint_t kh_put_##name(kh_##name##_t *h, khkey_t key, int *ret); \
extern void kh_del_##name(kh_##name##_t *h, khint_t x);
#define __KHASH_IMPL(name, SCOPE, khkey_t, khval_t, kh_is_map, __hash_func, __hash_equal) \
SCOPE kh_##name##_t *kh_init_##name(void) { \
return (kh_##name##_t*)kcalloc(1, sizeof(kh_##name##_t)); \
} \
SCOPE void kh_destroy_##name(kh_##name##_t *h) \
{ \
if (h) { \
kfree((void *)h->keys); kfree(h->flags); \
kfree((void *)h->vals); \
kfree(h); \
} \
} \
SCOPE void kh_clear_##name(kh_##name##_t *h) \
{ \
if (h && h->flags) { \
memset(h->flags, 0xaa, __ac_fsize(h->n_buckets) * sizeof(khint32_t)); \
h->size = h->n_occupied = 0; \
} \
} \
SCOPE khint_t kh_get_##name(const kh_##name##_t *h, khkey_t key) \
{ \
if (h->n_buckets) { \
khint_t k, i, last, mask, step = 0; \
mask = h->n_buckets - 1; \
k = __hash_func(key); i = k & mask; \
last = i; \
while (!__ac_isempty(h->flags, i) && (__ac_isdel(h->flags, i) || !__hash_equal(h->keys[i], key))) { \
i = (i + (++step)) & mask; \
if (i == last) return h->n_buckets; \
} \
return __ac_iseither(h->flags, i)? h->n_buckets : i; \
} else return 0; \
} \
SCOPE int kh_resize_##name(kh_##name##_t *h, khint_t new_n_buckets) \
{ /* This function uses 0.25*n_buckets bytes of working space instead of [sizeof(key_t+val_t)+.25]*n_buckets. */ \
khint32_t *new_flags = 0; \
khint_t j = 1; \
{ \
kroundup32(new_n_buckets); \
if (new_n_buckets < 4) new_n_buckets = 4; \
if (h->size >= (khint_t)(new_n_buckets * __ac_HASH_UPPER + 0.5)) j = 0; /* requested size is too small */ \
else { /* hash table size to be changed (shrink or expand); rehash */ \
new_flags = (khint32_t*)kreallocarray(NULL, __ac_fsize(new_n_buckets), sizeof(khint32_t)); \
if (!new_flags) return -1; \
memset(new_flags, 0xaa, __ac_fsize(new_n_buckets) * sizeof(khint32_t)); \
if (h->n_buckets < new_n_buckets) { /* expand */ \
khkey_t *new_keys = (khkey_t*)kreallocarray((void *)h->keys, new_n_buckets, sizeof(khkey_t)); \
if (!new_keys) { kfree(new_flags); return -1; } \
h->keys = new_keys; \
if (kh_is_map) { \
khval_t *new_vals = (khval_t*)kreallocarray((void *)h->vals, new_n_buckets, sizeof(khval_t)); \
if (!new_vals) { kfree(new_flags); return -1; } \
h->vals = new_vals; \
} \
} /* otherwise shrink */ \
} \
} \
if (j) { /* rehashing is needed */ \
for (j = 0; j != h->n_buckets; ++j) { \
if (__ac_iseither(h->flags, j) == 0) { \
khkey_t key = h->keys[j]; \
khval_t val; \
khint_t new_mask; \
new_mask = new_n_buckets - 1; \
if (kh_is_map) val = h->vals[j]; \
__ac_set_isdel_true(h->flags, j); \
while (1) { /* kick-out process; sort of like in Cuckoo hashing */ \
khint_t k, i, step = 0; \
k = __hash_func(key); \
i = k & new_mask; \
while (!__ac_isempty(new_flags, i)) i = (i + (++step)) & new_mask; \
__ac_set_isempty_false(new_flags, i); \
if (i < h->n_buckets && __ac_iseither(h->flags, i) == 0) { /* kick out the existing element */ \
{ khkey_t tmp = h->keys[i]; h->keys[i] = key; key = tmp; } \
if (kh_is_map) { khval_t tmp = h->vals[i]; h->vals[i] = val; val = tmp; } \
__ac_set_isdel_true(h->flags, i); /* mark it as deleted in the old hash table */ \
} else { /* write the element and jump out of the loop */ \
h->keys[i] = key; \
if (kh_is_map) h->vals[i] = val; \
break; \
} \
} \
} \
} \
if (h->n_buckets > new_n_buckets) { /* shrink the hash table */ \
h->keys = (khkey_t*)kreallocarray((void *)h->keys, new_n_buckets, sizeof(khkey_t)); \
if (kh_is_map) h->vals = (khval_t*)kreallocarray((void *)h->vals, new_n_buckets, sizeof(khval_t)); \
} \
kfree(h->flags); /* free the working space */ \
h->flags = new_flags; \
h->n_buckets = new_n_buckets; \
h->n_occupied = h->size; \
h->upper_bound = (khint_t)(h->n_buckets * __ac_HASH_UPPER + 0.5); \
} \
return 0; \
} \
SCOPE khint_t kh_put_##name(kh_##name##_t *h, khkey_t key, int *ret) \
{ \
khint_t x; \
if (h->n_occupied >= h->upper_bound) { /* update the hash table */ \
if (h->n_buckets > (h->size<<1)) { \
if (kh_resize_##name(h, h->n_buckets - 1) < 0) { /* clear "deleted" elements */ \
*ret = -1; return h->n_buckets; \
} \
} else if (kh_resize_##name(h, h->n_buckets + 1) < 0) { /* expand the hash table */ \
*ret = -1; return h->n_buckets; \
} \
} /* TODO: to implement automatically shrinking; resize() already support shrinking */ \
{ \
khint_t k, i, site, last, mask = h->n_buckets - 1, step = 0; \
x = site = h->n_buckets; k = __hash_func(key); i = k & mask; \
if (__ac_isempty(h->flags, i)) x = i; /* for speed up */ \
else { \
last = i; \
while (!__ac_isempty(h->flags, i) && (__ac_isdel(h->flags, i) || !__hash_equal(h->keys[i], key))) { \
if (__ac_isdel(h->flags, i)) site = i; \
i = (i + (++step)) & mask; \
if (i == last) { x = site; break; } \
} \
if (x == h->n_buckets) { \
if (__ac_isempty(h->flags, i) && site != h->n_buckets) x = site; \
else x = i; \
} \
} \
} \
if (__ac_isempty(h->flags, x)) { /* not present at all */ \
h->keys[x] = key; \
__ac_set_isboth_false(h->flags, x); \
++h->size; ++h->n_occupied; \
*ret = 1; \
} else if (__ac_isdel(h->flags, x)) { /* deleted */ \
h->keys[x] = key; \
__ac_set_isboth_false(h->flags, x); \
++h->size; \
*ret = 2; \
} else *ret = 0; /* Don't touch h->keys[x] if present and not deleted */ \
return x; \
} \
SCOPE void kh_del_##name(kh_##name##_t *h, khint_t x) \
{ \
if (x != h->n_buckets && !__ac_iseither(h->flags, x)) { \
__ac_set_isdel_true(h->flags, x); \
--h->size; \
} \
}
#define KHASH_DECLARE(name, khkey_t, khval_t) \
__KHASH_TYPE(name, khkey_t, khval_t) \
__KHASH_PROTOTYPES(name, khkey_t, khval_t)
#define KHASH_INIT2(name, SCOPE, khkey_t, khval_t, kh_is_map, __hash_func, __hash_equal) \
__KHASH_TYPE(name, khkey_t, khval_t) \
__KHASH_IMPL(name, SCOPE, khkey_t, khval_t, kh_is_map, __hash_func, __hash_equal)
#define KHASH_INIT(name, khkey_t, khval_t, kh_is_map, __hash_func, __hash_equal) \
KHASH_INIT2(name, static kh_inline, khkey_t, khval_t, kh_is_map, __hash_func, __hash_equal)
/* --- BEGIN OF HASH FUNCTIONS --- */
/*! @function
@abstract Integer hash function
@param key The integer [khint32_t]
@return The hash value [khint_t]
*/
#define kh_int_hash_func(key) (khint32_t)(key)
/*! @function
@abstract Integer comparison function
*/
#define kh_int_hash_equal(a, b) ((a) == (b))
/*! @function
@abstract 64-bit integer hash function
@param key The integer [khint64_t]
@return The hash value [khint_t]
*/
#define kh_int64_hash_func(key) (khint32_t)((key)>>33^(key)^(key)<<11)
/*! @function
@abstract 64-bit integer comparison function
*/
#define kh_int64_hash_equal(a, b) ((a) == (b))
/*! @function
@abstract const char* hash function
@param s Pointer to a null terminated string
@return The hash value
*/
static kh_inline khint_t __ac_X31_hash_string(const char *s)
{
khint_t h = (khint_t)*s;
if (h) for (++s ; *s; ++s) h = (h << 5) - h + (khint_t)*s;
return h;
}
/*! @function
@abstract Another interface to const char* hash function
@param key Pointer to a null terminated string [const char*]
@return The hash value [khint_t]
*/
#define kh_str_hash_func(key) __ac_X31_hash_string(key)
/*! @function
@abstract Const char* comparison function
*/
#define kh_str_hash_equal(a, b) (strcmp(a, b) == 0)
static kh_inline khint_t __ac_Wang_hash(khint_t key)
{
key += ~(key << 15);
key ^= (key >> 10);
key += (key << 3);
key ^= (key >> 6);
key += ~(key << 11);
key ^= (key >> 16);
return key;
}
#define kh_int_hash_func2(k) __ac_Wang_hash((khint_t)key)
/* --- END OF HASH FUNCTIONS --- */
/* Other convenient macros... */
/*!
@abstract Type of the hash table.
@param name Name of the hash table [symbol]
*/
#define khash_t(name) kh_##name##_t
/*! @function
@abstract Initiate a hash table.
@param name Name of the hash table [symbol]
@return Pointer to the hash table [khash_t(name)*]
*/
#define kh_init(name) kh_init_##name()
/*! @function
@abstract Destroy a hash table.
@param name Name of the hash table [symbol]
@param h Pointer to the hash table [khash_t(name)*]
*/
#define kh_destroy(name, h) kh_destroy_##name(h)
/*! @function
@abstract Reset a hash table without deallocating memory.
@param name Name of the hash table [symbol]
@param h Pointer to the hash table [khash_t(name)*]
*/
#define kh_clear(name, h) kh_clear_##name(h)
/*! @function
@abstract Resize a hash table.
@param name Name of the hash table [symbol]
@param h Pointer to the hash table [khash_t(name)*]
@param s New size [khint_t]
*/
#define kh_resize(name, h, s) kh_resize_##name(h, s)
/*! @function
@abstract Insert a key to the hash table.
@param name Name of the hash table [symbol]
@param h Pointer to the hash table [khash_t(name)*]
@param k Key [type of keys]
@param r Extra return code: -1 if the operation failed;
0 if the key is present in the hash table;
1 if the bucket is empty (never used); 2 if the element in
the bucket has been deleted [int*]
@return Iterator to the inserted element [khint_t]
*/
#define kh_put(name, h, k, r) kh_put_##name(h, k, r)
/*! @function
@abstract Retrieve a key from the hash table.
@param name Name of the hash table [symbol]
@param h Pointer to the hash table [khash_t(name)*]
@param k Key [type of keys]
@return Iterator to the found element, or kh_end(h) if the element is absent [khint_t]
*/
#define kh_get(name, h, k) kh_get_##name(h, k)
/*! @function
@abstract Remove a key from the hash table.
@param name Name of the hash table [symbol]
@param h Pointer to the hash table [khash_t(name)*]
@param k Iterator to the element to be deleted [khint_t]
*/
#define kh_del(name, h, k) kh_del_##name(h, k)
/*! @function
@abstract Test whether a bucket contains data.
@param h Pointer to the hash table [khash_t(name)*]
@param x Iterator to the bucket [khint_t]
@return 1 if containing data; 0 otherwise [int]
*/
#define kh_exist(h, x) (!__ac_iseither((h)->flags, (x)))
/*! @function
@abstract Get key given an iterator
@param h Pointer to the hash table [khash_t(name)*]
@param x Iterator to the bucket [khint_t]
@return Key [type of keys]
*/
#define kh_key(h, x) ((h)->keys[x])
/*! @function
@abstract Get value given an iterator
@param h Pointer to the hash table [khash_t(name)*]
@param x Iterator to the bucket [khint_t]
@return Value [type of values]
@discussion For hash sets, calling this results in segfault.
*/
#define kh_val(h, x) ((h)->vals[x])
/*! @function
@abstract Alias of kh_val()
*/
#define kh_value(h, x) ((h)->vals[x])
/*! @function
@abstract Get the start iterator
@param h Pointer to the hash table [khash_t(name)*]
@return The start iterator [khint_t]
*/
#define kh_begin(h) (khint_t)(0)
/*! @function
@abstract Get the end iterator
@param h Pointer to the hash table [khash_t(name)*]
@return The end iterator [khint_t]
*/
#define kh_end(h) ((h)->n_buckets)
/*! @function
@abstract Get the number of elements in the hash table
@param h Pointer to the hash table [khash_t(name)*]
@return Number of elements in the hash table [khint_t]
*/
#define kh_size(h) ((h)->size)
/*! @function
@abstract Get the number of buckets in the hash table
@param h Pointer to the hash table [khash_t(name)*]
@return Number of buckets in the hash table [khint_t]
*/
#define kh_n_buckets(h) ((h)->n_buckets)
/*! @function
@abstract Iterate over the entries in the hash table
@param h Pointer to the hash table [khash_t(name)*]
@param kvar Variable to which key will be assigned
@param vvar Variable to which value will be assigned
@param code Block of code to execute
*/
#define kh_foreach(h, kvar, vvar, code) { khint_t __i; \
for (__i = kh_begin(h); __i != kh_end(h); ++__i) { \
if (!kh_exist(h,__i)) continue; \
(kvar) = kh_key(h,__i); \
(vvar) = kh_val(h,__i); \
code; \
} }
/*! @function
@abstract Iterate over the values in the hash table
@param h Pointer to the hash table [khash_t(name)*]
@param vvar Variable to which value will be assigned
@param code Block of code to execute
*/
#define kh_foreach_value(h, vvar, code) { khint_t __i; \
for (__i = kh_begin(h); __i != kh_end(h); ++__i) { \
if (!kh_exist(h,__i)) continue; \
(vvar) = kh_val(h,__i); \
code; \
} }
/* More conenient interfaces */
/*! @function
@abstract Instantiate a hash set containing integer keys
@param name Name of the hash table [symbol]
*/
#define KHASH_SET_INIT_INT(name) \
KHASH_INIT(name, khint32_t, char, 0, kh_int_hash_func, kh_int_hash_equal)
/*! @function
@abstract Instantiate a hash map containing integer keys
@param name Name of the hash table [symbol]
@param khval_t Type of values [type]
*/
#define KHASH_MAP_INIT_INT(name, khval_t) \
KHASH_INIT(name, khint32_t, khval_t, 1, kh_int_hash_func, kh_int_hash_equal)
/*! @function
@abstract Instantiate a hash map containing 64-bit integer keys
@param name Name of the hash table [symbol]
*/
#define KHASH_SET_INIT_INT64(name) \
KHASH_INIT(name, khint64_t, char, 0, kh_int64_hash_func, kh_int64_hash_equal)
/*! @function
@abstract Instantiate a hash map containing 64-bit integer keys
@param name Name of the hash table [symbol]
@param khval_t Type of values [type]
*/
#define KHASH_MAP_INIT_INT64(name, khval_t) \
KHASH_INIT(name, khint64_t, khval_t, 1, kh_int64_hash_func, kh_int64_hash_equal)
typedef const char *kh_cstr_t;
/*! @function
@abstract Instantiate a hash map containing const char* keys
@param name Name of the hash table [symbol]
*/
#define KHASH_SET_INIT_STR(name) \
KHASH_INIT(name, kh_cstr_t, char, 0, kh_str_hash_func, kh_str_hash_equal)
/*! @function
@abstract Instantiate a hash map containing const char* keys
@param name Name of the hash table [symbol]
@param khval_t Type of values [type]
*/
#define KHASH_MAP_INIT_STR(name, khval_t) \
KHASH_INIT(name, kh_cstr_t, khval_t, 1, kh_str_hash_func, kh_str_hash_equal)
#endif /* __AC_KHASH_H */
|
0 |
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2
|
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2/src/crlf.c
|
/*
* Copyright (C) the libgit2 contributors. All rights reserved.
*
* This file is part of libgit2, distributed under the GNU GPL v2 with
* a Linking Exception. For full terms see the included COPYING file.
*/
#include "common.h"
#include "git2/attr.h"
#include "git2/blob.h"
#include "git2/index.h"
#include "git2/sys/filter.h"
#include "futils.h"
#include "hash.h"
#include "filter.h"
#include "repository.h"
typedef enum {
GIT_CRLF_UNDEFINED,
GIT_CRLF_BINARY,
GIT_CRLF_TEXT,
GIT_CRLF_TEXT_INPUT,
GIT_CRLF_TEXT_CRLF,
GIT_CRLF_AUTO,
GIT_CRLF_AUTO_INPUT,
GIT_CRLF_AUTO_CRLF,
} git_crlf_t;
struct crlf_attrs {
int attr_action; /* the .gitattributes setting */
int crlf_action; /* the core.autocrlf setting */
int auto_crlf;
int safe_crlf;
int core_eol;
};
struct crlf_filter {
git_filter f;
};
static git_crlf_t check_crlf(const char *value)
{
if (GIT_ATTR_IS_TRUE(value))
return GIT_CRLF_TEXT;
else if (GIT_ATTR_IS_FALSE(value))
return GIT_CRLF_BINARY;
else if (GIT_ATTR_IS_UNSPECIFIED(value))
;
else if (strcmp(value, "input") == 0)
return GIT_CRLF_TEXT_INPUT;
else if (strcmp(value, "auto") == 0)
return GIT_CRLF_AUTO;
return GIT_CRLF_UNDEFINED;
}
static git_configmap_value check_eol(const char *value)
{
if (GIT_ATTR_IS_UNSPECIFIED(value))
;
else if (strcmp(value, "lf") == 0)
return GIT_EOL_LF;
else if (strcmp(value, "crlf") == 0)
return GIT_EOL_CRLF;
return GIT_EOL_UNSET;
}
static int has_cr_in_index(const git_filter_source *src)
{
git_repository *repo = git_filter_source_repo(src);
const char *path = git_filter_source_path(src);
git_index *index;
const git_index_entry *entry;
git_blob *blob;
const void *blobcontent;
git_object_size_t blobsize;
bool found_cr;
if (!path)
return false;
if (git_repository_index__weakptr(&index, repo) < 0) {
git_error_clear();
return false;
}
if (!(entry = git_index_get_bypath(index, path, 0)) &&
!(entry = git_index_get_bypath(index, path, 1)))
return false;
if (!S_ISREG(entry->mode)) /* don't crlf filter non-blobs */
return true;
if (git_blob_lookup(&blob, repo, &entry->id) < 0)
return false;
blobcontent = git_blob_rawcontent(blob);
blobsize = git_blob_rawsize(blob);
if (!git__is_sizet(blobsize))
blobsize = (size_t)-1;
found_cr = (blobcontent != NULL &&
blobsize > 0 &&
memchr(blobcontent, '\r', (size_t)blobsize) != NULL);
git_blob_free(blob);
return found_cr;
}
static int text_eol_is_crlf(struct crlf_attrs *ca)
{
if (ca->auto_crlf == GIT_AUTO_CRLF_TRUE)
return 1;
else if (ca->auto_crlf == GIT_AUTO_CRLF_INPUT)
return 0;
if (ca->core_eol == GIT_EOL_CRLF)
return 1;
if (ca->core_eol == GIT_EOL_UNSET && GIT_EOL_NATIVE == GIT_EOL_CRLF)
return 1;
return 0;
}
static git_configmap_value output_eol(struct crlf_attrs *ca)
{
switch (ca->crlf_action) {
case GIT_CRLF_BINARY:
return GIT_EOL_UNSET;
case GIT_CRLF_TEXT_CRLF:
return GIT_EOL_CRLF;
case GIT_CRLF_TEXT_INPUT:
return GIT_EOL_LF;
case GIT_CRLF_UNDEFINED:
case GIT_CRLF_AUTO_CRLF:
return GIT_EOL_CRLF;
case GIT_CRLF_AUTO_INPUT:
return GIT_EOL_LF;
case GIT_CRLF_TEXT:
case GIT_CRLF_AUTO:
return text_eol_is_crlf(ca) ? GIT_EOL_CRLF : GIT_EOL_LF;
}
/* TODO: warn when available */
return ca->core_eol;
}
GIT_INLINE(int) check_safecrlf(
struct crlf_attrs *ca,
const git_filter_source *src,
git_buf_text_stats *stats)
{
const char *filename = git_filter_source_path(src);
if (!ca->safe_crlf)
return 0;
if (output_eol(ca) == GIT_EOL_LF) {
/*
* CRLFs would not be restored by checkout:
* check if we'd remove CRLFs
*/
if (stats->crlf) {
if (ca->safe_crlf == GIT_SAFE_CRLF_WARN) {
/* TODO: issue a warning when available */
} else {
if (filename && *filename)
git_error_set(
GIT_ERROR_FILTER, "CRLF would be replaced by LF in '%s'",
filename);
else
git_error_set(
GIT_ERROR_FILTER, "CRLF would be replaced by LF");
return -1;
}
}
} else if (output_eol(ca) == GIT_EOL_CRLF) {
/*
* CRLFs would be added by checkout:
* check if we have "naked" LFs
*/
if (stats->crlf != stats->lf) {
if (ca->safe_crlf == GIT_SAFE_CRLF_WARN) {
/* TODO: issue a warning when available */
} else {
if (filename && *filename)
git_error_set(
GIT_ERROR_FILTER, "LF would be replaced by CRLF in '%s'",
filename);
else
git_error_set(
GIT_ERROR_FILTER, "LF would be replaced by CRLF");
return -1;
}
}
}
return 0;
}
static int crlf_apply_to_odb(
struct crlf_attrs *ca,
git_buf *to,
const git_buf *from,
const git_filter_source *src)
{
git_buf_text_stats stats;
bool is_binary;
int error;
/* Binary attribute? Empty file? Nothing to do */
if (ca->crlf_action == GIT_CRLF_BINARY || !git_buf_len(from))
return GIT_PASSTHROUGH;
is_binary = git_buf_gather_text_stats(&stats, from, false);
/* Heuristics to see if we can skip the conversion.
* Straight from Core Git.
*/
if (ca->crlf_action == GIT_CRLF_AUTO ||
ca->crlf_action == GIT_CRLF_AUTO_INPUT ||
ca->crlf_action == GIT_CRLF_AUTO_CRLF) {
if (is_binary)
return GIT_PASSTHROUGH;
/*
* If the file in the index has any CR in it, do not convert.
* This is the new safer autocrlf handling.
*/
if (has_cr_in_index(src))
return GIT_PASSTHROUGH;
}
if ((error = check_safecrlf(ca, src, &stats)) < 0)
return error;
/* If there are no CR characters to filter out, then just pass */
if (!stats.crlf)
return GIT_PASSTHROUGH;
/* Actually drop the carriage returns */
return git_buf_crlf_to_lf(to, from);
}
static int crlf_apply_to_workdir(
struct crlf_attrs *ca,
git_buf *to,
const git_buf *from)
{
git_buf_text_stats stats;
bool is_binary;
/* Empty file? Nothing to do. */
if (git_buf_len(from) == 0 || output_eol(ca) != GIT_EOL_CRLF)
return GIT_PASSTHROUGH;
is_binary = git_buf_gather_text_stats(&stats, from, false);
/* If there are no LFs, or all LFs are part of a CRLF, nothing to do */
if (stats.lf == 0 || stats.lf == stats.crlf)
return GIT_PASSTHROUGH;
if (ca->crlf_action == GIT_CRLF_AUTO ||
ca->crlf_action == GIT_CRLF_AUTO_INPUT ||
ca->crlf_action == GIT_CRLF_AUTO_CRLF) {
/* If we have any existing CR or CRLF line endings, do nothing */
if (stats.cr > 0)
return GIT_PASSTHROUGH;
/* Don't filter binary files */
if (is_binary)
return GIT_PASSTHROUGH;
}
return git_buf_lf_to_crlf(to, from);
}
static int convert_attrs(
struct crlf_attrs *ca,
const char **attr_values,
const git_filter_source *src)
{
int error;
memset(ca, 0, sizeof(struct crlf_attrs));
if ((error = git_repository__configmap_lookup(&ca->auto_crlf,
git_filter_source_repo(src), GIT_CONFIGMAP_AUTO_CRLF)) < 0 ||
(error = git_repository__configmap_lookup(&ca->safe_crlf,
git_filter_source_repo(src), GIT_CONFIGMAP_SAFE_CRLF)) < 0 ||
(error = git_repository__configmap_lookup(&ca->core_eol,
git_filter_source_repo(src), GIT_CONFIGMAP_EOL)) < 0)
return error;
/* downgrade FAIL to WARN if ALLOW_UNSAFE option is used */
if ((git_filter_source_flags(src) & GIT_FILTER_ALLOW_UNSAFE) &&
ca->safe_crlf == GIT_SAFE_CRLF_FAIL)
ca->safe_crlf = GIT_SAFE_CRLF_WARN;
if (attr_values) {
/* load the text attribute */
ca->crlf_action = check_crlf(attr_values[2]); /* text */
if (ca->crlf_action == GIT_CRLF_UNDEFINED)
ca->crlf_action = check_crlf(attr_values[0]); /* crlf */
if (ca->crlf_action != GIT_CRLF_BINARY) {
/* load the eol attribute */
int eol_attr = check_eol(attr_values[1]);
if (ca->crlf_action == GIT_CRLF_AUTO && eol_attr == GIT_EOL_LF)
ca->crlf_action = GIT_CRLF_AUTO_INPUT;
else if (ca->crlf_action == GIT_CRLF_AUTO && eol_attr == GIT_EOL_CRLF)
ca->crlf_action = GIT_CRLF_AUTO_CRLF;
else if (eol_attr == GIT_EOL_LF)
ca->crlf_action = GIT_CRLF_TEXT_INPUT;
else if (eol_attr == GIT_EOL_CRLF)
ca->crlf_action = GIT_CRLF_TEXT_CRLF;
}
ca->attr_action = ca->crlf_action;
} else {
ca->crlf_action = GIT_CRLF_UNDEFINED;
}
if (ca->crlf_action == GIT_CRLF_TEXT)
ca->crlf_action = text_eol_is_crlf(ca) ? GIT_CRLF_TEXT_CRLF : GIT_CRLF_TEXT_INPUT;
if (ca->crlf_action == GIT_CRLF_UNDEFINED && ca->auto_crlf == GIT_AUTO_CRLF_FALSE)
ca->crlf_action = GIT_CRLF_BINARY;
if (ca->crlf_action == GIT_CRLF_UNDEFINED && ca->auto_crlf == GIT_AUTO_CRLF_TRUE)
ca->crlf_action = GIT_CRLF_AUTO_CRLF;
if (ca->crlf_action == GIT_CRLF_UNDEFINED && ca->auto_crlf == GIT_AUTO_CRLF_INPUT)
ca->crlf_action = GIT_CRLF_AUTO_INPUT;
return 0;
}
static int crlf_check(
git_filter *self,
void **payload, /* points to NULL ptr on entry, may be set */
const git_filter_source *src,
const char **attr_values)
{
struct crlf_attrs ca;
GIT_UNUSED(self);
convert_attrs(&ca, attr_values, src);
if (ca.crlf_action == GIT_CRLF_BINARY)
return GIT_PASSTHROUGH;
*payload = git__malloc(sizeof(ca));
GIT_ERROR_CHECK_ALLOC(*payload);
memcpy(*payload, &ca, sizeof(ca));
return 0;
}
static int crlf_apply(
git_filter *self,
void **payload, /* may be read and/or set */
git_buf *to,
const git_buf *from,
const git_filter_source *src)
{
/* initialize payload in case `check` was bypassed */
if (!*payload) {
int error = crlf_check(self, payload, src, NULL);
if (error < 0)
return error;
}
if (git_filter_source_mode(src) == GIT_FILTER_SMUDGE)
return crlf_apply_to_workdir(*payload, to, from);
else
return crlf_apply_to_odb(*payload, to, from, src);
}
static int crlf_stream(
git_writestream **out,
git_filter *self,
void **payload,
const git_filter_source *src,
git_writestream *next)
{
return git_filter_buffered_stream_new(out,
self, crlf_apply, NULL, payload, src, next);
}
static void crlf_cleanup(
git_filter *self,
void *payload)
{
GIT_UNUSED(self);
git__free(payload);
}
git_filter *git_crlf_filter_new(void)
{
struct crlf_filter *f = git__calloc(1, sizeof(struct crlf_filter));
if (f == NULL)
return NULL;
f->f.version = GIT_FILTER_VERSION;
f->f.attributes = "crlf eol text";
f->f.initialize = NULL;
f->f.shutdown = git_filter_free;
f->f.check = crlf_check;
f->f.stream = crlf_stream;
f->f.cleanup = crlf_cleanup;
return (git_filter *)f;
}
|
0 |
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2
|
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2/src/merge_driver.c
|
/*
* Copyright (C) the libgit2 contributors. All rights reserved.
*
* This file is part of libgit2, distributed under the GNU GPL v2 with
* a Linking Exception. For full terms see the included COPYING file.
*/
#include "merge_driver.h"
#include "vector.h"
#include "runtime.h"
#include "merge.h"
#include "git2/merge.h"
#include "git2/sys/merge.h"
static const char *merge_driver_name__text = "text";
static const char *merge_driver_name__union = "union";
static const char *merge_driver_name__binary = "binary";
struct merge_driver_registry {
git_rwlock lock;
git_vector drivers;
};
typedef struct {
git_merge_driver *driver;
int initialized;
char name[GIT_FLEX_ARRAY];
} git_merge_driver_entry;
static struct merge_driver_registry merge_driver_registry;
static void git_merge_driver_global_shutdown(void);
git_repository *git_merge_driver_source_repo(
const git_merge_driver_source *src)
{
GIT_ASSERT_ARG_WITH_RETVAL(src, NULL);
return src->repo;
}
const git_index_entry *git_merge_driver_source_ancestor(
const git_merge_driver_source *src)
{
GIT_ASSERT_ARG_WITH_RETVAL(src, NULL);
return src->ancestor;
}
const git_index_entry *git_merge_driver_source_ours(
const git_merge_driver_source *src)
{
GIT_ASSERT_ARG_WITH_RETVAL(src, NULL);
return src->ours;
}
const git_index_entry *git_merge_driver_source_theirs(
const git_merge_driver_source *src)
{
GIT_ASSERT_ARG_WITH_RETVAL(src, NULL);
return src->theirs;
}
const git_merge_file_options *git_merge_driver_source_file_options(
const git_merge_driver_source *src)
{
GIT_ASSERT_ARG_WITH_RETVAL(src, NULL);
return src->file_opts;
}
int git_merge_driver__builtin_apply(
git_merge_driver *self,
const char **path_out,
uint32_t *mode_out,
git_buf *merged_out,
const char *filter_name,
const git_merge_driver_source *src)
{
git_merge_driver__builtin *driver = (git_merge_driver__builtin *)self;
git_merge_file_options file_opts = GIT_MERGE_FILE_OPTIONS_INIT;
git_merge_file_result result = {0};
int error;
GIT_UNUSED(filter_name);
if (src->file_opts)
memcpy(&file_opts, src->file_opts, sizeof(git_merge_file_options));
if (driver->favor)
file_opts.favor = driver->favor;
if ((error = git_merge_file_from_index(&result, src->repo,
src->ancestor, src->ours, src->theirs, &file_opts)) < 0)
goto done;
if (!result.automergeable &&
!(file_opts.flags & GIT_MERGE_FILE_FAVOR__CONFLICTED)) {
error = GIT_EMERGECONFLICT;
goto done;
}
*path_out = git_merge_file__best_path(
src->ancestor ? src->ancestor->path : NULL,
src->ours ? src->ours->path : NULL,
src->theirs ? src->theirs->path : NULL);
*mode_out = git_merge_file__best_mode(
src->ancestor ? src->ancestor->mode : 0,
src->ours ? src->ours->mode : 0,
src->theirs ? src->theirs->mode : 0);
merged_out->ptr = (char *)result.ptr;
merged_out->size = result.len;
merged_out->asize = result.len;
result.ptr = NULL;
done:
git_merge_file_result_free(&result);
return error;
}
static int merge_driver_binary_apply(
git_merge_driver *self,
const char **path_out,
uint32_t *mode_out,
git_buf *merged_out,
const char *filter_name,
const git_merge_driver_source *src)
{
GIT_UNUSED(self);
GIT_UNUSED(path_out);
GIT_UNUSED(mode_out);
GIT_UNUSED(merged_out);
GIT_UNUSED(filter_name);
GIT_UNUSED(src);
return GIT_EMERGECONFLICT;
}
static int merge_driver_entry_cmp(const void *a, const void *b)
{
const git_merge_driver_entry *entry_a = a;
const git_merge_driver_entry *entry_b = b;
return strcmp(entry_a->name, entry_b->name);
}
static int merge_driver_entry_search(const void *a, const void *b)
{
const char *name_a = a;
const git_merge_driver_entry *entry_b = b;
return strcmp(name_a, entry_b->name);
}
git_merge_driver__builtin git_merge_driver__text = {
{
GIT_MERGE_DRIVER_VERSION,
NULL,
NULL,
git_merge_driver__builtin_apply,
},
GIT_MERGE_FILE_FAVOR_NORMAL
};
git_merge_driver__builtin git_merge_driver__union = {
{
GIT_MERGE_DRIVER_VERSION,
NULL,
NULL,
git_merge_driver__builtin_apply,
},
GIT_MERGE_FILE_FAVOR_UNION
};
git_merge_driver git_merge_driver__binary = {
GIT_MERGE_DRIVER_VERSION,
NULL,
NULL,
merge_driver_binary_apply
};
/* Note: callers must lock the registry before calling this function */
static int merge_driver_registry_insert(
const char *name, git_merge_driver *driver)
{
git_merge_driver_entry *entry;
entry = git__calloc(1, sizeof(git_merge_driver_entry) + strlen(name) + 1);
GIT_ERROR_CHECK_ALLOC(entry);
strcpy(entry->name, name);
entry->driver = driver;
return git_vector_insert_sorted(
&merge_driver_registry.drivers, entry, NULL);
}
int git_merge_driver_global_init(void)
{
int error;
if (git_rwlock_init(&merge_driver_registry.lock) < 0)
return -1;
if ((error = git_vector_init(&merge_driver_registry.drivers, 3,
merge_driver_entry_cmp)) < 0)
goto done;
if ((error = merge_driver_registry_insert(
merge_driver_name__text, &git_merge_driver__text.base)) < 0 ||
(error = merge_driver_registry_insert(
merge_driver_name__union, &git_merge_driver__union.base)) < 0 ||
(error = merge_driver_registry_insert(
merge_driver_name__binary, &git_merge_driver__binary)) < 0)
goto done;
error = git_runtime_shutdown_register(git_merge_driver_global_shutdown);
done:
if (error < 0)
git_vector_free_deep(&merge_driver_registry.drivers);
return error;
}
static void git_merge_driver_global_shutdown(void)
{
git_merge_driver_entry *entry;
size_t i;
if (git_rwlock_wrlock(&merge_driver_registry.lock) < 0)
return;
git_vector_foreach(&merge_driver_registry.drivers, i, entry) {
if (entry->driver->shutdown)
entry->driver->shutdown(entry->driver);
git__free(entry);
}
git_vector_free(&merge_driver_registry.drivers);
git_rwlock_wrunlock(&merge_driver_registry.lock);
git_rwlock_free(&merge_driver_registry.lock);
}
/* Note: callers must lock the registry before calling this function */
static int merge_driver_registry_find(size_t *pos, const char *name)
{
return git_vector_search2(pos, &merge_driver_registry.drivers,
merge_driver_entry_search, name);
}
/* Note: callers must lock the registry before calling this function */
static git_merge_driver_entry *merge_driver_registry_lookup(
size_t *pos, const char *name)
{
git_merge_driver_entry *entry = NULL;
if (!merge_driver_registry_find(pos, name))
entry = git_vector_get(&merge_driver_registry.drivers, *pos);
return entry;
}
int git_merge_driver_register(const char *name, git_merge_driver *driver)
{
int error;
GIT_ASSERT_ARG(name);
GIT_ASSERT_ARG(driver);
if (git_rwlock_wrlock(&merge_driver_registry.lock) < 0) {
git_error_set(GIT_ERROR_OS, "failed to lock merge driver registry");
return -1;
}
if (!merge_driver_registry_find(NULL, name)) {
git_error_set(GIT_ERROR_MERGE, "attempt to reregister existing driver '%s'",
name);
error = GIT_EEXISTS;
goto done;
}
error = merge_driver_registry_insert(name, driver);
done:
git_rwlock_wrunlock(&merge_driver_registry.lock);
return error;
}
int git_merge_driver_unregister(const char *name)
{
git_merge_driver_entry *entry;
size_t pos;
int error = 0;
if (git_rwlock_wrlock(&merge_driver_registry.lock) < 0) {
git_error_set(GIT_ERROR_OS, "failed to lock merge driver registry");
return -1;
}
if ((entry = merge_driver_registry_lookup(&pos, name)) == NULL) {
git_error_set(GIT_ERROR_MERGE, "cannot find merge driver '%s' to unregister",
name);
error = GIT_ENOTFOUND;
goto done;
}
git_vector_remove(&merge_driver_registry.drivers, pos);
if (entry->initialized && entry->driver->shutdown) {
entry->driver->shutdown(entry->driver);
entry->initialized = false;
}
git__free(entry);
done:
git_rwlock_wrunlock(&merge_driver_registry.lock);
return error;
}
git_merge_driver *git_merge_driver_lookup(const char *name)
{
git_merge_driver_entry *entry;
size_t pos;
int error;
/* If we've decided the merge driver to use internally - and not
* based on user configuration (in merge_driver_name_for_path)
* then we can use a hardcoded name to compare instead of bothering
* to take a lock and look it up in the vector.
*/
if (name == merge_driver_name__text)
return &git_merge_driver__text.base;
else if (name == merge_driver_name__binary)
return &git_merge_driver__binary;
if (git_rwlock_rdlock(&merge_driver_registry.lock) < 0) {
git_error_set(GIT_ERROR_OS, "failed to lock merge driver registry");
return NULL;
}
entry = merge_driver_registry_lookup(&pos, name);
git_rwlock_rdunlock(&merge_driver_registry.lock);
if (entry == NULL) {
git_error_set(GIT_ERROR_MERGE, "cannot use an unregistered filter");
return NULL;
}
if (!entry->initialized) {
if (entry->driver->initialize &&
(error = entry->driver->initialize(entry->driver)) < 0)
return NULL;
entry->initialized = 1;
}
return entry->driver;
}
static int merge_driver_name_for_path(
const char **out,
git_repository *repo,
const char *path,
const char *default_driver)
{
const char *value;
int error;
*out = NULL;
if ((error = git_attr_get(&value, repo, 0, path, "merge")) < 0)
return error;
/* set: use the built-in 3-way merge driver ("text") */
if (GIT_ATTR_IS_TRUE(value))
*out = merge_driver_name__text;
/* unset: do not merge ("binary") */
else if (GIT_ATTR_IS_FALSE(value))
*out = merge_driver_name__binary;
else if (GIT_ATTR_IS_UNSPECIFIED(value) && default_driver)
*out = default_driver;
else if (GIT_ATTR_IS_UNSPECIFIED(value))
*out = merge_driver_name__text;
else
*out = value;
return 0;
}
GIT_INLINE(git_merge_driver *) merge_driver_lookup_with_wildcard(
const char *name)
{
git_merge_driver *driver = git_merge_driver_lookup(name);
if (driver == NULL)
driver = git_merge_driver_lookup("*");
return driver;
}
int git_merge_driver_for_source(
const char **name_out,
git_merge_driver **driver_out,
const git_merge_driver_source *src)
{
const char *path, *driver_name;
int error = 0;
path = git_merge_file__best_path(
src->ancestor ? src->ancestor->path : NULL,
src->ours ? src->ours->path : NULL,
src->theirs ? src->theirs->path : NULL);
if ((error = merge_driver_name_for_path(
&driver_name, src->repo, path, src->default_driver)) < 0)
return error;
*name_out = driver_name;
*driver_out = merge_driver_lookup_with_wildcard(driver_name);
return error;
}
|
0 |
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2
|
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2/src/blame_git.c
|
/*
* Copyright (C) the libgit2 contributors. All rights reserved.
*
* This file is part of libgit2, distributed under the GNU GPL v2 with
* a Linking Exception. For full terms see the included COPYING file.
*/
#include "blame_git.h"
#include "commit.h"
#include "blob.h"
#include "xdiff/xinclude.h"
#include "diff_xdiff.h"
/*
* Origin is refcounted and usually we keep the blob contents to be
* reused.
*/
static git_blame__origin *origin_incref(git_blame__origin *o)
{
if (o)
o->refcnt++;
return o;
}
static void origin_decref(git_blame__origin *o)
{
if (o && --o->refcnt <= 0) {
if (o->previous)
origin_decref(o->previous);
git_blob_free(o->blob);
git_commit_free(o->commit);
git__free(o);
}
}
/* Given a commit and a path in it, create a new origin structure. */
static int make_origin(git_blame__origin **out, git_commit *commit, const char *path)
{
git_blame__origin *o;
git_object *blob;
size_t path_len = strlen(path), alloc_len;
int error = 0;
if ((error = git_object_lookup_bypath(&blob, (git_object*)commit,
path, GIT_OBJECT_BLOB)) < 0)
return error;
GIT_ERROR_CHECK_ALLOC_ADD(&alloc_len, sizeof(*o), path_len);
GIT_ERROR_CHECK_ALLOC_ADD(&alloc_len, alloc_len, 1);
o = git__calloc(1, alloc_len);
GIT_ERROR_CHECK_ALLOC(o);
o->commit = commit;
o->blob = (git_blob *) blob;
o->refcnt = 1;
strcpy(o->path, path);
*out = o;
return 0;
}
/* Locate an existing origin or create a new one. */
int git_blame__get_origin(
git_blame__origin **out,
git_blame *blame,
git_commit *commit,
const char *path)
{
git_blame__entry *e;
for (e = blame->ent; e; e = e->next) {
if (e->suspect->commit == commit && !strcmp(e->suspect->path, path)) {
*out = origin_incref(e->suspect);
}
}
return make_origin(out, commit, path);
}
typedef struct blame_chunk_cb_data {
git_blame *blame;
git_blame__origin *target;
git_blame__origin *parent;
long tlno;
long plno;
}blame_chunk_cb_data;
static bool same_suspect(git_blame__origin *a, git_blame__origin *b)
{
if (a == b)
return true;
if (git_oid_cmp(git_commit_id(a->commit), git_commit_id(b->commit)))
return false;
return 0 == strcmp(a->path, b->path);
}
/* find the line number of the last line the target is suspected for */
static bool find_last_in_target(size_t *out, git_blame *blame, git_blame__origin *target)
{
git_blame__entry *e;
size_t last_in_target = 0;
bool found = false;
*out = 0;
for (e=blame->ent; e; e=e->next) {
if (e->guilty || !same_suspect(e->suspect, target))
continue;
if (last_in_target < e->s_lno + e->num_lines) {
found = true;
last_in_target = e->s_lno + e->num_lines;
}
}
*out = last_in_target;
return found;
}
/*
* It is known that lines between tlno to same came from parent, and e
* has an overlap with that range. it also is known that parent's
* line plno corresponds to e's line tlno.
*
* <---- e ----->
* <------> (entirely within)
* <------------> (extends past)
* <------------> (starts before)
* <------------------> (entirely encloses)
*
* Split e into potentially three parts; before this chunk, the chunk
* to be blamed for the parent, and after that portion.
*/
static void split_overlap(git_blame__entry *split, git_blame__entry *e,
size_t tlno, size_t plno, size_t same, git_blame__origin *parent)
{
size_t chunk_end_lno;
if (e->s_lno < tlno) {
/* there is a pre-chunk part not blamed on the parent */
split[0].suspect = origin_incref(e->suspect);
split[0].lno = e->lno;
split[0].s_lno = e->s_lno;
split[0].num_lines = tlno - e->s_lno;
split[1].lno = e->lno + tlno - e->s_lno;
split[1].s_lno = plno;
} else {
split[1].lno = e->lno;
split[1].s_lno = plno + (e->s_lno - tlno);
}
if (same < e->s_lno + e->num_lines) {
/* there is a post-chunk part not blamed on parent */
split[2].suspect = origin_incref(e->suspect);
split[2].lno = e->lno + (same - e->s_lno);
split[2].s_lno = e->s_lno + (same - e->s_lno);
split[2].num_lines = e->s_lno + e->num_lines - same;
chunk_end_lno = split[2].lno;
} else {
chunk_end_lno = e->lno + e->num_lines;
}
split[1].num_lines = chunk_end_lno - split[1].lno;
/*
* if it turns out there is nothing to blame the parent for, forget about
* the splitting. !split[1].suspect signals this.
*/
if (split[1].num_lines < 1)
return;
split[1].suspect = origin_incref(parent);
}
/*
* Link in a new blame entry to the scoreboard. Entries that cover the same
* line range have been removed from the scoreboard previously.
*/
static void add_blame_entry(git_blame *blame, git_blame__entry *e)
{
git_blame__entry *ent, *prev = NULL;
origin_incref(e->suspect);
for (ent = blame->ent; ent && ent->lno < e->lno; ent = ent->next)
prev = ent;
/* prev, if not NULL, is the last one that is below e */
e->prev = prev;
if (prev) {
e->next = prev->next;
prev->next = e;
} else {
e->next = blame->ent;
blame->ent = e;
}
if (e->next)
e->next->prev = e;
}
/*
* src typically is on-stack; we want to copy the information in it to
* a malloced blame_entry that is already on the linked list of the scoreboard.
* The origin of dst loses a refcnt while the origin of src gains one.
*/
static void dup_entry(git_blame__entry *dst, git_blame__entry *src)
{
git_blame__entry *p, *n;
p = dst->prev;
n = dst->next;
origin_incref(src->suspect);
origin_decref(dst->suspect);
memcpy(dst, src, sizeof(*src));
dst->prev = p;
dst->next = n;
dst->score = 0;
}
/*
* split_overlap() divided an existing blame e into up to three parts in split.
* Adjust the linked list of blames in the scoreboard to reflect the split.
*/
static int split_blame(git_blame *blame, git_blame__entry *split, git_blame__entry *e)
{
git_blame__entry *new_entry;
if (split[0].suspect && split[2].suspect) {
/* The first part (reuse storage for the existing entry e */
dup_entry(e, &split[0]);
/* The last part -- me */
new_entry = git__malloc(sizeof(*new_entry));
GIT_ERROR_CHECK_ALLOC(new_entry);
memcpy(new_entry, &(split[2]), sizeof(git_blame__entry));
add_blame_entry(blame, new_entry);
/* ... and the middle part -- parent */
new_entry = git__malloc(sizeof(*new_entry));
GIT_ERROR_CHECK_ALLOC(new_entry);
memcpy(new_entry, &(split[1]), sizeof(git_blame__entry));
add_blame_entry(blame, new_entry);
} else if (!split[0].suspect && !split[2].suspect) {
/*
* The parent covers the entire area; reuse storage for e and replace it
* with the parent
*/
dup_entry(e, &split[1]);
} else if (split[0].suspect) {
/* me and then parent */
dup_entry(e, &split[0]);
new_entry = git__malloc(sizeof(*new_entry));
GIT_ERROR_CHECK_ALLOC(new_entry);
memcpy(new_entry, &(split[1]), sizeof(git_blame__entry));
add_blame_entry(blame, new_entry);
} else {
/* parent and then me */
dup_entry(e, &split[1]);
new_entry = git__malloc(sizeof(*new_entry));
GIT_ERROR_CHECK_ALLOC(new_entry);
memcpy(new_entry, &(split[2]), sizeof(git_blame__entry));
add_blame_entry(blame, new_entry);
}
return 0;
}
/*
* After splitting the blame, the origins used by the on-stack blame_entry
* should lose one refcnt each.
*/
static void decref_split(git_blame__entry *split)
{
int i;
for (i=0; i<3; i++)
origin_decref(split[i].suspect);
}
/*
* Helper for blame_chunk(). blame_entry e is known to overlap with the patch
* hunk; split it and pass blame to the parent.
*/
static int blame_overlap(
git_blame *blame,
git_blame__entry *e,
size_t tlno,
size_t plno,
size_t same,
git_blame__origin *parent)
{
git_blame__entry split[3] = {{0}};
split_overlap(split, e, tlno, plno, same, parent);
if (split[1].suspect)
if (split_blame(blame, split, e) < 0)
return -1;
decref_split(split);
return 0;
}
/*
* Process one hunk from the patch between the current suspect for blame_entry
* e and its parent. Find and split the overlap, and pass blame to the
* overlapping part to the parent.
*/
static int blame_chunk(
git_blame *blame,
size_t tlno,
size_t plno,
size_t same,
git_blame__origin *target,
git_blame__origin *parent)
{
git_blame__entry *e;
for (e = blame->ent; e; e = e->next) {
if (e->guilty || !same_suspect(e->suspect, target))
continue;
if (same <= e->s_lno)
continue;
if (tlno < e->s_lno + e->num_lines) {
if (blame_overlap(blame, e, tlno, plno, same, parent) < 0)
return -1;
}
}
return 0;
}
static int my_emit(
long start_a, long count_a,
long start_b, long count_b,
void *cb_data)
{
blame_chunk_cb_data *d = (blame_chunk_cb_data *)cb_data;
if (blame_chunk(d->blame, d->tlno, d->plno, start_b, d->target, d->parent) < 0)
return -1;
d->plno = start_a + count_a;
d->tlno = start_b + count_b;
return 0;
}
static void trim_common_tail(mmfile_t *a, mmfile_t *b, long ctx)
{
const int blk = 1024;
long trimmed = 0, recovered = 0;
char *ap = a->ptr + a->size;
char *bp = b->ptr + b->size;
long smaller = (long)((a->size < b->size) ? a->size : b->size);
if (ctx)
return;
while (blk + trimmed <= smaller && !memcmp(ap - blk, bp - blk, blk)) {
trimmed += blk;
ap -= blk;
bp -= blk;
}
while (recovered < trimmed)
if (ap[recovered++] == '\n')
break;
a->size -= trimmed - recovered;
b->size -= trimmed - recovered;
}
static int diff_hunks(mmfile_t file_a, mmfile_t file_b, void *cb_data, git_blame_options *options)
{
xdemitconf_t xecfg = {0};
xdemitcb_t ecb = {0};
xpparam_t xpp = {0};
if (options->flags & GIT_BLAME_IGNORE_WHITESPACE)
xpp.flags |= XDF_IGNORE_WHITESPACE;
xecfg.hunk_func = my_emit;
ecb.priv = cb_data;
trim_common_tail(&file_a, &file_b, 0);
if (file_a.size > GIT_XDIFF_MAX_SIZE ||
file_b.size > GIT_XDIFF_MAX_SIZE) {
git_error_set(GIT_ERROR_INVALID, "file too large to blame");
return -1;
}
return xdl_diff(&file_a, &file_b, &xpp, &xecfg, &ecb);
}
static void fill_origin_blob(git_blame__origin *o, mmfile_t *file)
{
memset(file, 0, sizeof(*file));
if (o->blob) {
file->ptr = (char*)git_blob_rawcontent(o->blob);
file->size = (size_t)git_blob_rawsize(o->blob);
}
}
static int pass_blame_to_parent(
git_blame *blame,
git_blame__origin *target,
git_blame__origin *parent)
{
size_t last_in_target;
mmfile_t file_p, file_o;
blame_chunk_cb_data d = { blame, target, parent, 0, 0 };
if (!find_last_in_target(&last_in_target, blame, target))
return 1; /* nothing remains for this target */
fill_origin_blob(parent, &file_p);
fill_origin_blob(target, &file_o);
if (diff_hunks(file_p, file_o, &d, &blame->options) < 0)
return -1;
/* The reset (i.e. anything after tlno) are the same as the parent */
if (blame_chunk(blame, d.tlno, d.plno, last_in_target, target, parent) < 0)
return -1;
return 0;
}
static int paths_on_dup(void **old, void *new)
{
GIT_UNUSED(old);
git__free(new);
return -1;
}
static git_blame__origin *find_origin(
git_blame *blame,
git_commit *parent,
git_blame__origin *origin)
{
git_blame__origin *porigin = NULL;
git_diff *difflist = NULL;
git_diff_options diffopts = GIT_DIFF_OPTIONS_INIT;
git_tree *otree=NULL, *ptree=NULL;
/* Get the trees from this commit and its parent */
if (0 != git_commit_tree(&otree, origin->commit) ||
0 != git_commit_tree(&ptree, parent))
goto cleanup;
/* Configure the diff */
diffopts.context_lines = 0;
diffopts.flags = GIT_DIFF_SKIP_BINARY_CHECK;
/* Check to see if files we're interested have changed */
diffopts.pathspec.count = blame->paths.length;
diffopts.pathspec.strings = (char**)blame->paths.contents;
if (0 != git_diff_tree_to_tree(&difflist, blame->repository, ptree, otree, &diffopts))
goto cleanup;
if (!git_diff_num_deltas(difflist)) {
/* No changes; copy data */
git_blame__get_origin(&porigin, blame, parent, origin->path);
} else {
git_diff_find_options findopts = GIT_DIFF_FIND_OPTIONS_INIT;
int i;
/* Generate a full diff between the two trees */
git_diff_free(difflist);
diffopts.pathspec.count = 0;
if (0 != git_diff_tree_to_tree(&difflist, blame->repository, ptree, otree, &diffopts))
goto cleanup;
/* Let diff find renames */
findopts.flags = GIT_DIFF_FIND_RENAMES;
if (0 != git_diff_find_similar(difflist, &findopts))
goto cleanup;
/* Find one that matches */
for (i=0; i<(int)git_diff_num_deltas(difflist); i++) {
const git_diff_delta *delta = git_diff_get_delta(difflist, i);
if (!git_vector_bsearch(NULL, &blame->paths, delta->new_file.path))
{
git_vector_insert_sorted(&blame->paths, (void*)git__strdup(delta->old_file.path),
paths_on_dup);
make_origin(&porigin, parent, delta->old_file.path);
}
}
}
cleanup:
git_diff_free(difflist);
git_tree_free(otree);
git_tree_free(ptree);
return porigin;
}
/*
* The blobs of origin and porigin exactly match, so everything origin is
* suspected for can be blamed on the parent.
*/
static int pass_whole_blame(git_blame *blame,
git_blame__origin *origin, git_blame__origin *porigin)
{
git_blame__entry *e;
if (!porigin->blob &&
git_object_lookup((git_object**)&porigin->blob, blame->repository,
git_blob_id(origin->blob), GIT_OBJECT_BLOB) < 0)
return -1;
for (e=blame->ent; e; e=e->next) {
if (!same_suspect(e->suspect, origin))
continue;
origin_incref(porigin);
origin_decref(e->suspect);
e->suspect = porigin;
}
return 0;
}
static int pass_blame(git_blame *blame, git_blame__origin *origin, uint32_t opt)
{
git_commit *commit = origin->commit;
int i, num_parents;
git_blame__origin *sg_buf[16];
git_blame__origin *porigin, **sg_origin = sg_buf;
int ret, error = 0;
num_parents = git_commit_parentcount(commit);
if (!git_oid_cmp(git_commit_id(commit), &blame->options.oldest_commit))
/* Stop at oldest specified commit */
num_parents = 0;
else if (opt & GIT_BLAME_FIRST_PARENT && num_parents > 1)
/* Limit search to the first parent */
num_parents = 1;
if (!num_parents) {
git_oid_cpy(&blame->options.oldest_commit, git_commit_id(commit));
goto finish;
} else if (num_parents < (int)ARRAY_SIZE(sg_buf))
memset(sg_buf, 0, sizeof(sg_buf));
else {
sg_origin = git__calloc(num_parents, sizeof(*sg_origin));
GIT_ERROR_CHECK_ALLOC(sg_origin);
}
for (i=0; i<num_parents; i++) {
git_commit *p;
int j, same;
if (sg_origin[i])
continue;
if ((error = git_commit_parent(&p, origin->commit, i)) < 0)
goto finish;
porigin = find_origin(blame, p, origin);
if (!porigin) {
/*
* We only have to decrement the parent's
* reference count when no porigin has
* been created, as otherwise the commit
* is assigned to the created object.
*/
git_commit_free(p);
continue;
}
if (porigin->blob && origin->blob &&
!git_oid_cmp(git_blob_id(porigin->blob), git_blob_id(origin->blob))) {
error = pass_whole_blame(blame, origin, porigin);
origin_decref(porigin);
goto finish;
}
for (j = same = 0; j<i; j++)
if (sg_origin[j] &&
!git_oid_cmp(git_blob_id(sg_origin[j]->blob), git_blob_id(porigin->blob))) {
same = 1;
break;
}
if (!same)
sg_origin[i] = porigin;
else
origin_decref(porigin);
}
/* Standard blame */
for (i=0; i<num_parents; i++) {
git_blame__origin *porigin = sg_origin[i];
if (!porigin)
continue;
if (!origin->previous) {
origin_incref(porigin);
origin->previous = porigin;
}
if ((ret = pass_blame_to_parent(blame, origin, porigin)) != 0) {
if (ret < 0)
error = -1;
goto finish;
}
}
/* TODO: optionally find moves in parents' files */
/* TODO: optionally find copies in parents' files */
finish:
for (i=0; i<num_parents; i++)
if (sg_origin[i])
origin_decref(sg_origin[i]);
if (sg_origin != sg_buf)
git__free(sg_origin);
return error;
}
/*
* If two blame entries that are next to each other came from
* contiguous lines in the same origin (i.e. <commit, path> pair),
* merge them together.
*/
static void coalesce(git_blame *blame)
{
git_blame__entry *ent, *next;
for (ent=blame->ent; ent && (next = ent->next); ent = next) {
if (same_suspect(ent->suspect, next->suspect) &&
ent->guilty == next->guilty &&
ent->s_lno + ent->num_lines == next->s_lno)
{
ent->num_lines += next->num_lines;
ent->next = next->next;
if (ent->next)
ent->next->prev = ent;
origin_decref(next->suspect);
git__free(next);
ent->score = 0;
next = ent; /* again */
}
}
}
int git_blame__like_git(git_blame *blame, uint32_t opt)
{
int error = 0;
while (true) {
git_blame__entry *ent;
git_blame__origin *suspect = NULL;
/* Find a suspect to break down */
for (ent = blame->ent; !suspect && ent; ent = ent->next)
if (!ent->guilty)
suspect = ent->suspect;
if (!suspect)
break;
/* We'll use this suspect later in the loop, so hold on to it for now. */
origin_incref(suspect);
if ((error = pass_blame(blame, suspect, opt)) < 0)
break;
/* Take responsibility for the remaining entries */
for (ent = blame->ent; ent; ent = ent->next) {
if (same_suspect(ent->suspect, suspect)) {
ent->guilty = true;
ent->is_boundary = !git_oid_cmp(
git_commit_id(suspect->commit),
&blame->options.oldest_commit);
}
}
origin_decref(suspect);
}
if (!error)
coalesce(blame);
return error;
}
void git_blame__free_entry(git_blame__entry *ent)
{
if (!ent) return;
origin_decref(ent->suspect);
git__free(ent);
}
|
0 |
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2
|
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2/src/settings.h
|
/*
* Copyright (C) the libgit2 contributors. All rights reserved.
*
* This file is part of libgit2, distributed under the GNU GPL v2 with
* a Linking Exception. For full terms see the included COPYING file.
*/
extern int git_settings_global_init(void);
extern const char *git_libgit2__user_agent(void);
extern const char *git_libgit2__ssl_ciphers(void);
|
0 |
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2
|
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2/src/blame_git.h
|
/*
* Copyright (C) the libgit2 contributors. All rights reserved.
*
* This file is part of libgit2, distributed under the GNU GPL v2 with
* a Linking Exception. For full terms see the included COPYING file.
*/
#ifndef INCLUDE_blame_git__
#define INCLUDE_blame_git__
#include "common.h"
#include "blame.h"
int git_blame__get_origin(
git_blame__origin **out,
git_blame *sb,
git_commit *commit,
const char *path);
void git_blame__free_entry(git_blame__entry *ent);
int git_blame__like_git(git_blame *sb, uint32_t flags);
#endif
|
0 |
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2
|
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2/src/alloc.c
|
/*
* Copyright (C) the libgit2 contributors. All rights reserved.
*
* This file is part of libgit2, distributed under the GNU GPL v2 with
* a Linking Exception. For full terms see the included COPYING file.
*/
#include "alloc.h"
#include "runtime.h"
#include "allocators/failalloc.h"
#include "allocators/stdalloc.h"
#include "allocators/win32_leakcheck.h"
/* Fail any allocation until git_libgit2_init is called. */
git_allocator git__allocator = {
git_failalloc_malloc,
git_failalloc_calloc,
git_failalloc_strdup,
git_failalloc_strndup,
git_failalloc_substrdup,
git_failalloc_realloc,
git_failalloc_reallocarray,
git_failalloc_mallocarray,
git_failalloc_free
};
static int setup_default_allocator(void)
{
#if defined(GIT_WIN32_LEAKCHECK)
return git_win32_leakcheck_init_allocator(&git__allocator);
#else
return git_stdalloc_init_allocator(&git__allocator);
#endif
}
int git_allocator_global_init(void)
{
/*
* We don't want to overwrite any allocator which has been set
* before the init function is called.
*/
if (git__allocator.gmalloc != git_failalloc_malloc)
return 0;
return setup_default_allocator();
}
int git_allocator_setup(git_allocator *allocator)
{
if (!allocator)
return setup_default_allocator();
memcpy(&git__allocator, allocator, sizeof(*allocator));
return 0;
}
|
0 |
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2
|
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2/src/diff.c
|
/*
* Copyright (C) the libgit2 contributors. All rights reserved.
*
* This file is part of libgit2, distributed under the GNU GPL v2 with
* a Linking Exception. For full terms see the included COPYING file.
*/
#include "diff.h"
#include "common.h"
#include "patch.h"
#include "email.h"
#include "commit.h"
#include "index.h"
#include "diff_generate.h"
#include "git2/version.h"
#include "git2/email.h"
struct patch_id_args {
git_hash_ctx ctx;
git_oid result;
int first_file;
};
GIT_INLINE(const char *) diff_delta__path(const git_diff_delta *delta)
{
const char *str = delta->old_file.path;
if (!str ||
delta->status == GIT_DELTA_ADDED ||
delta->status == GIT_DELTA_RENAMED ||
delta->status == GIT_DELTA_COPIED)
str = delta->new_file.path;
return str;
}
int git_diff_delta__cmp(const void *a, const void *b)
{
const git_diff_delta *da = a, *db = b;
int val = strcmp(diff_delta__path(da), diff_delta__path(db));
return val ? val : ((int)da->status - (int)db->status);
}
int git_diff_delta__casecmp(const void *a, const void *b)
{
const git_diff_delta *da = a, *db = b;
int val = strcasecmp(diff_delta__path(da), diff_delta__path(db));
return val ? val : ((int)da->status - (int)db->status);
}
int git_diff__entry_cmp(const void *a, const void *b)
{
const git_index_entry *entry_a = a;
const git_index_entry *entry_b = b;
return strcmp(entry_a->path, entry_b->path);
}
int git_diff__entry_icmp(const void *a, const void *b)
{
const git_index_entry *entry_a = a;
const git_index_entry *entry_b = b;
return strcasecmp(entry_a->path, entry_b->path);
}
void git_diff_free(git_diff *diff)
{
if (!diff)
return;
GIT_REFCOUNT_DEC(diff, diff->free_fn);
}
void git_diff_addref(git_diff *diff)
{
GIT_REFCOUNT_INC(diff);
}
size_t git_diff_num_deltas(const git_diff *diff)
{
GIT_ASSERT_ARG(diff);
return diff->deltas.length;
}
size_t git_diff_num_deltas_of_type(const git_diff *diff, git_delta_t type)
{
size_t i, count = 0;
const git_diff_delta *delta;
GIT_ASSERT_ARG(diff);
git_vector_foreach(&diff->deltas, i, delta) {
count += (delta->status == type);
}
return count;
}
const git_diff_delta *git_diff_get_delta(const git_diff *diff, size_t idx)
{
GIT_ASSERT_ARG_WITH_RETVAL(diff, NULL);
return git_vector_get(&diff->deltas, idx);
}
int git_diff_is_sorted_icase(const git_diff *diff)
{
return (diff->opts.flags & GIT_DIFF_IGNORE_CASE) != 0;
}
int git_diff_get_perfdata(git_diff_perfdata *out, const git_diff *diff)
{
GIT_ASSERT_ARG(out);
GIT_ERROR_CHECK_VERSION(out, GIT_DIFF_PERFDATA_VERSION, "git_diff_perfdata");
out->stat_calls = diff->perf.stat_calls;
out->oid_calculations = diff->perf.oid_calculations;
return 0;
}
int git_diff_foreach(
git_diff *diff,
git_diff_file_cb file_cb,
git_diff_binary_cb binary_cb,
git_diff_hunk_cb hunk_cb,
git_diff_line_cb data_cb,
void *payload)
{
int error = 0;
git_diff_delta *delta;
size_t idx;
GIT_ASSERT_ARG(diff);
git_vector_foreach(&diff->deltas, idx, delta) {
git_patch *patch;
/* check flags against patch status */
if (git_diff_delta__should_skip(&diff->opts, delta))
continue;
if ((error = git_patch_from_diff(&patch, diff, idx)) != 0)
break;
error = git_patch__invoke_callbacks(patch, file_cb, binary_cb,
hunk_cb, data_cb, payload);
git_patch_free(patch);
if (error)
break;
}
return error;
}
#ifndef GIT_DEPRECATE_HARD
int git_diff_format_email(
git_buf *out,
git_diff *diff,
const git_diff_format_email_options *opts)
{
git_email_create_options email_create_opts = GIT_EMAIL_CREATE_OPTIONS_INIT;
int error;
GIT_ASSERT_ARG(out);
GIT_ASSERT_ARG(diff);
GIT_ASSERT_ARG(opts && opts->summary && opts->id && opts->author);
GIT_ERROR_CHECK_VERSION(opts,
GIT_DIFF_FORMAT_EMAIL_OPTIONS_VERSION,
"git_format_email_options");
if ((opts->flags & GIT_DIFF_FORMAT_EMAIL_EXCLUDE_SUBJECT_PATCH_MARKER) != 0)
email_create_opts.subject_prefix = "";
error = git_email__append_from_diff(out, diff, opts->patch_no,
opts->total_patches, opts->id, opts->summary, opts->body,
opts->author, &email_create_opts);
return error;
}
int git_diff_commit_as_email(
git_buf *out,
git_repository *repo,
git_commit *commit,
size_t patch_no,
size_t total_patches,
uint32_t flags,
const git_diff_options *diff_opts)
{
git_diff *diff = NULL;
git_email_create_options opts = GIT_EMAIL_CREATE_OPTIONS_INIT;
const git_oid *commit_id;
const char *summary, *body;
const git_signature *author;
int error;
GIT_ASSERT_ARG(out);
GIT_ASSERT_ARG(repo);
GIT_ASSERT_ARG(commit);
commit_id = git_commit_id(commit);
summary = git_commit_summary(commit);
body = git_commit_body(commit);
author = git_commit_author(commit);
if ((flags & GIT_DIFF_FORMAT_EMAIL_EXCLUDE_SUBJECT_PATCH_MARKER) != 0)
opts.subject_prefix = "";
if ((error = git_diff__commit(&diff, repo, commit, diff_opts)) < 0)
return error;
error = git_email_create_from_diff(out, diff, patch_no, total_patches, commit_id, summary, body, author, &opts);
git_diff_free(diff);
return error;
}
int git_diff_init_options(git_diff_options *opts, unsigned int version)
{
return git_diff_options_init(opts, version);
}
int git_diff_find_init_options(
git_diff_find_options *opts, unsigned int version)
{
return git_diff_find_options_init(opts, version);
}
int git_diff_format_email_options_init(
git_diff_format_email_options *opts, unsigned int version)
{
GIT_INIT_STRUCTURE_FROM_TEMPLATE(
opts, version, git_diff_format_email_options,
GIT_DIFF_FORMAT_EMAIL_OPTIONS_INIT);
return 0;
}
int git_diff_format_email_init_options(
git_diff_format_email_options *opts, unsigned int version)
{
return git_diff_format_email_options_init(opts, version);
}
#endif
int git_diff_options_init(git_diff_options *opts, unsigned int version)
{
GIT_INIT_STRUCTURE_FROM_TEMPLATE(
opts, version, git_diff_options, GIT_DIFF_OPTIONS_INIT);
return 0;
}
int git_diff_find_options_init(
git_diff_find_options *opts, unsigned int version)
{
GIT_INIT_STRUCTURE_FROM_TEMPLATE(
opts, version, git_diff_find_options, GIT_DIFF_FIND_OPTIONS_INIT);
return 0;
}
static int flush_hunk(git_oid *result, git_hash_ctx *ctx)
{
git_oid hash;
unsigned short carry = 0;
int error, i;
if ((error = git_hash_final(&hash, ctx)) < 0 ||
(error = git_hash_init(ctx)) < 0)
return error;
for (i = 0; i < GIT_OID_RAWSZ; i++) {
carry += result->id[i] + hash.id[i];
result->id[i] = (unsigned char)carry;
carry >>= 8;
}
return 0;
}
static void strip_spaces(git_buf *buf)
{
char *src = buf->ptr, *dst = buf->ptr;
char c;
size_t len = 0;
while ((c = *src++) != '\0') {
if (!git__isspace(c)) {
*dst++ = c;
len++;
}
}
git_buf_truncate(buf, len);
}
static int diff_patchid_print_callback_to_buf(
const git_diff_delta *delta,
const git_diff_hunk *hunk,
const git_diff_line *line,
void *payload)
{
struct patch_id_args *args = (struct patch_id_args *) payload;
git_buf buf = GIT_BUF_INIT;
int error = 0;
if (line->origin == GIT_DIFF_LINE_CONTEXT_EOFNL ||
line->origin == GIT_DIFF_LINE_ADD_EOFNL ||
line->origin == GIT_DIFF_LINE_DEL_EOFNL)
goto out;
if ((error = git_diff_print_callback__to_buf(delta, hunk,
line, &buf)) < 0)
goto out;
strip_spaces(&buf);
if (line->origin == GIT_DIFF_LINE_FILE_HDR &&
!args->first_file &&
(error = flush_hunk(&args->result, &args->ctx) < 0))
goto out;
if ((error = git_hash_update(&args->ctx, buf.ptr, buf.size)) < 0)
goto out;
if (line->origin == GIT_DIFF_LINE_FILE_HDR && args->first_file)
args->first_file = 0;
out:
git_buf_dispose(&buf);
return error;
}
int git_diff_patchid_options_init(git_diff_patchid_options *opts, unsigned int version)
{
GIT_INIT_STRUCTURE_FROM_TEMPLATE(
opts, version, git_diff_patchid_options, GIT_DIFF_PATCHID_OPTIONS_INIT);
return 0;
}
int git_diff_patchid(git_oid *out, git_diff *diff, git_diff_patchid_options *opts)
{
struct patch_id_args args;
int error;
GIT_ERROR_CHECK_VERSION(
opts, GIT_DIFF_PATCHID_OPTIONS_VERSION, "git_diff_patchid_options");
memset(&args, 0, sizeof(args));
args.first_file = 1;
if ((error = git_hash_ctx_init(&args.ctx)) < 0)
goto out;
if ((error = git_diff_print(diff,
GIT_DIFF_FORMAT_PATCH_ID,
diff_patchid_print_callback_to_buf,
&args)) < 0)
goto out;
if ((error = (flush_hunk(&args.result, &args.ctx))) < 0)
goto out;
git_oid_cpy(out, &args.result);
out:
git_hash_ctx_cleanup(&args.ctx);
return error;
}
|
0 |
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2
|
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2/src/cache.c
|
/*
* Copyright (C) the libgit2 contributors. All rights reserved.
*
* This file is part of libgit2, distributed under the GNU GPL v2 with
* a Linking Exception. For full terms see the included COPYING file.
*/
#include "cache.h"
#include "repository.h"
#include "commit.h"
#include "thread.h"
#include "util.h"
#include "odb.h"
#include "object.h"
#include "git2/oid.h"
bool git_cache__enabled = true;
ssize_t git_cache__max_storage = (256 * 1024 * 1024);
git_atomic_ssize git_cache__current_storage = {0};
static size_t git_cache__max_object_size[8] = {
0, /* GIT_OBJECT__EXT1 */
4096, /* GIT_OBJECT_COMMIT */
4096, /* GIT_OBJECT_TREE */
0, /* GIT_OBJECT_BLOB */
4096, /* GIT_OBJECT_TAG */
0, /* GIT_OBJECT__EXT2 */
0, /* GIT_OBJECT_OFS_DELTA */
0 /* GIT_OBJECT_REF_DELTA */
};
int git_cache_set_max_object_size(git_object_t type, size_t size)
{
if (type < 0 || (size_t)type >= ARRAY_SIZE(git_cache__max_object_size)) {
git_error_set(GIT_ERROR_INVALID, "type out of range");
return -1;
}
git_cache__max_object_size[type] = size;
return 0;
}
int git_cache_init(git_cache *cache)
{
memset(cache, 0, sizeof(*cache));
if ((git_oidmap_new(&cache->map)) < 0)
return -1;
if (git_rwlock_init(&cache->lock)) {
git_error_set(GIT_ERROR_OS, "failed to initialize cache rwlock");
return -1;
}
return 0;
}
/* called with lock */
static void clear_cache(git_cache *cache)
{
git_cached_obj *evict = NULL;
if (git_cache_size(cache) == 0)
return;
git_oidmap_foreach_value(cache->map, evict, {
git_cached_obj_decref(evict);
});
git_oidmap_clear(cache->map);
git_atomic_ssize_add(&git_cache__current_storage, -cache->used_memory);
cache->used_memory = 0;
}
void git_cache_clear(git_cache *cache)
{
if (git_rwlock_wrlock(&cache->lock) < 0)
return;
clear_cache(cache);
git_rwlock_wrunlock(&cache->lock);
}
void git_cache_dispose(git_cache *cache)
{
git_cache_clear(cache);
git_oidmap_free(cache->map);
git_rwlock_free(&cache->lock);
git__memzero(cache, sizeof(*cache));
}
/* Called with lock */
static void cache_evict_entries(git_cache *cache)
{
size_t evict_count = git_cache_size(cache) / 2048, i;
ssize_t evicted_memory = 0;
if (evict_count < 8)
evict_count = 8;
/* do not infinite loop if there's not enough entries to evict */
if (evict_count > git_cache_size(cache)) {
clear_cache(cache);
return;
}
i = 0;
while (evict_count > 0) {
git_cached_obj *evict;
const git_oid *key;
if (git_oidmap_iterate((void **) &evict, cache->map, &i, &key) == GIT_ITEROVER)
break;
evict_count--;
evicted_memory += evict->size;
git_oidmap_delete(cache->map, key);
git_cached_obj_decref(evict);
}
cache->used_memory -= evicted_memory;
git_atomic_ssize_add(&git_cache__current_storage, -evicted_memory);
}
static bool cache_should_store(git_object_t object_type, size_t object_size)
{
size_t max_size = git_cache__max_object_size[object_type];
return git_cache__enabled && object_size < max_size;
}
static void *cache_get(git_cache *cache, const git_oid *oid, unsigned int flags)
{
git_cached_obj *entry;
if (!git_cache__enabled || git_rwlock_rdlock(&cache->lock) < 0)
return NULL;
if ((entry = git_oidmap_get(cache->map, oid)) != NULL) {
if (flags && entry->flags != flags) {
entry = NULL;
} else {
git_cached_obj_incref(entry);
}
}
git_rwlock_rdunlock(&cache->lock);
return entry;
}
static void *cache_store(git_cache *cache, git_cached_obj *entry)
{
git_cached_obj *stored_entry;
git_cached_obj_incref(entry);
if (!git_cache__enabled && cache->used_memory > 0) {
git_cache_clear(cache);
return entry;
}
if (!cache_should_store(entry->type, entry->size))
return entry;
if (git_rwlock_wrlock(&cache->lock) < 0)
return entry;
/* soften the load on the cache */
if (git_atomic_ssize_get(&git_cache__current_storage) > git_cache__max_storage)
cache_evict_entries(cache);
/* not found */
if ((stored_entry = git_oidmap_get(cache->map, &entry->oid)) == NULL) {
if (git_oidmap_set(cache->map, &entry->oid, entry) == 0) {
git_cached_obj_incref(entry);
cache->used_memory += entry->size;
git_atomic_ssize_add(&git_cache__current_storage, (ssize_t)entry->size);
}
}
/* found */
else {
if (stored_entry->flags == entry->flags) {
git_cached_obj_decref(entry);
git_cached_obj_incref(stored_entry);
entry = stored_entry;
} else if (stored_entry->flags == GIT_CACHE_STORE_RAW &&
entry->flags == GIT_CACHE_STORE_PARSED) {
if (git_oidmap_set(cache->map, &entry->oid, entry) == 0) {
git_cached_obj_decref(stored_entry);
git_cached_obj_incref(entry);
} else {
git_cached_obj_decref(entry);
git_cached_obj_incref(stored_entry);
entry = stored_entry;
}
} else {
/* NO OP */
}
}
git_rwlock_wrunlock(&cache->lock);
return entry;
}
void *git_cache_store_raw(git_cache *cache, git_odb_object *entry)
{
entry->cached.flags = GIT_CACHE_STORE_RAW;
return cache_store(cache, (git_cached_obj *)entry);
}
void *git_cache_store_parsed(git_cache *cache, git_object *entry)
{
entry->cached.flags = GIT_CACHE_STORE_PARSED;
return cache_store(cache, (git_cached_obj *)entry);
}
git_odb_object *git_cache_get_raw(git_cache *cache, const git_oid *oid)
{
return cache_get(cache, oid, GIT_CACHE_STORE_RAW);
}
git_object *git_cache_get_parsed(git_cache *cache, const git_oid *oid)
{
return cache_get(cache, oid, GIT_CACHE_STORE_PARSED);
}
void *git_cache_get_any(git_cache *cache, const git_oid *oid)
{
return cache_get(cache, oid, GIT_CACHE_STORE_ANY);
}
void git_cached_obj_decref(void *_obj)
{
git_cached_obj *obj = _obj;
if (git_atomic32_dec(&obj->refcount) == 0) {
switch (obj->flags) {
case GIT_CACHE_STORE_RAW:
git_odb_object__free(_obj);
break;
case GIT_CACHE_STORE_PARSED:
git_object__free(_obj);
break;
default:
git__free(_obj);
break;
}
}
}
|
0 |
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2
|
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2/src/ignore.h
|
/*
* Copyright (C) the libgit2 contributors. All rights reserved.
*
* This file is part of libgit2, distributed under the GNU GPL v2 with
* a Linking Exception. For full terms see the included COPYING file.
*/
#ifndef INCLUDE_ignore_h__
#define INCLUDE_ignore_h__
#include "common.h"
#include "repository.h"
#include "vector.h"
#include "attr_file.h"
#define GIT_IGNORE_FILE ".gitignore"
#define GIT_IGNORE_FILE_INREPO "exclude"
#define GIT_IGNORE_FILE_XDG "ignore"
/* The git_ignores structure maintains three sets of ignores:
* - internal ignores
* - per directory ignores
* - global ignores (at lower priority than the others)
* As you traverse from one directory to another, you can push and pop
* directories onto git_ignores list efficiently.
*/
typedef struct {
git_repository *repo;
git_buf dir; /* current directory reflected in ign_path */
git_attr_file *ign_internal;
git_vector ign_path;
git_vector ign_global;
size_t dir_root; /* offset in dir to repo root */
int ignore_case;
int depth;
} git_ignores;
extern int git_ignore__for_path(
git_repository *repo, const char *path, git_ignores *ign);
extern int git_ignore__push_dir(git_ignores *ign, const char *dir);
extern int git_ignore__pop_dir(git_ignores *ign);
extern void git_ignore__free(git_ignores *ign);
enum {
GIT_IGNORE_UNCHECKED = -2,
GIT_IGNORE_NOTFOUND = -1,
GIT_IGNORE_FALSE = 0,
GIT_IGNORE_TRUE = 1,
};
extern int git_ignore__lookup(int *out, git_ignores *ign, const char *path, git_dir_flag dir_flag);
/* command line Git sometimes generates an error message if given a
* pathspec that contains an exact match to an ignored file (provided
* --force isn't also given). This makes it easy to check it that has
* happened. Returns GIT_EINVALIDSPEC if the pathspec contains ignored
* exact matches (that are not already present in the index).
*/
extern int git_ignore__check_pathspec_for_exact_ignores(
git_repository *repo, git_vector *pathspec, bool no_fnmatch);
#endif
|
0 |
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2
|
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2/src/annotated_commit.h
|
/*
* Copyright (C) the libgit2 contributors. All rights reserved.
*
* This file is part of libgit2, distributed under the GNU GPL v2 with
* a Linking Exception. For full terms see the included COPYING file.
*/
#ifndef INCLUDE_annotated_commit_h__
#define INCLUDE_annotated_commit_h__
#include "common.h"
#include "oidarray.h"
#include "git2/oid.h"
typedef enum {
GIT_ANNOTATED_COMMIT_REAL = 1,
GIT_ANNOTATED_COMMIT_VIRTUAL = 2,
} git_annotated_commit_t;
/**
* Internal structure for merge inputs. An annotated commit is generally
* "real" and backed by an actual commit in the repository, but merge will
* internally create "virtual" commits that are in-memory intermediate
* commits backed by an index.
*/
struct git_annotated_commit {
git_annotated_commit_t type;
/* real commit */
git_commit *commit;
git_tree *tree;
/* virtual commit structure */
git_index *index;
git_array_oid_t parents;
/* how this commit was looked up */
const char *description;
const char *ref_name;
const char *remote_url;
char id_str[GIT_OID_HEXSZ+1];
};
extern int git_annotated_commit_from_head(git_annotated_commit **out,
git_repository *repo);
extern int git_annotated_commit_from_commit(git_annotated_commit **out,
git_commit *commit);
#endif
|
0 |
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2
|
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2/src/refs.c
|
/*
* Copyright (C) the libgit2 contributors. All rights reserved.
*
* This file is part of libgit2, distributed under the GNU GPL v2 with
* a Linking Exception. For full terms see the included COPYING file.
*/
#include "refs.h"
#include "hash.h"
#include "repository.h"
#include "futils.h"
#include "filebuf.h"
#include "pack.h"
#include "reflog.h"
#include "refdb.h"
#include <git2/tag.h>
#include <git2/object.h>
#include <git2/oid.h>
#include <git2/branch.h>
#include <git2/refs.h>
#include <git2/refdb.h>
#include <git2/sys/refs.h>
#include <git2/signature.h>
#include <git2/commit.h>
bool git_reference__enable_symbolic_ref_target_validation = true;
enum {
GIT_PACKREF_HAS_PEEL = 1,
GIT_PACKREF_WAS_LOOSE = 2
};
static git_reference *alloc_ref(const char *name)
{
git_reference *ref = NULL;
size_t namelen = strlen(name), reflen;
if (!GIT_ADD_SIZET_OVERFLOW(&reflen, sizeof(git_reference), namelen) &&
!GIT_ADD_SIZET_OVERFLOW(&reflen, reflen, 1) &&
(ref = git__calloc(1, reflen)) != NULL)
memcpy(ref->name, name, namelen + 1);
return ref;
}
git_reference *git_reference__alloc_symbolic(
const char *name, const char *target)
{
git_reference *ref;
GIT_ASSERT_ARG_WITH_RETVAL(name, NULL);
GIT_ASSERT_ARG_WITH_RETVAL(target, NULL);
ref = alloc_ref(name);
if (!ref)
return NULL;
ref->type = GIT_REFERENCE_SYMBOLIC;
if ((ref->target.symbolic = git__strdup(target)) == NULL) {
git__free(ref);
return NULL;
}
return ref;
}
git_reference *git_reference__alloc(
const char *name,
const git_oid *oid,
const git_oid *peel)
{
git_reference *ref;
GIT_ASSERT_ARG_WITH_RETVAL(name, NULL);
GIT_ASSERT_ARG_WITH_RETVAL(oid, NULL);
ref = alloc_ref(name);
if (!ref)
return NULL;
ref->type = GIT_REFERENCE_DIRECT;
git_oid_cpy(&ref->target.oid, oid);
if (peel != NULL)
git_oid_cpy(&ref->peel, peel);
return ref;
}
git_reference *git_reference__realloc(
git_reference **ptr_to_ref, const char *name)
{
size_t namelen, reflen;
git_reference *rewrite = NULL;
GIT_ASSERT_ARG_WITH_RETVAL(ptr_to_ref, NULL);
GIT_ASSERT_ARG_WITH_RETVAL(name, NULL);
namelen = strlen(name);
if (!GIT_ADD_SIZET_OVERFLOW(&reflen, sizeof(git_reference), namelen) &&
!GIT_ADD_SIZET_OVERFLOW(&reflen, reflen, 1) &&
(rewrite = git__realloc(*ptr_to_ref, reflen)) != NULL)
memcpy(rewrite->name, name, namelen + 1);
*ptr_to_ref = NULL;
return rewrite;
}
int git_reference_dup(git_reference **dest, git_reference *source)
{
if (source->type == GIT_REFERENCE_SYMBOLIC)
*dest = git_reference__alloc_symbolic(source->name, source->target.symbolic);
else
*dest = git_reference__alloc(source->name, &source->target.oid, &source->peel);
GIT_ERROR_CHECK_ALLOC(*dest);
(*dest)->db = source->db;
GIT_REFCOUNT_INC((*dest)->db);
return 0;
}
void git_reference_free(git_reference *reference)
{
if (reference == NULL)
return;
if (reference->type == GIT_REFERENCE_SYMBOLIC)
git__free(reference->target.symbolic);
if (reference->db)
GIT_REFCOUNT_DEC(reference->db, git_refdb__free);
git__free(reference);
}
int git_reference_delete(git_reference *ref)
{
const git_oid *old_id = NULL;
const char *old_target = NULL;
if (!strcmp(ref->name, "HEAD")) {
git_error_set(GIT_ERROR_REFERENCE, "cannot delete HEAD");
return GIT_ERROR;
}
if (ref->type == GIT_REFERENCE_DIRECT)
old_id = &ref->target.oid;
else
old_target = ref->target.symbolic;
return git_refdb_delete(ref->db, ref->name, old_id, old_target);
}
int git_reference_remove(git_repository *repo, const char *name)
{
git_refdb *db;
int error;
if ((error = git_repository_refdb__weakptr(&db, repo)) < 0)
return error;
return git_refdb_delete(db, name, NULL, NULL);
}
int git_reference_lookup(git_reference **ref_out,
git_repository *repo, const char *name)
{
return git_reference_lookup_resolved(ref_out, repo, name, 0);
}
int git_reference_name_to_id(
git_oid *out, git_repository *repo, const char *name)
{
int error;
git_reference *ref;
if ((error = git_reference_lookup_resolved(&ref, repo, name, -1)) < 0)
return error;
git_oid_cpy(out, git_reference_target(ref));
git_reference_free(ref);
return 0;
}
static int reference_normalize_for_repo(
git_refname_t out,
git_repository *repo,
const char *name,
bool validate)
{
int precompose;
unsigned int flags = GIT_REFERENCE_FORMAT_ALLOW_ONELEVEL;
if (!git_repository__configmap_lookup(&precompose, repo, GIT_CONFIGMAP_PRECOMPOSE) &&
precompose)
flags |= GIT_REFERENCE_FORMAT__PRECOMPOSE_UNICODE;
if (!validate)
flags |= GIT_REFERENCE_FORMAT__VALIDATION_DISABLE;
return git_reference_normalize_name(out, GIT_REFNAME_MAX, name, flags);
}
int git_reference_lookup_resolved(
git_reference **ref_out,
git_repository *repo,
const char *name,
int max_nesting)
{
git_refname_t normalized;
git_refdb *refdb;
int error = 0;
GIT_ASSERT_ARG(ref_out);
GIT_ASSERT_ARG(repo);
GIT_ASSERT_ARG(name);
if ((error = reference_normalize_for_repo(normalized, repo, name, true)) < 0 ||
(error = git_repository_refdb__weakptr(&refdb, repo)) < 0 ||
(error = git_refdb_resolve(ref_out, refdb, normalized, max_nesting)) < 0)
return error;
/*
* The resolved reference may be a symbolic reference in case its
* target doesn't exist. If the user asked us to resolve (e.g.
* `max_nesting != 0`), then we need to return an error in case we got
* a symbolic reference back.
*/
if (max_nesting && git_reference_type(*ref_out) == GIT_REFERENCE_SYMBOLIC) {
git_reference_free(*ref_out);
*ref_out = NULL;
return GIT_ENOTFOUND;
}
return 0;
}
int git_reference_dwim(git_reference **out, git_repository *repo, const char *refname)
{
int error = 0, i, valid;
bool fallbackmode = true, foundvalid = false;
git_reference *ref;
git_buf refnamebuf = GIT_BUF_INIT, name = GIT_BUF_INIT;
static const char *formatters[] = {
"%s",
GIT_REFS_DIR "%s",
GIT_REFS_TAGS_DIR "%s",
GIT_REFS_HEADS_DIR "%s",
GIT_REFS_REMOTES_DIR "%s",
GIT_REFS_REMOTES_DIR "%s/" GIT_HEAD_FILE,
NULL
};
if (*refname)
git_buf_puts(&name, refname);
else {
git_buf_puts(&name, GIT_HEAD_FILE);
fallbackmode = false;
}
for (i = 0; formatters[i] && (fallbackmode || i == 0); i++) {
git_buf_clear(&refnamebuf);
if ((error = git_buf_printf(&refnamebuf, formatters[i], git_buf_cstr(&name))) < 0 ||
(error = git_reference_name_is_valid(&valid, git_buf_cstr(&refnamebuf))) < 0)
goto cleanup;
if (!valid) {
error = GIT_EINVALIDSPEC;
continue;
}
foundvalid = true;
error = git_reference_lookup_resolved(&ref, repo, git_buf_cstr(&refnamebuf), -1);
if (!error) {
*out = ref;
error = 0;
goto cleanup;
}
if (error != GIT_ENOTFOUND)
goto cleanup;
}
cleanup:
if (error && !foundvalid) {
/* never found a valid reference name */
git_error_set(GIT_ERROR_REFERENCE,
"could not use '%s' as valid reference name", git_buf_cstr(&name));
}
if (error == GIT_ENOTFOUND)
git_error_set(GIT_ERROR_REFERENCE, "no reference found for shorthand '%s'", refname);
git_buf_dispose(&name);
git_buf_dispose(&refnamebuf);
return error;
}
/**
* Getters
*/
git_reference_t git_reference_type(const git_reference *ref)
{
GIT_ASSERT_ARG(ref);
return ref->type;
}
const char *git_reference_name(const git_reference *ref)
{
GIT_ASSERT_ARG_WITH_RETVAL(ref, NULL);
return ref->name;
}
git_repository *git_reference_owner(const git_reference *ref)
{
GIT_ASSERT_ARG_WITH_RETVAL(ref, NULL);
return ref->db->repo;
}
const git_oid *git_reference_target(const git_reference *ref)
{
GIT_ASSERT_ARG_WITH_RETVAL(ref, NULL);
if (ref->type != GIT_REFERENCE_DIRECT)
return NULL;
return &ref->target.oid;
}
const git_oid *git_reference_target_peel(const git_reference *ref)
{
GIT_ASSERT_ARG_WITH_RETVAL(ref, NULL);
if (ref->type != GIT_REFERENCE_DIRECT || git_oid_is_zero(&ref->peel))
return NULL;
return &ref->peel;
}
const char *git_reference_symbolic_target(const git_reference *ref)
{
GIT_ASSERT_ARG_WITH_RETVAL(ref, NULL);
if (ref->type != GIT_REFERENCE_SYMBOLIC)
return NULL;
return ref->target.symbolic;
}
static int reference__create(
git_reference **ref_out,
git_repository *repo,
const char *name,
const git_oid *oid,
const char *symbolic,
int force,
const git_signature *signature,
const char *log_message,
const git_oid *old_id,
const char *old_target)
{
git_refname_t normalized;
git_refdb *refdb;
git_reference *ref = NULL;
int error = 0;
GIT_ASSERT_ARG(repo);
GIT_ASSERT_ARG(name);
GIT_ASSERT_ARG(symbolic || signature);
if (ref_out)
*ref_out = NULL;
error = reference_normalize_for_repo(normalized, repo, name, true);
if (error < 0)
return error;
error = git_repository_refdb__weakptr(&refdb, repo);
if (error < 0)
return error;
if (oid != NULL) {
GIT_ASSERT(symbolic == NULL);
if (!git_object__is_valid(repo, oid, GIT_OBJECT_ANY)) {
git_error_set(GIT_ERROR_REFERENCE,
"target OID for the reference doesn't exist on the repository");
return -1;
}
ref = git_reference__alloc(normalized, oid, NULL);
} else {
git_refname_t normalized_target;
error = reference_normalize_for_repo(normalized_target, repo,
symbolic, git_reference__enable_symbolic_ref_target_validation);
if (error < 0)
return error;
ref = git_reference__alloc_symbolic(normalized, normalized_target);
}
GIT_ERROR_CHECK_ALLOC(ref);
if ((error = git_refdb_write(refdb, ref, force, signature, log_message, old_id, old_target)) < 0) {
git_reference_free(ref);
return error;
}
if (ref_out == NULL)
git_reference_free(ref);
else
*ref_out = ref;
return 0;
}
static int refs_configured_ident(git_signature **out, const git_repository *repo)
{
if (repo->ident_name && repo->ident_email)
return git_signature_now(out, repo->ident_name, repo->ident_email);
/* if not configured let us fall-through to the next method */
return -1;
}
int git_reference__log_signature(git_signature **out, git_repository *repo)
{
int error;
git_signature *who;
if(((error = refs_configured_ident(&who, repo)) < 0) &&
((error = git_signature_default(&who, repo)) < 0) &&
((error = git_signature_now(&who, "unknown", "unknown")) < 0))
return error;
*out = who;
return 0;
}
int git_reference_create_matching(
git_reference **ref_out,
git_repository *repo,
const char *name,
const git_oid *id,
int force,
const git_oid *old_id,
const char *log_message)
{
int error;
git_signature *who = NULL;
GIT_ASSERT_ARG(id);
if ((error = git_reference__log_signature(&who, repo)) < 0)
return error;
error = reference__create(
ref_out, repo, name, id, NULL, force, who, log_message, old_id, NULL);
git_signature_free(who);
return error;
}
int git_reference_create(
git_reference **ref_out,
git_repository *repo,
const char *name,
const git_oid *id,
int force,
const char *log_message)
{
return git_reference_create_matching(ref_out, repo, name, id, force, NULL, log_message);
}
int git_reference_symbolic_create_matching(
git_reference **ref_out,
git_repository *repo,
const char *name,
const char *target,
int force,
const char *old_target,
const char *log_message)
{
int error;
git_signature *who = NULL;
GIT_ASSERT_ARG(target);
if ((error = git_reference__log_signature(&who, repo)) < 0)
return error;
error = reference__create(
ref_out, repo, name, NULL, target, force, who, log_message, NULL, old_target);
git_signature_free(who);
return error;
}
int git_reference_symbolic_create(
git_reference **ref_out,
git_repository *repo,
const char *name,
const char *target,
int force,
const char *log_message)
{
return git_reference_symbolic_create_matching(ref_out, repo, name, target, force, NULL, log_message);
}
static int ensure_is_an_updatable_direct_reference(git_reference *ref)
{
if (ref->type == GIT_REFERENCE_DIRECT)
return 0;
git_error_set(GIT_ERROR_REFERENCE, "cannot set OID on symbolic reference");
return -1;
}
int git_reference_set_target(
git_reference **out,
git_reference *ref,
const git_oid *id,
const char *log_message)
{
int error;
git_repository *repo;
GIT_ASSERT_ARG(out);
GIT_ASSERT_ARG(ref);
GIT_ASSERT_ARG(id);
repo = ref->db->repo;
if ((error = ensure_is_an_updatable_direct_reference(ref)) < 0)
return error;
return git_reference_create_matching(out, repo, ref->name, id, 1, &ref->target.oid, log_message);
}
static int ensure_is_an_updatable_symbolic_reference(git_reference *ref)
{
if (ref->type == GIT_REFERENCE_SYMBOLIC)
return 0;
git_error_set(GIT_ERROR_REFERENCE, "cannot set symbolic target on a direct reference");
return -1;
}
int git_reference_symbolic_set_target(
git_reference **out,
git_reference *ref,
const char *target,
const char *log_message)
{
int error;
GIT_ASSERT_ARG(out);
GIT_ASSERT_ARG(ref);
GIT_ASSERT_ARG(target);
if ((error = ensure_is_an_updatable_symbolic_reference(ref)) < 0)
return error;
return git_reference_symbolic_create_matching(
out, ref->db->repo, ref->name, target, 1, ref->target.symbolic, log_message);
}
typedef struct {
const char *old_name;
git_refname_t new_name;
} refs_update_head_payload;
static int refs_update_head(git_repository *worktree, void *_payload)
{
refs_update_head_payload *payload = (refs_update_head_payload *)_payload;
git_reference *head = NULL, *updated = NULL;
int error;
if ((error = git_reference_lookup(&head, worktree, GIT_HEAD_FILE)) < 0)
goto out;
if (git_reference_type(head) != GIT_REFERENCE_SYMBOLIC ||
git__strcmp(git_reference_symbolic_target(head), payload->old_name) != 0)
goto out;
/* Update HEAD if it was pointing to the reference being renamed */
if ((error = git_reference_symbolic_set_target(&updated, head, payload->new_name, NULL)) < 0) {
git_error_set(GIT_ERROR_REFERENCE, "failed to update HEAD after renaming reference");
goto out;
}
out:
git_reference_free(updated);
git_reference_free(head);
return error;
}
int git_reference_rename(
git_reference **out,
git_reference *ref,
const char *new_name,
int force,
const char *log_message)
{
refs_update_head_payload payload;
git_signature *signature = NULL;
git_repository *repo;
int error;
GIT_ASSERT_ARG(out);
GIT_ASSERT_ARG(ref);
repo = git_reference_owner(ref);
if ((error = git_reference__log_signature(&signature, repo)) < 0 ||
(error = reference_normalize_for_repo(payload.new_name, repo, new_name, true)) < 0 ||
(error = git_refdb_rename(out, ref->db, ref->name, payload.new_name, force, signature, log_message)) < 0)
goto out;
payload.old_name = ref->name;
/* We may have to update any HEAD that was pointing to the renamed reference. */
if ((error = git_repository_foreach_worktree(repo, refs_update_head, &payload)) < 0)
goto out;
out:
git_signature_free(signature);
return error;
}
int git_reference_resolve(git_reference **ref_out, const git_reference *ref)
{
switch (git_reference_type(ref)) {
case GIT_REFERENCE_DIRECT:
return git_reference_lookup(ref_out, ref->db->repo, ref->name);
case GIT_REFERENCE_SYMBOLIC:
return git_reference_lookup_resolved(ref_out, ref->db->repo, ref->target.symbolic, -1);
default:
git_error_set(GIT_ERROR_REFERENCE, "invalid reference");
return -1;
}
}
int git_reference_foreach(
git_repository *repo,
git_reference_foreach_cb callback,
void *payload)
{
git_reference_iterator *iter;
git_reference *ref;
int error;
if ((error = git_reference_iterator_new(&iter, repo)) < 0)
return error;
while (!(error = git_reference_next(&ref, iter))) {
if ((error = callback(ref, payload)) != 0) {
git_error_set_after_callback(error);
break;
}
}
if (error == GIT_ITEROVER)
error = 0;
git_reference_iterator_free(iter);
return error;
}
int git_reference_foreach_name(
git_repository *repo,
git_reference_foreach_name_cb callback,
void *payload)
{
git_reference_iterator *iter;
const char *refname;
int error;
if ((error = git_reference_iterator_new(&iter, repo)) < 0)
return error;
while (!(error = git_reference_next_name(&refname, iter))) {
if ((error = callback(refname, payload)) != 0) {
git_error_set_after_callback(error);
break;
}
}
if (error == GIT_ITEROVER)
error = 0;
git_reference_iterator_free(iter);
return error;
}
int git_reference_foreach_glob(
git_repository *repo,
const char *glob,
git_reference_foreach_name_cb callback,
void *payload)
{
git_reference_iterator *iter;
const char *refname;
int error;
if ((error = git_reference_iterator_glob_new(&iter, repo, glob)) < 0)
return error;
while (!(error = git_reference_next_name(&refname, iter))) {
if ((error = callback(refname, payload)) != 0) {
git_error_set_after_callback(error);
break;
}
}
if (error == GIT_ITEROVER)
error = 0;
git_reference_iterator_free(iter);
return error;
}
int git_reference_iterator_new(git_reference_iterator **out, git_repository *repo)
{
git_refdb *refdb;
if (git_repository_refdb__weakptr(&refdb, repo) < 0)
return -1;
return git_refdb_iterator(out, refdb, NULL);
}
int git_reference_iterator_glob_new(
git_reference_iterator **out, git_repository *repo, const char *glob)
{
git_refdb *refdb;
if (git_repository_refdb__weakptr(&refdb, repo) < 0)
return -1;
return git_refdb_iterator(out, refdb, glob);
}
int git_reference_next(git_reference **out, git_reference_iterator *iter)
{
return git_refdb_iterator_next(out, iter);
}
int git_reference_next_name(const char **out, git_reference_iterator *iter)
{
return git_refdb_iterator_next_name(out, iter);
}
void git_reference_iterator_free(git_reference_iterator *iter)
{
if (iter == NULL)
return;
git_refdb_iterator_free(iter);
}
static int cb__reflist_add(const char *ref, void *data)
{
char *name = git__strdup(ref);
GIT_ERROR_CHECK_ALLOC(name);
return git_vector_insert((git_vector *)data, name);
}
int git_reference_list(
git_strarray *array,
git_repository *repo)
{
git_vector ref_list;
GIT_ASSERT_ARG(array);
GIT_ASSERT_ARG(repo);
array->strings = NULL;
array->count = 0;
if (git_vector_init(&ref_list, 8, NULL) < 0)
return -1;
if (git_reference_foreach_name(
repo, &cb__reflist_add, (void *)&ref_list) < 0) {
git_vector_free(&ref_list);
return -1;
}
array->strings = (char **)git_vector_detach(&array->count, NULL, &ref_list);
return 0;
}
static int is_valid_ref_char(char ch)
{
if ((unsigned) ch <= ' ')
return 0;
switch (ch) {
case '~':
case '^':
case ':':
case '\\':
case '?':
case '[':
return 0;
default:
return 1;
}
}
static int ensure_segment_validity(const char *name, char may_contain_glob)
{
const char *current = name;
char prev = '\0';
const int lock_len = (int)strlen(GIT_FILELOCK_EXTENSION);
int segment_len;
if (*current == '.')
return -1; /* Refname starts with "." */
for (current = name; ; current++) {
if (*current == '\0' || *current == '/')
break;
if (!is_valid_ref_char(*current))
return -1; /* Illegal character in refname */
if (prev == '.' && *current == '.')
return -1; /* Refname contains ".." */
if (prev == '@' && *current == '{')
return -1; /* Refname contains "@{" */
if (*current == '*') {
if (!may_contain_glob)
return -1;
may_contain_glob = 0;
}
prev = *current;
}
segment_len = (int)(current - name);
/* A refname component can not end with ".lock" */
if (segment_len >= lock_len &&
!memcmp(current - lock_len, GIT_FILELOCK_EXTENSION, lock_len))
return -1;
return segment_len;
}
static bool is_all_caps_and_underscore(const char *name, size_t len)
{
size_t i;
char c;
GIT_ASSERT_ARG(name);
GIT_ASSERT_ARG(len > 0);
for (i = 0; i < len; i++)
{
c = name[i];
if ((c < 'A' || c > 'Z') && c != '_')
return false;
}
if (*name == '_' || name[len - 1] == '_')
return false;
return true;
}
/* Inspired from https://github.com/git/git/blob/f06d47e7e0d9db709ee204ed13a8a7486149f494/refs.c#L36-100 */
int git_reference__normalize_name(
git_buf *buf,
const char *name,
unsigned int flags)
{
const char *current;
int segment_len, segments_count = 0, error = GIT_EINVALIDSPEC;
unsigned int process_flags;
bool normalize = (buf != NULL);
bool validate = (flags & GIT_REFERENCE_FORMAT__VALIDATION_DISABLE) == 0;
#ifdef GIT_USE_ICONV
git_path_iconv_t ic = GIT_PATH_ICONV_INIT;
#endif
GIT_ASSERT_ARG(name);
process_flags = flags;
current = (char *)name;
if (validate && *current == '/')
goto cleanup;
if (normalize)
git_buf_clear(buf);
#ifdef GIT_USE_ICONV
if ((flags & GIT_REFERENCE_FORMAT__PRECOMPOSE_UNICODE) != 0) {
size_t namelen = strlen(current);
if ((error = git_path_iconv_init_precompose(&ic)) < 0 ||
(error = git_path_iconv(&ic, ¤t, &namelen)) < 0)
goto cleanup;
error = GIT_EINVALIDSPEC;
}
#endif
if (!validate) {
git_buf_sets(buf, current);
error = git_buf_oom(buf) ? -1 : 0;
goto cleanup;
}
while (true) {
char may_contain_glob = process_flags & GIT_REFERENCE_FORMAT_REFSPEC_PATTERN;
segment_len = ensure_segment_validity(current, may_contain_glob);
if (segment_len < 0)
goto cleanup;
if (segment_len > 0) {
/*
* There may only be one glob in a pattern, thus we reset
* the pattern-flag in case the current segment has one.
*/
if (memchr(current, '*', segment_len))
process_flags &= ~GIT_REFERENCE_FORMAT_REFSPEC_PATTERN;
if (normalize) {
size_t cur_len = git_buf_len(buf);
git_buf_joinpath(buf, git_buf_cstr(buf), current);
git_buf_truncate(buf,
cur_len + segment_len + (segments_count ? 1 : 0));
if (git_buf_oom(buf)) {
error = -1;
goto cleanup;
}
}
segments_count++;
}
/* No empty segment is allowed when not normalizing */
if (segment_len == 0 && !normalize)
goto cleanup;
if (current[segment_len] == '\0')
break;
current += segment_len + 1;
}
/* A refname can not be empty */
if (segment_len == 0 && segments_count == 0)
goto cleanup;
/* A refname can not end with "." */
if (current[segment_len - 1] == '.')
goto cleanup;
/* A refname can not end with "/" */
if (current[segment_len - 1] == '/')
goto cleanup;
if ((segments_count == 1 ) && !(flags & GIT_REFERENCE_FORMAT_ALLOW_ONELEVEL))
goto cleanup;
if ((segments_count == 1 ) &&
!(flags & GIT_REFERENCE_FORMAT_REFSPEC_SHORTHAND) &&
!(is_all_caps_and_underscore(name, (size_t)segment_len) ||
((flags & GIT_REFERENCE_FORMAT_REFSPEC_PATTERN) && !strcmp("*", name))))
goto cleanup;
if ((segments_count > 1)
&& (is_all_caps_and_underscore(name, strchr(name, '/') - name)))
goto cleanup;
error = 0;
cleanup:
if (error == GIT_EINVALIDSPEC)
git_error_set(
GIT_ERROR_REFERENCE,
"the given reference name '%s' is not valid", name);
if (error && normalize)
git_buf_dispose(buf);
#ifdef GIT_USE_ICONV
git_path_iconv_clear(&ic);
#endif
return error;
}
int git_reference_normalize_name(
char *buffer_out,
size_t buffer_size,
const char *name,
unsigned int flags)
{
git_buf buf = GIT_BUF_INIT;
int error;
if ((error = git_reference__normalize_name(&buf, name, flags)) < 0)
goto cleanup;
if (git_buf_len(&buf) > buffer_size - 1) {
git_error_set(
GIT_ERROR_REFERENCE,
"the provided buffer is too short to hold the normalization of '%s'", name);
error = GIT_EBUFS;
goto cleanup;
}
if ((error = git_buf_copy_cstr(buffer_out, buffer_size, &buf)) < 0)
goto cleanup;
error = 0;
cleanup:
git_buf_dispose(&buf);
return error;
}
#define GIT_REFERENCE_TYPEMASK (GIT_REFERENCE_DIRECT | GIT_REFERENCE_SYMBOLIC)
int git_reference_cmp(
const git_reference *ref1,
const git_reference *ref2)
{
git_reference_t type1, type2;
GIT_ASSERT_ARG(ref1);
GIT_ASSERT_ARG(ref2);
type1 = git_reference_type(ref1);
type2 = git_reference_type(ref2);
/* let's put symbolic refs before OIDs */
if (type1 != type2)
return (type1 == GIT_REFERENCE_SYMBOLIC) ? -1 : 1;
if (type1 == GIT_REFERENCE_SYMBOLIC)
return strcmp(ref1->target.symbolic, ref2->target.symbolic);
return git_oid__cmp(&ref1->target.oid, &ref2->target.oid);
}
/*
* Starting with the reference given by `ref_name`, follows symbolic
* references until a direct reference is found and updated the OID
* on that direct reference to `oid`.
*/
int git_reference__update_terminal(
git_repository *repo,
const char *ref_name,
const git_oid *oid,
const git_signature *sig,
const char *log_message)
{
git_reference *ref = NULL, *ref2 = NULL;
git_signature *who = NULL;
git_refdb *refdb = NULL;
const git_signature *to_use;
int error = 0;
if (!sig && (error = git_reference__log_signature(&who, repo)) < 0)
goto out;
to_use = sig ? sig : who;
if ((error = git_repository_refdb__weakptr(&refdb, repo)) < 0)
goto out;
if ((error = git_refdb_resolve(&ref, refdb, ref_name, -1)) < 0) {
if (error == GIT_ENOTFOUND) {
git_error_clear();
error = reference__create(&ref2, repo, ref_name, oid, NULL, 0, to_use,
log_message, NULL, NULL);
}
goto out;
}
/* In case the resolved reference is symbolic, then it's a dangling symref. */
if (git_reference_type(ref) == GIT_REFERENCE_SYMBOLIC) {
error = reference__create(&ref2, repo, ref->target.symbolic, oid, NULL, 0, to_use,
log_message, NULL, NULL);
} else {
error = reference__create(&ref2, repo, ref->name, oid, NULL, 1, to_use,
log_message, &ref->target.oid, NULL);
}
out:
git_reference_free(ref2);
git_reference_free(ref);
git_signature_free(who);
return error;
}
static const char *commit_type(const git_commit *commit)
{
unsigned int count = git_commit_parentcount(commit);
if (count >= 2)
return " (merge)";
else if (count == 0)
return " (initial)";
else
return "";
}
int git_reference__update_for_commit(
git_repository *repo,
git_reference *ref,
const char *ref_name,
const git_oid *id,
const char *operation)
{
git_reference *ref_new = NULL;
git_commit *commit = NULL;
git_buf reflog_msg = GIT_BUF_INIT;
const git_signature *who;
int error;
if ((error = git_commit_lookup(&commit, repo, id)) < 0 ||
(error = git_buf_printf(&reflog_msg, "%s%s: %s",
operation ? operation : "commit",
commit_type(commit),
git_commit_summary(commit))) < 0)
goto done;
who = git_commit_committer(commit);
if (ref) {
if ((error = ensure_is_an_updatable_direct_reference(ref)) < 0)
return error;
error = reference__create(&ref_new, repo, ref->name, id, NULL, 1, who,
git_buf_cstr(&reflog_msg), &ref->target.oid, NULL);
}
else
error = git_reference__update_terminal(
repo, ref_name, id, who, git_buf_cstr(&reflog_msg));
done:
git_reference_free(ref_new);
git_buf_dispose(&reflog_msg);
git_commit_free(commit);
return error;
}
int git_reference_has_log(git_repository *repo, const char *refname)
{
int error;
git_refdb *refdb;
GIT_ASSERT_ARG(repo);
GIT_ASSERT_ARG(refname);
if ((error = git_repository_refdb__weakptr(&refdb, repo)) < 0)
return error;
return git_refdb_has_log(refdb, refname);
}
int git_reference_ensure_log(git_repository *repo, const char *refname)
{
int error;
git_refdb *refdb;
GIT_ASSERT_ARG(repo);
GIT_ASSERT_ARG(refname);
if ((error = git_repository_refdb__weakptr(&refdb, repo)) < 0)
return error;
return git_refdb_ensure_log(refdb, refname);
}
int git_reference__is_branch(const char *ref_name)
{
return git__prefixcmp(ref_name, GIT_REFS_HEADS_DIR) == 0;
}
int git_reference_is_branch(const git_reference *ref)
{
GIT_ASSERT_ARG(ref);
return git_reference__is_branch(ref->name);
}
int git_reference__is_remote(const char *ref_name)
{
return git__prefixcmp(ref_name, GIT_REFS_REMOTES_DIR) == 0;
}
int git_reference_is_remote(const git_reference *ref)
{
GIT_ASSERT_ARG(ref);
return git_reference__is_remote(ref->name);
}
int git_reference__is_tag(const char *ref_name)
{
return git__prefixcmp(ref_name, GIT_REFS_TAGS_DIR) == 0;
}
int git_reference_is_tag(const git_reference *ref)
{
GIT_ASSERT_ARG(ref);
return git_reference__is_tag(ref->name);
}
int git_reference__is_note(const char *ref_name)
{
return git__prefixcmp(ref_name, GIT_REFS_NOTES_DIR) == 0;
}
int git_reference_is_note(const git_reference *ref)
{
GIT_ASSERT_ARG(ref);
return git_reference__is_note(ref->name);
}
static int peel_error(int error, const git_reference *ref, const char *msg)
{
git_error_set(
GIT_ERROR_INVALID,
"the reference '%s' cannot be peeled - %s", git_reference_name(ref), msg);
return error;
}
int git_reference_peel(
git_object **peeled,
const git_reference *ref,
git_object_t target_type)
{
const git_reference *resolved = NULL;
git_reference *allocated = NULL;
git_object *target = NULL;
int error;
GIT_ASSERT_ARG(ref);
if (ref->type == GIT_REFERENCE_DIRECT) {
resolved = ref;
} else {
if ((error = git_reference_resolve(&allocated, ref)) < 0)
return peel_error(error, ref, "Cannot resolve reference");
resolved = allocated;
}
/*
* If we try to peel an object to a tag, we cannot use
* the fully peeled object, as that will always resolve
* to a commit. So we only want to use the peeled value
* if it is not zero and the target is not a tag.
*/
if (target_type != GIT_OBJECT_TAG && !git_oid_is_zero(&resolved->peel)) {
error = git_object_lookup(&target,
git_reference_owner(ref), &resolved->peel, GIT_OBJECT_ANY);
} else {
error = git_object_lookup(&target,
git_reference_owner(ref), &resolved->target.oid, GIT_OBJECT_ANY);
}
if (error < 0) {
peel_error(error, ref, "Cannot retrieve reference target");
goto cleanup;
}
if (target_type == GIT_OBJECT_ANY && git_object_type(target) != GIT_OBJECT_TAG)
error = git_object_dup(peeled, target);
else
error = git_object_peel(peeled, target, target_type);
cleanup:
git_object_free(target);
git_reference_free(allocated);
return error;
}
int git_reference__name_is_valid(
int *valid,
const char *refname,
unsigned int flags)
{
int error;
GIT_ASSERT(valid && refname);
*valid = 0;
error = git_reference__normalize_name(NULL, refname, flags);
if (!error)
*valid = 1;
else if (error == GIT_EINVALIDSPEC)
error = 0;
return error;
}
int git_reference_name_is_valid(int *valid, const char *refname)
{
return git_reference__name_is_valid(valid, refname, GIT_REFERENCE_FORMAT_ALLOW_ONELEVEL);
}
const char *git_reference__shorthand(const char *name)
{
if (!git__prefixcmp(name, GIT_REFS_HEADS_DIR))
return name + strlen(GIT_REFS_HEADS_DIR);
else if (!git__prefixcmp(name, GIT_REFS_TAGS_DIR))
return name + strlen(GIT_REFS_TAGS_DIR);
else if (!git__prefixcmp(name, GIT_REFS_REMOTES_DIR))
return name + strlen(GIT_REFS_REMOTES_DIR);
else if (!git__prefixcmp(name, GIT_REFS_DIR))
return name + strlen(GIT_REFS_DIR);
/* No shorthands are available, so just return the name. */
return name;
}
const char *git_reference_shorthand(const git_reference *ref)
{
return git_reference__shorthand(ref->name);
}
int git_reference__is_unborn_head(bool *unborn, const git_reference *ref, git_repository *repo)
{
int error;
git_reference *tmp_ref;
GIT_ASSERT_ARG(unborn);
GIT_ASSERT_ARG(ref);
GIT_ASSERT_ARG(repo);
if (ref->type == GIT_REFERENCE_DIRECT) {
*unborn = 0;
return 0;
}
error = git_reference_lookup_resolved(&tmp_ref, repo, ref->name, -1);
git_reference_free(tmp_ref);
if (error != 0 && error != GIT_ENOTFOUND)
return error;
else if (error == GIT_ENOTFOUND && git__strcmp(ref->name, GIT_HEAD_FILE) == 0)
*unborn = true;
else
*unborn = false;
return 0;
}
/* Deprecated functions */
#ifndef GIT_DEPRECATE_HARD
int git_reference_is_valid_name(const char *refname)
{
int valid = 0;
git_reference__name_is_valid(&valid, refname, GIT_REFERENCE_FORMAT_ALLOW_ONELEVEL);
return valid;
}
#endif
|
0 |
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2
|
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2/src/parse.h
|
/*
* Copyright (C) the libgit2 contributors. All rights reserved.
*
* This file is part of libgit2, distributed under the GNU GPL v2 with
* a Linking Exception. For full terms see the included COPYING file.
*/
#ifndef INCLUDE_parse_h__
#define INCLUDE_parse_h__
#include "common.h"
typedef struct {
/* Original content buffer */
const char *content;
size_t content_len;
/* The remaining (unparsed) buffer */
const char *remain;
size_t remain_len;
const char *line;
size_t line_len;
size_t line_num;
} git_parse_ctx;
#define GIT_PARSE_CTX_INIT { 0 }
int git_parse_ctx_init(git_parse_ctx *ctx, const char *content, size_t content_len);
void git_parse_ctx_clear(git_parse_ctx *ctx);
#define git_parse_ctx_contains_s(ctx, str) \
git_parse_ctx_contains(ctx, str, sizeof(str) - 1)
GIT_INLINE(bool) git_parse_ctx_contains(
git_parse_ctx *ctx, const char *str, size_t len)
{
return (ctx->line_len >= len && memcmp(ctx->line, str, len) == 0);
}
void git_parse_advance_line(git_parse_ctx *ctx);
void git_parse_advance_chars(git_parse_ctx *ctx, size_t char_cnt);
int git_parse_advance_expected(
git_parse_ctx *ctx,
const char *expected,
size_t expected_len);
#define git_parse_advance_expected_str(ctx, str) \
git_parse_advance_expected(ctx, str, strlen(str))
int git_parse_advance_ws(git_parse_ctx *ctx);
int git_parse_advance_nl(git_parse_ctx *ctx);
int git_parse_advance_digit(int64_t *out, git_parse_ctx *ctx, int base);
int git_parse_advance_oid(git_oid *out, git_parse_ctx *ctx);
enum GIT_PARSE_PEEK_FLAGS {
GIT_PARSE_PEEK_SKIP_WHITESPACE = (1 << 0)
};
int git_parse_peek(char *out, git_parse_ctx *ctx, int flags);
#endif
|
0 |
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2
|
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2/src/strmap.c
|
/*
* Copyright (C) the libgit2 contributors. All rights reserved.
*
* This file is part of libgit2, distributed under the GNU GPL v2 with
* a Linking Exception. For full terms see the included COPYING file.
*/
#include "strmap.h"
#define kmalloc git__malloc
#define kcalloc git__calloc
#define krealloc git__realloc
#define kreallocarray git__reallocarray
#define kfree git__free
#include "khash.h"
__KHASH_TYPE(str, const char *, void *)
__KHASH_IMPL(str, static kh_inline, const char *, void *, 1, kh_str_hash_func, kh_str_hash_equal)
int git_strmap_new(git_strmap **out)
{
*out = kh_init(str);
GIT_ERROR_CHECK_ALLOC(*out);
return 0;
}
void git_strmap_free(git_strmap *map)
{
kh_destroy(str, map);
}
void git_strmap_clear(git_strmap *map)
{
kh_clear(str, map);
}
size_t git_strmap_size(git_strmap *map)
{
return kh_size(map);
}
void *git_strmap_get(git_strmap *map, const char *key)
{
size_t idx = kh_get(str, map, key);
if (idx == kh_end(map) || !kh_exist(map, idx))
return NULL;
return kh_val(map, idx);
}
int git_strmap_set(git_strmap *map, const char *key, void *value)
{
size_t idx;
int rval;
idx = kh_put(str, map, key, &rval);
if (rval < 0)
return -1;
if (rval == 0)
kh_key(map, idx) = key;
kh_val(map, idx) = value;
return 0;
}
int git_strmap_delete(git_strmap *map, const char *key)
{
khiter_t idx = kh_get(str, map, key);
if (idx == kh_end(map))
return GIT_ENOTFOUND;
kh_del(str, map, idx);
return 0;
}
int git_strmap_exists(git_strmap *map, const char *key)
{
return kh_get(str, map, key) != kh_end(map);
}
int git_strmap_iterate(void **value, git_strmap *map, size_t *iter, const char **key)
{
size_t i = *iter;
while (i < map->n_buckets && !kh_exist(map, i))
i++;
if (i >= map->n_buckets)
return GIT_ITEROVER;
if (key)
*key = kh_key(map, i);
if (value)
*value = kh_val(map, i);
*iter = ++i;
return 0;
}
|
0 |
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2
|
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2/src/diff_parse.h
|
/*
* Copyright (C) the libgit2 contributors. All rights reserved.
*
* This file is part of libgit2, distributed under the GNU GPL v2 with
* a Linking Exception. For full terms see the included COPYING file.
*/
#ifndef INCLUDE_diff_parse_h__
#define INCLUDE_diff_parse_h__
#include "common.h"
#include "diff.h"
typedef struct {
struct git_diff base;
git_vector patches;
} git_diff_parsed;
#endif
|
0 |
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2
|
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2/src/cache.h
|
/*
* Copyright (C) the libgit2 contributors. All rights reserved.
*
* This file is part of libgit2, distributed under the GNU GPL v2 with
* a Linking Exception. For full terms see the included COPYING file.
*/
#ifndef INCLUDE_cache_h__
#define INCLUDE_cache_h__
#include "common.h"
#include "git2/common.h"
#include "git2/oid.h"
#include "git2/odb.h"
#include "thread.h"
#include "oidmap.h"
enum {
GIT_CACHE_STORE_ANY = 0,
GIT_CACHE_STORE_RAW = 1,
GIT_CACHE_STORE_PARSED = 2
};
typedef struct {
git_oid oid;
int16_t type; /* git_object_t value */
uint16_t flags; /* GIT_CACHE_STORE value */
size_t size;
git_atomic32 refcount;
} git_cached_obj;
typedef struct {
git_oidmap *map;
git_rwlock lock;
ssize_t used_memory;
} git_cache;
extern bool git_cache__enabled;
extern ssize_t git_cache__max_storage;
extern git_atomic_ssize git_cache__current_storage;
int git_cache_set_max_object_size(git_object_t type, size_t size);
int git_cache_init(git_cache *cache);
void git_cache_dispose(git_cache *cache);
void git_cache_clear(git_cache *cache);
void *git_cache_store_raw(git_cache *cache, git_odb_object *entry);
void *git_cache_store_parsed(git_cache *cache, git_object *entry);
git_odb_object *git_cache_get_raw(git_cache *cache, const git_oid *oid);
git_object *git_cache_get_parsed(git_cache *cache, const git_oid *oid);
void *git_cache_get_any(git_cache *cache, const git_oid *oid);
GIT_INLINE(size_t) git_cache_size(git_cache *cache)
{
return (size_t)git_oidmap_size(cache->map);
}
GIT_INLINE(void) git_cached_obj_incref(void *_obj)
{
git_cached_obj *obj = _obj;
git_atomic32_inc(&obj->refcount);
}
void git_cached_obj_decref(void *_obj);
#endif
|
0 |
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2
|
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2/src/fetchhead.c
|
/*
* Copyright (C) the libgit2 contributors. All rights reserved.
*
* This file is part of libgit2, distributed under the GNU GPL v2 with
* a Linking Exception. For full terms see the included COPYING file.
*/
#include "fetchhead.h"
#include "git2/types.h"
#include "git2/oid.h"
#include "buffer.h"
#include "futils.h"
#include "filebuf.h"
#include "refs.h"
#include "net.h"
#include "repository.h"
int git_fetchhead_ref_cmp(const void *a, const void *b)
{
const git_fetchhead_ref *one = (const git_fetchhead_ref *)a;
const git_fetchhead_ref *two = (const git_fetchhead_ref *)b;
if (one->is_merge && !two->is_merge)
return -1;
if (two->is_merge && !one->is_merge)
return 1;
if (one->ref_name && two->ref_name)
return strcmp(one->ref_name, two->ref_name);
else if (one->ref_name)
return -1;
else if (two->ref_name)
return 1;
return 0;
}
static char *sanitized_remote_url(const char *remote_url)
{
git_net_url url = GIT_NET_URL_INIT;
char *sanitized = NULL;
int error;
if (git_net_url_parse(&url, remote_url) == 0) {
git_buf buf = GIT_BUF_INIT;
git__free(url.username);
git__free(url.password);
url.username = url.password = NULL;
if ((error = git_net_url_fmt(&buf, &url)) < 0)
goto fallback;
sanitized = git_buf_detach(&buf);
}
fallback:
if (!sanitized)
sanitized = git__strdup(remote_url);
git_net_url_dispose(&url);
return sanitized;
}
int git_fetchhead_ref_create(
git_fetchhead_ref **out,
git_oid *oid,
unsigned int is_merge,
const char *ref_name,
const char *remote_url)
{
git_fetchhead_ref *fetchhead_ref;
GIT_ASSERT_ARG(out);
GIT_ASSERT_ARG(oid);
*out = NULL;
fetchhead_ref = git__malloc(sizeof(git_fetchhead_ref));
GIT_ERROR_CHECK_ALLOC(fetchhead_ref);
memset(fetchhead_ref, 0x0, sizeof(git_fetchhead_ref));
git_oid_cpy(&fetchhead_ref->oid, oid);
fetchhead_ref->is_merge = is_merge;
if (ref_name) {
fetchhead_ref->ref_name = git__strdup(ref_name);
GIT_ERROR_CHECK_ALLOC(fetchhead_ref->ref_name);
}
if (remote_url) {
fetchhead_ref->remote_url = sanitized_remote_url(remote_url);
GIT_ERROR_CHECK_ALLOC(fetchhead_ref->remote_url);
}
*out = fetchhead_ref;
return 0;
}
static int fetchhead_ref_write(
git_filebuf *file,
git_fetchhead_ref *fetchhead_ref)
{
char oid[GIT_OID_HEXSZ + 1];
const char *type, *name;
int head = 0;
GIT_ASSERT_ARG(file);
GIT_ASSERT_ARG(fetchhead_ref);
git_oid_fmt(oid, &fetchhead_ref->oid);
oid[GIT_OID_HEXSZ] = '\0';
if (git__prefixcmp(fetchhead_ref->ref_name, GIT_REFS_HEADS_DIR) == 0) {
type = "branch ";
name = fetchhead_ref->ref_name + strlen(GIT_REFS_HEADS_DIR);
} else if(git__prefixcmp(fetchhead_ref->ref_name,
GIT_REFS_TAGS_DIR) == 0) {
type = "tag ";
name = fetchhead_ref->ref_name + strlen(GIT_REFS_TAGS_DIR);
} else if (!git__strcmp(fetchhead_ref->ref_name, GIT_HEAD_FILE)) {
head = 1;
} else {
type = "";
name = fetchhead_ref->ref_name;
}
if (head)
return git_filebuf_printf(file, "%s\t\t%s\n", oid, fetchhead_ref->remote_url);
return git_filebuf_printf(file, "%s\t%s\t%s'%s' of %s\n",
oid,
(fetchhead_ref->is_merge) ? "" : "not-for-merge",
type,
name,
fetchhead_ref->remote_url);
}
int git_fetchhead_write(git_repository *repo, git_vector *fetchhead_refs)
{
git_filebuf file = GIT_FILEBUF_INIT;
git_buf path = GIT_BUF_INIT;
unsigned int i;
git_fetchhead_ref *fetchhead_ref;
GIT_ASSERT_ARG(repo);
GIT_ASSERT_ARG(fetchhead_refs);
if (git_buf_joinpath(&path, repo->gitdir, GIT_FETCH_HEAD_FILE) < 0)
return -1;
if (git_filebuf_open(&file, path.ptr, GIT_FILEBUF_APPEND, GIT_REFS_FILE_MODE) < 0) {
git_buf_dispose(&path);
return -1;
}
git_buf_dispose(&path);
git_vector_sort(fetchhead_refs);
git_vector_foreach(fetchhead_refs, i, fetchhead_ref)
fetchhead_ref_write(&file, fetchhead_ref);
return git_filebuf_commit(&file);
}
static int fetchhead_ref_parse(
git_oid *oid,
unsigned int *is_merge,
git_buf *ref_name,
const char **remote_url,
char *line,
size_t line_num)
{
char *oid_str, *is_merge_str, *desc, *name = NULL;
const char *type = NULL;
int error = 0;
*remote_url = NULL;
if (!*line) {
git_error_set(GIT_ERROR_FETCHHEAD,
"empty line in FETCH_HEAD line %"PRIuZ, line_num);
return -1;
}
/* Compat with old git clients that wrote FETCH_HEAD like a loose ref. */
if ((oid_str = git__strsep(&line, "\t")) == NULL) {
oid_str = line;
line += strlen(line);
*is_merge = 1;
}
if (strlen(oid_str) != GIT_OID_HEXSZ) {
git_error_set(GIT_ERROR_FETCHHEAD,
"invalid object ID in FETCH_HEAD line %"PRIuZ, line_num);
return -1;
}
if (git_oid_fromstr(oid, oid_str) < 0) {
const git_error *oid_err = git_error_last();
const char *err_msg = oid_err ? oid_err->message : "invalid object ID";
git_error_set(GIT_ERROR_FETCHHEAD, "%s in FETCH_HEAD line %"PRIuZ,
err_msg, line_num);
return -1;
}
/* Parse new data from newer git clients */
if (*line) {
if ((is_merge_str = git__strsep(&line, "\t")) == NULL) {
git_error_set(GIT_ERROR_FETCHHEAD,
"invalid description data in FETCH_HEAD line %"PRIuZ, line_num);
return -1;
}
if (*is_merge_str == '\0')
*is_merge = 1;
else if (strcmp(is_merge_str, "not-for-merge") == 0)
*is_merge = 0;
else {
git_error_set(GIT_ERROR_FETCHHEAD,
"invalid for-merge entry in FETCH_HEAD line %"PRIuZ, line_num);
return -1;
}
if ((desc = line) == NULL) {
git_error_set(GIT_ERROR_FETCHHEAD,
"invalid description in FETCH_HEAD line %"PRIuZ, line_num);
return -1;
}
if (git__prefixcmp(desc, "branch '") == 0) {
type = GIT_REFS_HEADS_DIR;
name = desc + 8;
} else if (git__prefixcmp(desc, "tag '") == 0) {
type = GIT_REFS_TAGS_DIR;
name = desc + 5;
} else if (git__prefixcmp(desc, "'") == 0)
name = desc + 1;
if (name) {
if ((desc = strstr(name, "' ")) == NULL ||
git__prefixcmp(desc, "' of ") != 0) {
git_error_set(GIT_ERROR_FETCHHEAD,
"invalid description in FETCH_HEAD line %"PRIuZ, line_num);
return -1;
}
*desc = '\0';
desc += 5;
}
*remote_url = desc;
}
git_buf_clear(ref_name);
if (type)
git_buf_join(ref_name, '/', type, name);
else if(name)
git_buf_puts(ref_name, name);
return error;
}
int git_repository_fetchhead_foreach(git_repository *repo,
git_repository_fetchhead_foreach_cb cb,
void *payload)
{
git_buf path = GIT_BUF_INIT, file = GIT_BUF_INIT, name = GIT_BUF_INIT;
const char *ref_name;
git_oid oid;
const char *remote_url;
unsigned int is_merge = 0;
char *buffer, *line;
size_t line_num = 0;
int error = 0;
GIT_ASSERT_ARG(repo);
GIT_ASSERT_ARG(cb);
if (git_buf_joinpath(&path, repo->gitdir, GIT_FETCH_HEAD_FILE) < 0)
return -1;
if ((error = git_futils_readbuffer(&file, git_buf_cstr(&path))) < 0)
goto done;
buffer = file.ptr;
while ((line = git__strsep(&buffer, "\n")) != NULL) {
++line_num;
if ((error = fetchhead_ref_parse(
&oid, &is_merge, &name, &remote_url, line, line_num)) < 0)
goto done;
if (git_buf_len(&name) > 0)
ref_name = git_buf_cstr(&name);
else
ref_name = NULL;
error = cb(ref_name, remote_url, &oid, is_merge, payload);
if (error) {
git_error_set_after_callback(error);
goto done;
}
}
if (*buffer) {
git_error_set(GIT_ERROR_FETCHHEAD, "no EOL at line %"PRIuZ, line_num+1);
error = -1;
goto done;
}
done:
git_buf_dispose(&file);
git_buf_dispose(&path);
git_buf_dispose(&name);
return error;
}
void git_fetchhead_ref_free(git_fetchhead_ref *fetchhead_ref)
{
if (fetchhead_ref == NULL)
return;
git__free(fetchhead_ref->remote_url);
git__free(fetchhead_ref->ref_name);
git__free(fetchhead_ref);
}
|
0 |
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2
|
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2/src/threadstate.c
|
/*
* Copyright (C) the libgit2 contributors. All rights reserved.
*
* This file is part of libgit2, distributed under the GNU GPL v2 with
* a Linking Exception. For full terms see the included COPYING file.
*/
#include "threadstate.h"
#include "runtime.h"
/**
* Handle the thread-local state
*
* `git_threadstate_global_init` will be called as part
* of `git_libgit2_init` (which itself must be called
* before calling any other function in the library).
*
* This function allocates a TLS index to store the per-
* thread state.
*
* Any internal method that requires thread-local state
* will then call `git_threadstate_get()` which returns a
* pointer to the thread-local state structure; this
* structure is lazily allocated on each thread.
*
* This mechanism will register a shutdown handler
* (`git_threadstate_global_shutdown`) which will free the
* TLS index. This shutdown handler will be called by
* `git_libgit2_shutdown`.
*/
static git_tlsdata_key tls_key;
static void threadstate_dispose(git_threadstate *threadstate)
{
if (!threadstate)
return;
if (threadstate->error_t.message != git_buf__initbuf)
git__free(threadstate->error_t.message);
threadstate->error_t.message = NULL;
}
static void GIT_SYSTEM_CALL threadstate_free(void *threadstate)
{
threadstate_dispose(threadstate);
git__free(threadstate);
}
static void git_threadstate_global_shutdown(void)
{
git_threadstate *threadstate;
threadstate = git_tlsdata_get(tls_key);
git_tlsdata_set(tls_key, NULL);
threadstate_dispose(threadstate);
git__free(threadstate);
git_tlsdata_dispose(tls_key);
}
int git_threadstate_global_init(void)
{
if (git_tlsdata_init(&tls_key, &threadstate_free) != 0)
return -1;
return git_runtime_shutdown_register(git_threadstate_global_shutdown);
}
git_threadstate *git_threadstate_get(void)
{
git_threadstate *threadstate;
if ((threadstate = git_tlsdata_get(tls_key)) != NULL)
return threadstate;
if ((threadstate = git__calloc(1, sizeof(git_threadstate))) == NULL ||
git_buf_init(&threadstate->error_buf, 0) < 0)
return NULL;
git_tlsdata_set(tls_key, threadstate);
return threadstate;
}
|
0 |
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2
|
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2/src/commit.h
|
/*
* Copyright (C) the libgit2 contributors. All rights reserved.
*
* This file is part of libgit2, distributed under the GNU GPL v2 with
* a Linking Exception. For full terms see the included COPYING file.
*/
#ifndef INCLUDE_commit_h__
#define INCLUDE_commit_h__
#include "common.h"
#include "git2/commit.h"
#include "tree.h"
#include "repository.h"
#include "array.h"
#include <time.h>
struct git_commit {
git_object object;
git_array_t(git_oid) parent_ids;
git_oid tree_id;
git_signature *author;
git_signature *committer;
char *message_encoding;
char *raw_message;
char *raw_header;
char *summary;
char *body;
};
void git_commit__free(void *commit);
int git_commit__parse(void *commit, git_odb_object *obj);
int git_commit__parse_raw(void *commit, const char *data, size_t size);
typedef enum {
GIT_COMMIT_PARSE_QUICK = (1 << 0), /**< Only parse parents and committer info */
} git_commit__parse_flags;
int git_commit__parse_ext(git_commit *commit, git_odb_object *odb_obj, unsigned int flags);
#endif
|
0 |
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2
|
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2/src/diff_xdiff.h
|
/*
* Copyright (C) the libgit2 contributors. All rights reserved.
*
* This file is part of libgit2, distributed under the GNU GPL v2 with
* a Linking Exception. For full terms see the included COPYING file.
*/
#ifndef INCLUDE_diff_xdiff_h__
#define INCLUDE_diff_xdiff_h__
#include "common.h"
#include "diff.h"
#include "xdiff/xdiff.h"
#include "patch_generate.h"
/* xdiff cannot cope with large files. these files should not be passed to
* xdiff. callers should treat these large files as binary.
*/
#define GIT_XDIFF_MAX_SIZE (INT64_C(1024) * 1024 * 1023)
/* A git_xdiff_output is a git_patch_generate_output with extra fields
* necessary to use libxdiff. Calling git_xdiff_init() will set the diff_cb
* field of the output to use xdiff to generate the diffs.
*/
typedef struct {
git_patch_generated_output output;
xdemitconf_t config;
xpparam_t params;
xdemitcb_t callback;
} git_xdiff_output;
void git_xdiff_init(git_xdiff_output *xo, const git_diff_options *opts);
#endif
|
0 |
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2
|
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2/src/indexer.h
|
/*
* Copyright (C) the libgit2 contributors. All rights reserved.
*
* This file is part of libgit2, distributed under the GNU GPL v2 with
* a Linking Exception. For full terms see the included COPYING file.
*/
#ifndef INCLUDE_indexer_h__
#define INCLUDE_indexer_h__
#include "common.h"
#include "git2/indexer.h"
extern void git_indexer__set_fsync(git_indexer *idx, int do_fsync);
#endif
|
0 |
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2
|
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2/src/odb_mempack.c
|
/*
* Copyright (C) the libgit2 contributors. All rights reserved.
*
* This file is part of libgit2, distributed under the GNU GPL v2 with
* a Linking Exception. For full terms see the included COPYING file.
*/
#include "common.h"
#include "git2/object.h"
#include "git2/sys/odb_backend.h"
#include "git2/sys/mempack.h"
#include "futils.h"
#include "hash.h"
#include "odb.h"
#include "array.h"
#include "oidmap.h"
#include "git2/odb_backend.h"
#include "git2/types.h"
#include "git2/pack.h"
struct memobject {
git_oid oid;
size_t len;
git_object_t type;
char data[GIT_FLEX_ARRAY];
};
struct memory_packer_db {
git_odb_backend parent;
git_oidmap *objects;
git_array_t(struct memobject *) commits;
};
static int impl__write(git_odb_backend *_backend, const git_oid *oid, const void *data, size_t len, git_object_t type)
{
struct memory_packer_db *db = (struct memory_packer_db *)_backend;
struct memobject *obj = NULL;
size_t alloc_len;
if (git_oidmap_exists(db->objects, oid))
return 0;
GIT_ERROR_CHECK_ALLOC_ADD(&alloc_len, sizeof(struct memobject), len);
obj = git__malloc(alloc_len);
GIT_ERROR_CHECK_ALLOC(obj);
memcpy(obj->data, data, len);
git_oid_cpy(&obj->oid, oid);
obj->len = len;
obj->type = type;
if (git_oidmap_set(db->objects, &obj->oid, obj) < 0)
return -1;
if (type == GIT_OBJECT_COMMIT) {
struct memobject **store = git_array_alloc(db->commits);
GIT_ERROR_CHECK_ALLOC(store);
*store = obj;
}
return 0;
}
static int impl__exists(git_odb_backend *backend, const git_oid *oid)
{
struct memory_packer_db *db = (struct memory_packer_db *)backend;
return git_oidmap_exists(db->objects, oid);
}
static int impl__read(void **buffer_p, size_t *len_p, git_object_t *type_p, git_odb_backend *backend, const git_oid *oid)
{
struct memory_packer_db *db = (struct memory_packer_db *)backend;
struct memobject *obj;
if ((obj = git_oidmap_get(db->objects, oid)) == NULL)
return GIT_ENOTFOUND;
*len_p = obj->len;
*type_p = obj->type;
*buffer_p = git__malloc(obj->len);
GIT_ERROR_CHECK_ALLOC(*buffer_p);
memcpy(*buffer_p, obj->data, obj->len);
return 0;
}
static int impl__read_header(size_t *len_p, git_object_t *type_p, git_odb_backend *backend, const git_oid *oid)
{
struct memory_packer_db *db = (struct memory_packer_db *)backend;
struct memobject *obj;
if ((obj = git_oidmap_get(db->objects, oid)) == NULL)
return GIT_ENOTFOUND;
*len_p = obj->len;
*type_p = obj->type;
return 0;
}
int git_mempack_dump(git_buf *pack, git_repository *repo, git_odb_backend *_backend)
{
struct memory_packer_db *db = (struct memory_packer_db *)_backend;
git_packbuilder *packbuilder;
uint32_t i;
int err = -1;
if (git_packbuilder_new(&packbuilder, repo) < 0)
return -1;
git_packbuilder_set_threads(packbuilder, 0);
for (i = 0; i < db->commits.size; ++i) {
struct memobject *commit = db->commits.ptr[i];
err = git_packbuilder_insert_commit(packbuilder, &commit->oid);
if (err < 0)
goto cleanup;
}
err = git_packbuilder_write_buf(pack, packbuilder);
cleanup:
git_packbuilder_free(packbuilder);
return err;
}
int git_mempack_reset(git_odb_backend *_backend)
{
struct memory_packer_db *db = (struct memory_packer_db *)_backend;
struct memobject *object = NULL;
git_oidmap_foreach_value(db->objects, object, {
git__free(object);
});
git_array_clear(db->commits);
git_oidmap_clear(db->objects);
return 0;
}
static void impl__free(git_odb_backend *_backend)
{
struct memory_packer_db *db = (struct memory_packer_db *)_backend;
git_mempack_reset(_backend);
git_oidmap_free(db->objects);
git__free(db);
}
int git_mempack_new(git_odb_backend **out)
{
struct memory_packer_db *db;
GIT_ASSERT_ARG(out);
db = git__calloc(1, sizeof(struct memory_packer_db));
GIT_ERROR_CHECK_ALLOC(db);
if (git_oidmap_new(&db->objects) < 0)
return -1;
db->parent.version = GIT_ODB_BACKEND_VERSION;
db->parent.read = &impl__read;
db->parent.write = &impl__write;
db->parent.read_header = &impl__read_header;
db->parent.exists = &impl__exists;
db->parent.free = &impl__free;
*out = (git_odb_backend *)db;
return 0;
}
|
0 |
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2
|
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2/src/config_parse.h
|
/*
* Copyright (C) the libgit2 contributors. All rights reserved.
*
* This file is part of libgit2, distributed under the GNU GPL v2 with
* a Linking Exception. For full terms see the included COPYING file.
*/
#ifndef INCLUDE_config_parse_h__
#define INCLUDE_config_parse_h__
#include "common.h"
#include "array.h"
#include "futils.h"
#include "oid.h"
#include "parse.h"
extern const char *git_config_escapes;
extern const char *git_config_escaped;
typedef struct {
const char *path;
git_parse_ctx ctx;
} git_config_parser;
#define GIT_CONFIG_PARSER_INIT { NULL, GIT_PARSE_CTX_INIT }
typedef int (*git_config_parser_section_cb)(
git_config_parser *parser,
const char *current_section,
const char *line,
size_t line_len,
void *payload);
typedef int (*git_config_parser_variable_cb)(
git_config_parser *parser,
const char *current_section,
const char *var_name,
const char *var_value,
const char *line,
size_t line_len,
void *payload);
typedef int (*git_config_parser_comment_cb)(
git_config_parser *parser,
const char *line,
size_t line_len,
void *payload);
typedef int (*git_config_parser_eof_cb)(
git_config_parser *parser,
const char *current_section,
void *payload);
int git_config_parser_init(git_config_parser *out, const char *path, const char *data, size_t datalen);
void git_config_parser_dispose(git_config_parser *parser);
int git_config_parse(
git_config_parser *parser,
git_config_parser_section_cb on_section,
git_config_parser_variable_cb on_variable,
git_config_parser_comment_cb on_comment,
git_config_parser_eof_cb on_eof,
void *payload);
#endif
|
0 |
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2
|
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2/src/tree.h
|
/*
* Copyright (C) the libgit2 contributors. All rights reserved.
*
* This file is part of libgit2, distributed under the GNU GPL v2 with
* a Linking Exception. For full terms see the included COPYING file.
*/
#ifndef INCLUDE_tree_h__
#define INCLUDE_tree_h__
#include "common.h"
#include "git2/tree.h"
#include "repository.h"
#include "odb.h"
#include "vector.h"
#include "strmap.h"
#include "pool.h"
struct git_tree_entry {
uint16_t attr;
uint16_t filename_len;
const git_oid *oid;
const char *filename;
};
struct git_tree {
git_object object;
git_odb_object *odb_obj;
git_array_t(git_tree_entry) entries;
};
struct git_treebuilder {
git_repository *repo;
git_strmap *map;
git_buf write_cache;
};
GIT_INLINE(bool) git_tree_entry__is_tree(const struct git_tree_entry *e)
{
return (S_ISDIR(e->attr) && !S_ISGITLINK(e->attr));
}
void git_tree__free(void *tree);
int git_tree__parse(void *tree, git_odb_object *obj);
int git_tree__parse_raw(void *_tree, const char *data, size_t size);
/**
* Write a tree to the given repository
*/
int git_tree__write_index(
git_oid *oid, git_index *index, git_repository *repo);
/**
* Obsolete mode kept for compatibility reasons
*/
#define GIT_FILEMODE_BLOB_GROUP_WRITABLE 0100664
#endif
|
0 |
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2
|
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2/src/thread.c
|
/*
* Copyright (C) the libgit2 contributors. All rights reserved.
*
* This file is part of libgit2, distributed under the GNU GPL v2 with
* a Linking Exception. For full terms see the included COPYING file.
*/
#include "common.h"
#if !defined(GIT_THREADS)
#define TLSDATA_MAX 16
typedef struct {
void *value;
void (GIT_SYSTEM_CALL *destroy_fn)(void *);
} tlsdata_value;
static tlsdata_value tlsdata_values[TLSDATA_MAX];
static int tlsdata_cnt = 0;
int git_tlsdata_init(git_tlsdata_key *key, void (GIT_SYSTEM_CALL *destroy_fn)(void *))
{
if (tlsdata_cnt >= TLSDATA_MAX)
return -1;
tlsdata_values[tlsdata_cnt].value = NULL;
tlsdata_values[tlsdata_cnt].destroy_fn = destroy_fn;
*key = tlsdata_cnt;
tlsdata_cnt++;
return 0;
}
int git_tlsdata_set(git_tlsdata_key key, void *value)
{
if (key < 0 || key > tlsdata_cnt)
return -1;
tlsdata_values[key].value = value;
return 0;
}
void *git_tlsdata_get(git_tlsdata_key key)
{
if (key < 0 || key > tlsdata_cnt)
return NULL;
return tlsdata_values[key].value;
}
int git_tlsdata_dispose(git_tlsdata_key key)
{
void *value;
void (*destroy_fn)(void *) = NULL;
if (key < 0 || key > tlsdata_cnt)
return -1;
value = tlsdata_values[key].value;
destroy_fn = tlsdata_values[key].destroy_fn;
tlsdata_values[key].value = NULL;
tlsdata_values[key].destroy_fn = NULL;
if (value && destroy_fn)
destroy_fn(value);
return 0;
}
#elif defined(GIT_WIN32)
int git_tlsdata_init(git_tlsdata_key *key, void (GIT_SYSTEM_CALL *destroy_fn)(void *))
{
DWORD fls_index = FlsAlloc(destroy_fn);
if (fls_index == FLS_OUT_OF_INDEXES)
return -1;
*key = fls_index;
return 0;
}
int git_tlsdata_set(git_tlsdata_key key, void *value)
{
if (!FlsSetValue(key, value))
return -1;
return 0;
}
void *git_tlsdata_get(git_tlsdata_key key)
{
return FlsGetValue(key);
}
int git_tlsdata_dispose(git_tlsdata_key key)
{
if (!FlsFree(key))
return -1;
return 0;
}
#elif defined(_POSIX_THREADS)
int git_tlsdata_init(git_tlsdata_key *key, void (GIT_SYSTEM_CALL *destroy_fn)(void *))
{
if (pthread_key_create(key, destroy_fn) != 0)
return -1;
return 0;
}
int git_tlsdata_set(git_tlsdata_key key, void *value)
{
if (pthread_setspecific(key, value) != 0)
return -1;
return 0;
}
void *git_tlsdata_get(git_tlsdata_key key)
{
return pthread_getspecific(key);
}
int git_tlsdata_dispose(git_tlsdata_key key)
{
if (pthread_key_delete(key) != 0)
return -1;
return 0;
}
#else
# error unknown threading model
#endif
|
0 |
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2
|
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2/src/revwalk.h
|
/*
* Copyright (C) the libgit2 contributors. All rights reserved.
*
* This file is part of libgit2, distributed under the GNU GPL v2 with
* a Linking Exception. For full terms see the included COPYING file.
*/
#ifndef INCLUDE_revwalk_h__
#define INCLUDE_revwalk_h__
#include "common.h"
#include "git2/revwalk.h"
#include "oidmap.h"
#include "commit_list.h"
#include "pqueue.h"
#include "pool.h"
#include "vector.h"
#include "oidmap.h"
struct git_revwalk {
git_repository *repo;
git_odb *odb;
git_oidmap *commits;
git_pool commit_pool;
git_commit_list *iterator_topo;
git_commit_list *iterator_rand;
git_commit_list *iterator_reverse;
git_pqueue iterator_time;
int (*get_next)(git_commit_list_node **, git_revwalk *);
int (*enqueue)(git_revwalk *, git_commit_list_node *);
unsigned walking:1,
first_parent: 1,
did_hide: 1,
did_push: 1,
limited: 1;
unsigned int sorting;
/* the pushes and hides */
git_commit_list *user_input;
/* hide callback */
git_revwalk_hide_cb hide_cb;
void *hide_cb_payload;
};
git_commit_list_node *git_revwalk__commit_lookup(git_revwalk *walk, const git_oid *oid);
typedef struct {
int uninteresting;
int from_glob;
int insert_by_date;
} git_revwalk__push_options;
#define GIT_REVWALK__PUSH_OPTIONS_INIT { 0 }
int git_revwalk__push_commit(git_revwalk *walk,
const git_oid *oid,
const git_revwalk__push_options *opts);
int git_revwalk__push_ref(git_revwalk *walk,
const char *refname,
const git_revwalk__push_options *opts);
int git_revwalk__push_glob(git_revwalk *walk,
const char *glob,
const git_revwalk__push_options *given_opts);
#endif
|
0 |
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2
|
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2/src/pathspec.h
|
/*
* Copyright (C) the libgit2 contributors. All rights reserved.
*
* This file is part of libgit2, distributed under the GNU GPL v2 with
* a Linking Exception. For full terms see the included COPYING file.
*/
#ifndef INCLUDE_pathspec_h__
#define INCLUDE_pathspec_h__
#include "common.h"
#include "git2/pathspec.h"
#include "buffer.h"
#include "vector.h"
#include "pool.h"
#include "array.h"
/* public compiled pathspec */
struct git_pathspec {
git_refcount rc;
char *prefix;
git_vector pathspec;
git_pool pool;
};
enum {
PATHSPEC_DATATYPE_STRINGS = 0,
PATHSPEC_DATATYPE_DIFF = 1,
};
typedef git_array_t(char *) git_pathspec_string_array_t;
/* public interface to pathspec matching */
struct git_pathspec_match_list {
git_pathspec *pathspec;
git_array_t(void *) matches;
git_pathspec_string_array_t failures;
git_pool pool;
int datatype;
};
/* what is the common non-wildcard prefix for all items in the pathspec */
extern char *git_pathspec_prefix(const git_strarray *pathspec);
/* is there anything in the spec that needs to be filtered on */
extern bool git_pathspec_is_empty(const git_strarray *pathspec);
/* build a vector of fnmatch patterns to evaluate efficiently */
extern int git_pathspec__vinit(
git_vector *vspec, const git_strarray *strspec, git_pool *strpool);
/* free data from the pathspec vector */
extern void git_pathspec__vfree(git_vector *vspec);
#define GIT_PATHSPEC_NOMATCH ((size_t)-1)
/*
* Match a path against the vectorized pathspec.
* The matched pathspec is passed back into the `matched_pathspec` parameter,
* unless it is passed as NULL by the caller.
*/
extern bool git_pathspec__match(
const git_vector *vspec,
const char *path,
bool disable_fnmatch,
bool casefold,
const char **matched_pathspec,
size_t *matched_at);
/* easy pathspec setup */
extern int git_pathspec__init(git_pathspec *ps, const git_strarray *paths);
extern void git_pathspec__clear(git_pathspec *ps);
#endif
|
0 |
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2
|
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2/src/config_entries.c
|
/*
* Copyright (C) the libgit2 contributors. All rights reserved.
*
* This file is part of libgit2, distributed under the GNU GPL v2 with
* a Linking Exception. For full terms see the included COPYING file.
*/
#include "config_entries.h"
typedef struct config_entry_list {
struct config_entry_list *next;
struct config_entry_list *last;
git_config_entry *entry;
} config_entry_list;
typedef struct {
git_config_entry *entry;
bool multivar;
} config_entry_map_head;
typedef struct config_entries_iterator {
git_config_iterator parent;
git_config_entries *entries;
config_entry_list *head;
} config_entries_iterator;
struct git_config_entries {
git_refcount rc;
git_strmap *map;
config_entry_list *list;
};
int git_config_entries_new(git_config_entries **out)
{
git_config_entries *entries;
int error;
entries = git__calloc(1, sizeof(git_config_entries));
GIT_ERROR_CHECK_ALLOC(entries);
GIT_REFCOUNT_INC(entries);
if ((error = git_strmap_new(&entries->map)) < 0)
git__free(entries);
else
*out = entries;
return error;
}
int git_config_entries_dup_entry(git_config_entries *entries, const git_config_entry *entry)
{
git_config_entry *duplicated;
int error;
duplicated = git__calloc(1, sizeof(git_config_entry));
GIT_ERROR_CHECK_ALLOC(duplicated);
duplicated->name = git__strdup(entry->name);
GIT_ERROR_CHECK_ALLOC(duplicated->name);
if (entry->value) {
duplicated->value = git__strdup(entry->value);
GIT_ERROR_CHECK_ALLOC(duplicated->value);
}
duplicated->level = entry->level;
duplicated->include_depth = entry->include_depth;
if ((error = git_config_entries_append(entries, duplicated)) < 0)
goto out;
out:
if (error && duplicated) {
git__free((char *) duplicated->name);
git__free((char *) duplicated->value);
git__free(duplicated);
}
return error;
}
int git_config_entries_dup(git_config_entries **out, git_config_entries *entries)
{
git_config_entries *result = NULL;
config_entry_list *head;
int error;
if ((error = git_config_entries_new(&result)) < 0)
goto out;
for (head = entries->list; head; head = head->next)
if ((git_config_entries_dup_entry(result, head->entry)) < 0)
goto out;
*out = result;
result = NULL;
out:
git_config_entries_free(result);
return error;
}
void git_config_entries_incref(git_config_entries *entries)
{
GIT_REFCOUNT_INC(entries);
}
static void config_entries_free(git_config_entries *entries)
{
config_entry_list *list = NULL, *next;
config_entry_map_head *head;
git_strmap_foreach_value(entries->map, head,
git__free((char *) head->entry->name); git__free(head)
);
git_strmap_free(entries->map);
list = entries->list;
while (list != NULL) {
next = list->next;
git__free((char *) list->entry->value);
git__free(list->entry);
git__free(list);
list = next;
}
git__free(entries);
}
void git_config_entries_free(git_config_entries *entries)
{
if (entries)
GIT_REFCOUNT_DEC(entries, config_entries_free);
}
int git_config_entries_append(git_config_entries *entries, git_config_entry *entry)
{
config_entry_list *list_head;
config_entry_map_head *map_head;
if ((map_head = git_strmap_get(entries->map, entry->name)) != NULL) {
map_head->multivar = true;
/*
* This is a micro-optimization for configuration files
* with a lot of same keys. As for multivars the entry's
* key will be the same for all entries, we can just free
* all except the first entry's name and just re-use it.
*/
git__free((char *) entry->name);
entry->name = map_head->entry->name;
} else {
map_head = git__calloc(1, sizeof(*map_head));
if ((git_strmap_set(entries->map, entry->name, map_head)) < 0)
return -1;
}
map_head->entry = entry;
list_head = git__calloc(1, sizeof(config_entry_list));
GIT_ERROR_CHECK_ALLOC(list_head);
list_head->entry = entry;
if (entries->list)
entries->list->last->next = list_head;
else
entries->list = list_head;
entries->list->last = list_head;
return 0;
}
int git_config_entries_get(git_config_entry **out, git_config_entries *entries, const char *key)
{
config_entry_map_head *entry;
if ((entry = git_strmap_get(entries->map, key)) == NULL)
return GIT_ENOTFOUND;
*out = entry->entry;
return 0;
}
int git_config_entries_get_unique(git_config_entry **out, git_config_entries *entries, const char *key)
{
config_entry_map_head *entry;
if ((entry = git_strmap_get(entries->map, key)) == NULL)
return GIT_ENOTFOUND;
if (entry->multivar) {
git_error_set(GIT_ERROR_CONFIG, "entry is not unique due to being a multivar");
return -1;
}
if (entry->entry->include_depth) {
git_error_set(GIT_ERROR_CONFIG, "entry is not unique due to being included");
return -1;
}
*out = entry->entry;
return 0;
}
static void config_iterator_free(git_config_iterator *iter)
{
config_entries_iterator *it = (config_entries_iterator *) iter;
git_config_entries_free(it->entries);
git__free(it);
}
static int config_iterator_next(
git_config_entry **entry,
git_config_iterator *iter)
{
config_entries_iterator *it = (config_entries_iterator *) iter;
if (!it->head)
return GIT_ITEROVER;
*entry = it->head->entry;
it->head = it->head->next;
return 0;
}
int git_config_entries_iterator_new(git_config_iterator **out, git_config_entries *entries)
{
config_entries_iterator *it;
it = git__calloc(1, sizeof(config_entries_iterator));
GIT_ERROR_CHECK_ALLOC(it);
it->parent.next = config_iterator_next;
it->parent.free = config_iterator_free;
it->head = entries->list;
it->entries = entries;
git_config_entries_incref(entries);
*out = &it->parent;
return 0;
}
|
0 |
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2
|
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2/src/diff_driver.h
|
/*
* Copyright (C) the libgit2 contributors. All rights reserved.
*
* This file is part of libgit2, distributed under the GNU GPL v2 with
* a Linking Exception. For full terms see the included COPYING file.
*/
#ifndef INCLUDE_diff_driver_h__
#define INCLUDE_diff_driver_h__
#include "common.h"
#include "attr_file.h"
#include "buffer.h"
typedef struct git_diff_driver_registry git_diff_driver_registry;
git_diff_driver_registry *git_diff_driver_registry_new(void);
void git_diff_driver_registry_free(git_diff_driver_registry *);
typedef struct git_diff_driver git_diff_driver;
int git_diff_driver_lookup(git_diff_driver **, git_repository *,
git_attr_session *attrsession, const char *);
void git_diff_driver_free(git_diff_driver *);
/* diff option flags to force off and on for this driver */
void git_diff_driver_update_options(uint32_t *option_flags, git_diff_driver *);
/* returns -1 meaning "unknown", 0 meaning not binary, 1 meaning binary */
int git_diff_driver_content_is_binary(
git_diff_driver *, const char *content, size_t content_len);
typedef long (*git_diff_find_context_fn)(
const char *, long, char *, long, void *);
typedef int (*git_diff_find_context_line)(
git_diff_driver *, git_buf *);
typedef struct {
git_diff_driver *driver;
git_diff_find_context_line match_line;
git_buf line;
} git_diff_find_context_payload;
void git_diff_find_context_init(
git_diff_find_context_fn *findfn_out,
git_diff_find_context_payload *payload_out,
git_diff_driver *driver);
void git_diff_find_context_clear(git_diff_find_context_payload *);
#endif
|
0 |
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2
|
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2/src/futils.h
|
/*
* Copyright (C) the libgit2 contributors. All rights reserved.
*
* This file is part of libgit2, distributed under the GNU GPL v2 with
* a Linking Exception. For full terms see the included COPYING file.
*/
#ifndef INCLUDE_futils_h__
#define INCLUDE_futils_h__
#include "common.h"
#include "map.h"
#include "posix.h"
#include "path.h"
#include "pool.h"
#include "strmap.h"
#include "oid.h"
/**
* Filebuffer methods
*
* Read whole files into an in-memory buffer for processing
*/
extern int git_futils_readbuffer(git_buf *obj, const char *path);
extern int git_futils_readbuffer_updated(
git_buf *obj, const char *path, git_oid *checksum, int *updated);
extern int git_futils_readbuffer_fd(git_buf *obj, git_file fd, size_t len);
/* Additional constants for `git_futils_writebuffer`'s `open_flags`. We
* support these internally and they will be removed before the `open` call.
*/
#ifndef O_FSYNC
# define O_FSYNC (1 << 31)
#endif
extern int git_futils_writebuffer(
const git_buf *buf, const char *path, int open_flags, mode_t mode);
/**
* File utils
*
* These are custom filesystem-related helper methods. They are
* rather high level, and wrap the underlying POSIX methods
*
* All these methods return 0 on success,
* or an error code on failure and an error message is set.
*/
/**
* Create and open a file, while also
* creating all the folders in its path
*/
extern int git_futils_creat_withpath(const char *path, const mode_t dirmode, const mode_t mode);
/**
* Create and open a process-locked file
*/
extern int git_futils_creat_locked(const char *path, const mode_t mode);
/**
* Create and open a process-locked file, while
* also creating all the folders in its path
*/
extern int git_futils_creat_locked_withpath(const char *path, const mode_t dirmode, const mode_t mode);
/**
* Create a path recursively.
*/
extern int git_futils_mkdir_r(const char *path, const mode_t mode);
/**
* Flags to pass to `git_futils_mkdir`.
*
* * GIT_MKDIR_EXCL is "exclusive" - i.e. generate an error if dir exists.
* * GIT_MKDIR_PATH says to make all components in the path.
* * GIT_MKDIR_CHMOD says to chmod the final directory entry after creation
* * GIT_MKDIR_CHMOD_PATH says to chmod each directory component in the path
* * GIT_MKDIR_SKIP_LAST says to leave off the last element of the path
* * GIT_MKDIR_SKIP_LAST2 says to leave off the last 2 elements of the path
* * GIT_MKDIR_VERIFY_DIR says confirm final item is a dir, not just EEXIST
* * GIT_MKDIR_REMOVE_FILES says to remove files and recreate dirs
* * GIT_MKDIR_REMOVE_SYMLINKS says to remove symlinks and recreate dirs
*
* Note that the chmod options will be executed even if the directory already
* exists, unless GIT_MKDIR_EXCL is given.
*/
typedef enum {
GIT_MKDIR_EXCL = 1,
GIT_MKDIR_PATH = 2,
GIT_MKDIR_CHMOD = 4,
GIT_MKDIR_CHMOD_PATH = 8,
GIT_MKDIR_SKIP_LAST = 16,
GIT_MKDIR_SKIP_LAST2 = 32,
GIT_MKDIR_VERIFY_DIR = 64,
GIT_MKDIR_REMOVE_FILES = 128,
GIT_MKDIR_REMOVE_SYMLINKS = 256,
} git_futils_mkdir_flags;
struct git_futils_mkdir_perfdata
{
size_t stat_calls;
size_t mkdir_calls;
size_t chmod_calls;
};
struct git_futils_mkdir_options
{
git_strmap *dir_map;
git_pool *pool;
struct git_futils_mkdir_perfdata perfdata;
};
/**
* Create a directory or entire path.
*
* This makes a directory (and the entire path leading up to it if requested),
* and optionally chmods the directory immediately after (or each part of the
* path if requested).
*
* @param path The path to create, relative to base.
* @param base Root for relative path. These directories will never be made.
* @param mode The mode to use for created directories.
* @param flags Combination of the mkdir flags above.
* @param opts Extended options, or null.
* @return 0 on success, else error code
*/
extern int git_futils_mkdir_relative(const char *path, const char *base, mode_t mode, uint32_t flags, struct git_futils_mkdir_options *opts);
/**
* Create a directory or entire path. Similar to `git_futils_mkdir_relative`
* without performance data.
*/
extern int git_futils_mkdir(const char *path, mode_t mode, uint32_t flags);
/**
* Create all the folders required to contain
* the full path of a file
*/
extern int git_futils_mkpath2file(const char *path, const mode_t mode);
/**
* Flags to pass to `git_futils_rmdir_r`.
*
* * GIT_RMDIR_EMPTY_HIERARCHY - the default; remove hierarchy of empty
* dirs and generate error if any files are found.
* * GIT_RMDIR_REMOVE_FILES - attempt to remove files in the hierarchy.
* * GIT_RMDIR_SKIP_NONEMPTY - skip non-empty directories with no error.
* * GIT_RMDIR_EMPTY_PARENTS - remove containing directories up to base
* if removing this item leaves them empty
* * GIT_RMDIR_REMOVE_BLOCKERS - remove blocking file that causes ENOTDIR
* * GIT_RMDIR_SKIP_ROOT - don't remove root directory itself
*/
typedef enum {
GIT_RMDIR_EMPTY_HIERARCHY = 0,
GIT_RMDIR_REMOVE_FILES = (1 << 0),
GIT_RMDIR_SKIP_NONEMPTY = (1 << 1),
GIT_RMDIR_EMPTY_PARENTS = (1 << 2),
GIT_RMDIR_REMOVE_BLOCKERS = (1 << 3),
GIT_RMDIR_SKIP_ROOT = (1 << 4),
} git_futils_rmdir_flags;
/**
* Remove path and any files and directories beneath it.
*
* @param path Path to the top level directory to process.
* @param base Root for relative path.
* @param flags Combination of git_futils_rmdir_flags values
* @return 0 on success; -1 on error.
*/
extern int git_futils_rmdir_r(const char *path, const char *base, uint32_t flags);
/**
* Create and open a temporary file with a `_git2_` suffix.
* Writes the filename into path_out.
* @return On success, an open file descriptor, else an error code < 0.
*/
extern int git_futils_mktmp(git_buf *path_out, const char *filename, mode_t mode);
/**
* Move a file on the filesystem, create the
* destination path if it doesn't exist
*/
extern int git_futils_mv_withpath(const char *from, const char *to, const mode_t dirmode);
/**
* Copy a file
*
* The filemode will be used for the newly created file.
*/
extern int git_futils_cp(
const char *from,
const char *to,
mode_t filemode);
/**
* Set the files atime and mtime to the given time, or the current time
* if `ts` is NULL.
*/
extern int git_futils_touch(const char *path, time_t *when);
/**
* Flags that can be passed to `git_futils_cp_r`.
*
* - GIT_CPDIR_CREATE_EMPTY_DIRS: create directories even if there are no
* files under them (otherwise directories will only be created lazily
* when a file inside them is copied).
* - GIT_CPDIR_COPY_SYMLINKS: copy symlinks, otherwise they are ignored.
* - GIT_CPDIR_COPY_DOTFILES: copy files with leading '.', otherwise ignored.
* - GIT_CPDIR_OVERWRITE: overwrite pre-existing files with source content,
* otherwise they are silently skipped.
* - GIT_CPDIR_CHMOD_DIRS: explicitly chmod directories to `dirmode`
* - GIT_CPDIR_SIMPLE_TO_MODE: default tries to replicate the mode of the
* source file to the target; with this flag, always use 0666 (or 0777 if
* source has exec bits set) for target.
* - GIT_CPDIR_LINK_FILES will try to use hardlinks for the files
*/
typedef enum {
GIT_CPDIR_CREATE_EMPTY_DIRS = (1u << 0),
GIT_CPDIR_COPY_SYMLINKS = (1u << 1),
GIT_CPDIR_COPY_DOTFILES = (1u << 2),
GIT_CPDIR_OVERWRITE = (1u << 3),
GIT_CPDIR_CHMOD_DIRS = (1u << 4),
GIT_CPDIR_SIMPLE_TO_MODE = (1u << 5),
GIT_CPDIR_LINK_FILES = (1u << 6),
} git_futils_cpdir_flags;
/**
* Copy a directory tree.
*
* This copies directories and files from one root to another. You can
* pass a combinationof GIT_CPDIR flags as defined above.
*
* If you pass the CHMOD flag, then the dirmode will be applied to all
* directories that are created during the copy, overiding the natural
* permissions. If you do not pass the CHMOD flag, then the dirmode
* will actually be copied from the source files and the `dirmode` arg
* will be ignored.
*/
extern int git_futils_cp_r(
const char *from,
const char *to,
uint32_t flags,
mode_t dirmode);
/**
* Open a file readonly and set error if needed.
*/
extern int git_futils_open_ro(const char *path);
/**
* Truncate a file, creating it if it doesn't exist.
*/
extern int git_futils_truncate(const char *path, int mode);
/**
* Get the filesize in bytes of a file
*/
extern int git_futils_filesize(uint64_t *out, git_file fd);
#define GIT_PERMS_IS_EXEC(MODE) (((MODE) & 0100) != 0)
#define GIT_PERMS_CANONICAL(MODE) (GIT_PERMS_IS_EXEC(MODE) ? 0755 : 0644)
#define GIT_PERMS_FOR_WRITE(MODE) (GIT_PERMS_IS_EXEC(MODE) ? 0777 : 0666)
#define GIT_MODE_PERMS_MASK 0777
#define GIT_MODE_TYPE_MASK 0170000
#define GIT_MODE_TYPE(MODE) ((MODE) & GIT_MODE_TYPE_MASK)
#define GIT_MODE_ISBLOB(MODE) (GIT_MODE_TYPE(MODE) == GIT_MODE_TYPE(GIT_FILEMODE_BLOB))
/**
* Convert a mode_t from the OS to a legal git mode_t value.
*/
extern mode_t git_futils_canonical_mode(mode_t raw_mode);
/**
* Read-only map all or part of a file into memory.
* When possible this function should favor a virtual memory
* style mapping over some form of malloc()+read(), as the
* data access will be random and is not likely to touch the
* majority of the region requested.
*
* @param out buffer to populate with the mapping information.
* @param fd open descriptor to configure the mapping from.
* @param begin first byte to map, this should be page aligned.
* @param len number of bytes to map.
* @return
* - 0 on success;
* - -1 on error.
*/
extern int git_futils_mmap_ro(
git_map *out,
git_file fd,
off64_t begin,
size_t len);
/**
* Read-only map an entire file.
*
* @param out buffer to populate with the mapping information.
* @param path path to file to be opened.
* @return
* - 0 on success;
* - GIT_ENOTFOUND if not found;
* - -1 on an unspecified OS related error.
*/
extern int git_futils_mmap_ro_file(
git_map *out,
const char *path);
/**
* Release the memory associated with a previous memory mapping.
* @param map the mapping description previously configured.
*/
extern void git_futils_mmap_free(git_map *map);
/**
* Create a "fake" symlink (text file containing the target path).
*
* @param target original symlink target
* @param path symlink file to be created
* @return 0 on success, -1 on error
*/
extern int git_futils_fake_symlink(const char *target, const char *path);
/**
* A file stamp represents a snapshot of information about a file that can
* be used to test if the file changes. This portable implementation is
* based on stat data about that file, but it is possible that OS specific
* versions could be implemented in the future.
*/
typedef struct {
struct timespec mtime;
uint64_t size;
unsigned int ino;
} git_futils_filestamp;
/**
* Compare stat information for file with reference info.
*
* This function updates the file stamp to current data for the given path
* and returns 0 if the file is up-to-date relative to the prior setting,
* 1 if the file has been changed, or GIT_ENOTFOUND if the file doesn't
* exist. This will not call git_error_set, so you must set the error if you
* plan to return an error.
*
* @param stamp File stamp to be checked
* @param path Path to stat and check if changed
* @return 0 if up-to-date, 1 if out-of-date, GIT_ENOTFOUND if cannot stat
*/
extern int git_futils_filestamp_check(
git_futils_filestamp *stamp, const char *path);
/**
* Set or reset file stamp data
*
* This writes the target file stamp. If the source is NULL, this will set
* the target stamp to values that will definitely be out of date. If the
* source is not NULL, this copies the source values to the target.
*
* @param tgt File stamp to write to
* @param src File stamp to copy from or NULL to clear the target
*/
extern void git_futils_filestamp_set(
git_futils_filestamp *tgt, const git_futils_filestamp *src);
/**
* Set file stamp data from stat structure
*/
extern void git_futils_filestamp_set_from_stat(
git_futils_filestamp *stamp, struct stat *st);
/**
* `fsync` the parent directory of the given path, if `fsync` is
* supported for directories on this platform.
*
* @param path Path of the directory to sync.
* @return 0 on success, -1 on error
*/
extern int git_futils_fsync_dir(const char *path);
/**
* `fsync` the parent directory of the given path, if `fsync` is
* supported for directories on this platform.
*
* @param path Path of the file whose parent directory should be synced.
* @return 0 on success, -1 on error
*/
extern int git_futils_fsync_parent(const char *path);
#endif
|
0 |
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2
|
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2/src/config_entries.h
|
/*
* Copyright (C) the libgit2 contributors. All rights reserved.
*
* This file is part of libgit2, distributed under the GNU GPL v2 with
* a Linking Exception. For full terms see the included COPYING file.
*/
#include "common.h"
#include "git2/sys/config.h"
#include "config.h"
typedef struct git_config_entries git_config_entries;
int git_config_entries_new(git_config_entries **out);
int git_config_entries_dup(git_config_entries **out, git_config_entries *entries);
int git_config_entries_dup_entry(git_config_entries *entries, const git_config_entry *entry);
void git_config_entries_incref(git_config_entries *entries);
void git_config_entries_free(git_config_entries *entries);
/* Add or append the new config option */
int git_config_entries_append(git_config_entries *entries, git_config_entry *entry);
int git_config_entries_get(git_config_entry **out, git_config_entries *entries, const char *key);
int git_config_entries_get_unique(git_config_entry **out, git_config_entries *entries, const char *key);
int git_config_entries_iterator_new(git_config_iterator **out, git_config_entries *entries);
|
0 |
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2
|
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2/src/index.c
|
/*
* Copyright (C) the libgit2 contributors. All rights reserved.
*
* This file is part of libgit2, distributed under the GNU GPL v2 with
* a Linking Exception. For full terms see the included COPYING file.
*/
#include "index.h"
#include <stddef.h>
#include "repository.h"
#include "tree.h"
#include "tree-cache.h"
#include "hash.h"
#include "iterator.h"
#include "pathspec.h"
#include "ignore.h"
#include "blob.h"
#include "idxmap.h"
#include "diff.h"
#include "varint.h"
#include "git2/odb.h"
#include "git2/oid.h"
#include "git2/blob.h"
#include "git2/config.h"
#include "git2/sys/index.h"
static int index_apply_to_wd_diff(git_index *index, int action, const git_strarray *paths,
unsigned int flags,
git_index_matched_path_cb cb, void *payload);
#define minimal_entry_size (offsetof(struct entry_short, path))
static const size_t INDEX_FOOTER_SIZE = GIT_OID_RAWSZ;
static const size_t INDEX_HEADER_SIZE = 12;
static const unsigned int INDEX_VERSION_NUMBER_DEFAULT = 2;
static const unsigned int INDEX_VERSION_NUMBER_LB = 2;
static const unsigned int INDEX_VERSION_NUMBER_EXT = 3;
static const unsigned int INDEX_VERSION_NUMBER_COMP = 4;
static const unsigned int INDEX_VERSION_NUMBER_UB = 4;
static const unsigned int INDEX_HEADER_SIG = 0x44495243;
static const char INDEX_EXT_TREECACHE_SIG[] = {'T', 'R', 'E', 'E'};
static const char INDEX_EXT_UNMERGED_SIG[] = {'R', 'E', 'U', 'C'};
static const char INDEX_EXT_CONFLICT_NAME_SIG[] = {'N', 'A', 'M', 'E'};
#define INDEX_OWNER(idx) ((git_repository *)(GIT_REFCOUNT_OWNER(idx)))
struct index_header {
uint32_t signature;
uint32_t version;
uint32_t entry_count;
};
struct index_extension {
char signature[4];
uint32_t extension_size;
};
struct entry_time {
uint32_t seconds;
uint32_t nanoseconds;
};
struct entry_short {
struct entry_time ctime;
struct entry_time mtime;
uint32_t dev;
uint32_t ino;
uint32_t mode;
uint32_t uid;
uint32_t gid;
uint32_t file_size;
git_oid oid;
uint16_t flags;
char path[1]; /* arbitrary length */
};
struct entry_long {
struct entry_time ctime;
struct entry_time mtime;
uint32_t dev;
uint32_t ino;
uint32_t mode;
uint32_t uid;
uint32_t gid;
uint32_t file_size;
git_oid oid;
uint16_t flags;
uint16_t flags_extended;
char path[1]; /* arbitrary length */
};
struct entry_srch_key {
const char *path;
size_t pathlen;
int stage;
};
struct entry_internal {
git_index_entry entry;
size_t pathlen;
char path[GIT_FLEX_ARRAY];
};
struct reuc_entry_internal {
git_index_reuc_entry entry;
size_t pathlen;
char path[GIT_FLEX_ARRAY];
};
bool git_index__enforce_unsaved_safety = false;
/* local declarations */
static int read_extension(size_t *read_len, git_index *index, const char *buffer, size_t buffer_size);
static int read_header(struct index_header *dest, const void *buffer);
static int parse_index(git_index *index, const char *buffer, size_t buffer_size);
static bool is_index_extended(git_index *index);
static int write_index(git_oid *checksum, git_index *index, git_filebuf *file);
static void index_entry_free(git_index_entry *entry);
static void index_entry_reuc_free(git_index_reuc_entry *reuc);
GIT_INLINE(int) index_map_set(git_idxmap *map, git_index_entry *e, bool ignore_case)
{
if (ignore_case)
return git_idxmap_icase_set((git_idxmap_icase *) map, e, e);
else
return git_idxmap_set(map, e, e);
}
GIT_INLINE(int) index_map_delete(git_idxmap *map, git_index_entry *e, bool ignore_case)
{
if (ignore_case)
return git_idxmap_icase_delete((git_idxmap_icase *) map, e);
else
return git_idxmap_delete(map, e);
}
GIT_INLINE(int) index_map_resize(git_idxmap *map, size_t count, bool ignore_case)
{
if (ignore_case)
return git_idxmap_icase_resize((git_idxmap_icase *) map, count);
else
return git_idxmap_resize(map, count);
}
int git_index_entry_srch(const void *key, const void *array_member)
{
const struct entry_srch_key *srch_key = key;
const struct entry_internal *entry = array_member;
int cmp;
size_t len1, len2, len;
len1 = srch_key->pathlen;
len2 = entry->pathlen;
len = len1 < len2 ? len1 : len2;
cmp = memcmp(srch_key->path, entry->path, len);
if (cmp)
return cmp;
if (len1 < len2)
return -1;
if (len1 > len2)
return 1;
if (srch_key->stage != GIT_INDEX_STAGE_ANY)
return srch_key->stage - GIT_INDEX_ENTRY_STAGE(&entry->entry);
return 0;
}
int git_index_entry_isrch(const void *key, const void *array_member)
{
const struct entry_srch_key *srch_key = key;
const struct entry_internal *entry = array_member;
int cmp;
size_t len1, len2, len;
len1 = srch_key->pathlen;
len2 = entry->pathlen;
len = len1 < len2 ? len1 : len2;
cmp = strncasecmp(srch_key->path, entry->path, len);
if (cmp)
return cmp;
if (len1 < len2)
return -1;
if (len1 > len2)
return 1;
if (srch_key->stage != GIT_INDEX_STAGE_ANY)
return srch_key->stage - GIT_INDEX_ENTRY_STAGE(&entry->entry);
return 0;
}
static int index_entry_srch_path(const void *path, const void *array_member)
{
const git_index_entry *entry = array_member;
return strcmp((const char *)path, entry->path);
}
static int index_entry_isrch_path(const void *path, const void *array_member)
{
const git_index_entry *entry = array_member;
return strcasecmp((const char *)path, entry->path);
}
int git_index_entry_cmp(const void *a, const void *b)
{
int diff;
const git_index_entry *entry_a = a;
const git_index_entry *entry_b = b;
diff = strcmp(entry_a->path, entry_b->path);
if (diff == 0)
diff = (GIT_INDEX_ENTRY_STAGE(entry_a) - GIT_INDEX_ENTRY_STAGE(entry_b));
return diff;
}
int git_index_entry_icmp(const void *a, const void *b)
{
int diff;
const git_index_entry *entry_a = a;
const git_index_entry *entry_b = b;
diff = strcasecmp(entry_a->path, entry_b->path);
if (diff == 0)
diff = (GIT_INDEX_ENTRY_STAGE(entry_a) - GIT_INDEX_ENTRY_STAGE(entry_b));
return diff;
}
static int conflict_name_cmp(const void *a, const void *b)
{
const git_index_name_entry *name_a = a;
const git_index_name_entry *name_b = b;
if (name_a->ancestor && !name_b->ancestor)
return 1;
if (!name_a->ancestor && name_b->ancestor)
return -1;
if (name_a->ancestor)
return strcmp(name_a->ancestor, name_b->ancestor);
if (!name_a->ours || !name_b->ours)
return 0;
return strcmp(name_a->ours, name_b->ours);
}
/**
* TODO: enable this when resolving case insensitive conflicts
*/
#if 0
static int conflict_name_icmp(const void *a, const void *b)
{
const git_index_name_entry *name_a = a;
const git_index_name_entry *name_b = b;
if (name_a->ancestor && !name_b->ancestor)
return 1;
if (!name_a->ancestor && name_b->ancestor)
return -1;
if (name_a->ancestor)
return strcasecmp(name_a->ancestor, name_b->ancestor);
if (!name_a->ours || !name_b->ours)
return 0;
return strcasecmp(name_a->ours, name_b->ours);
}
#endif
static int reuc_srch(const void *key, const void *array_member)
{
const git_index_reuc_entry *reuc = array_member;
return strcmp(key, reuc->path);
}
static int reuc_isrch(const void *key, const void *array_member)
{
const git_index_reuc_entry *reuc = array_member;
return strcasecmp(key, reuc->path);
}
static int reuc_cmp(const void *a, const void *b)
{
const git_index_reuc_entry *info_a = a;
const git_index_reuc_entry *info_b = b;
return strcmp(info_a->path, info_b->path);
}
static int reuc_icmp(const void *a, const void *b)
{
const git_index_reuc_entry *info_a = a;
const git_index_reuc_entry *info_b = b;
return strcasecmp(info_a->path, info_b->path);
}
static void index_entry_reuc_free(git_index_reuc_entry *reuc)
{
git__free(reuc);
}
static void index_entry_free(git_index_entry *entry)
{
if (!entry)
return;
memset(&entry->id, 0, sizeof(entry->id));
git__free(entry);
}
unsigned int git_index__create_mode(unsigned int mode)
{
if (S_ISLNK(mode))
return S_IFLNK;
if (S_ISDIR(mode) || (mode & S_IFMT) == (S_IFLNK | S_IFDIR))
return (S_IFLNK | S_IFDIR);
return S_IFREG | GIT_PERMS_CANONICAL(mode);
}
static unsigned int index_merge_mode(
git_index *index, git_index_entry *existing, unsigned int mode)
{
if (index->no_symlinks && S_ISREG(mode) &&
existing && S_ISLNK(existing->mode))
return existing->mode;
if (index->distrust_filemode && S_ISREG(mode))
return (existing && S_ISREG(existing->mode)) ?
existing->mode : git_index__create_mode(0666);
return git_index__create_mode(mode);
}
GIT_INLINE(int) index_find_in_entries(
size_t *out, git_vector *entries, git_vector_cmp entry_srch,
const char *path, size_t path_len, int stage)
{
struct entry_srch_key srch_key;
srch_key.path = path;
srch_key.pathlen = !path_len ? strlen(path) : path_len;
srch_key.stage = stage;
return git_vector_bsearch2(out, entries, entry_srch, &srch_key);
}
GIT_INLINE(int) index_find(
size_t *out, git_index *index,
const char *path, size_t path_len, int stage)
{
git_vector_sort(&index->entries);
return index_find_in_entries(
out, &index->entries, index->entries_search, path, path_len, stage);
}
void git_index__set_ignore_case(git_index *index, bool ignore_case)
{
index->ignore_case = ignore_case;
if (ignore_case) {
index->entries_cmp_path = git__strcasecmp_cb;
index->entries_search = git_index_entry_isrch;
index->entries_search_path = index_entry_isrch_path;
index->reuc_search = reuc_isrch;
} else {
index->entries_cmp_path = git__strcmp_cb;
index->entries_search = git_index_entry_srch;
index->entries_search_path = index_entry_srch_path;
index->reuc_search = reuc_srch;
}
git_vector_set_cmp(&index->entries,
ignore_case ? git_index_entry_icmp : git_index_entry_cmp);
git_vector_sort(&index->entries);
git_vector_set_cmp(&index->reuc, ignore_case ? reuc_icmp : reuc_cmp);
git_vector_sort(&index->reuc);
}
int git_index_open(git_index **index_out, const char *index_path)
{
git_index *index;
int error = -1;
GIT_ASSERT_ARG(index_out);
index = git__calloc(1, sizeof(git_index));
GIT_ERROR_CHECK_ALLOC(index);
if (git_pool_init(&index->tree_pool, 1) < 0)
goto fail;
if (index_path != NULL) {
index->index_file_path = git__strdup(index_path);
if (!index->index_file_path)
goto fail;
/* Check if index file is stored on disk already */
if (git_path_exists(index->index_file_path) == true)
index->on_disk = 1;
}
if (git_vector_init(&index->entries, 32, git_index_entry_cmp) < 0 ||
git_idxmap_new(&index->entries_map) < 0 ||
git_vector_init(&index->names, 8, conflict_name_cmp) < 0 ||
git_vector_init(&index->reuc, 8, reuc_cmp) < 0 ||
git_vector_init(&index->deleted, 8, git_index_entry_cmp) < 0)
goto fail;
index->entries_cmp_path = git__strcmp_cb;
index->entries_search = git_index_entry_srch;
index->entries_search_path = index_entry_srch_path;
index->reuc_search = reuc_srch;
index->version = INDEX_VERSION_NUMBER_DEFAULT;
if (index_path != NULL && (error = git_index_read(index, true)) < 0)
goto fail;
*index_out = index;
GIT_REFCOUNT_INC(index);
return 0;
fail:
git_pool_clear(&index->tree_pool);
git_index_free(index);
return error;
}
int git_index_new(git_index **out)
{
return git_index_open(out, NULL);
}
static void index_free(git_index *index)
{
/* index iterators increment the refcount of the index, so if we
* get here then there should be no outstanding iterators.
*/
if (git_atomic32_get(&index->readers))
return;
git_index_clear(index);
git_idxmap_free(index->entries_map);
git_vector_free(&index->entries);
git_vector_free(&index->names);
git_vector_free(&index->reuc);
git_vector_free(&index->deleted);
git__free(index->index_file_path);
git__memzero(index, sizeof(*index));
git__free(index);
}
void git_index_free(git_index *index)
{
if (index == NULL)
return;
GIT_REFCOUNT_DEC(index, index_free);
}
/* call with locked index */
static void index_free_deleted(git_index *index)
{
int readers = (int)git_atomic32_get(&index->readers);
size_t i;
if (readers > 0 || !index->deleted.length)
return;
for (i = 0; i < index->deleted.length; ++i) {
git_index_entry *ie = git_atomic_swap(index->deleted.contents[i], NULL);
index_entry_free(ie);
}
git_vector_clear(&index->deleted);
}
/* call with locked index */
static int index_remove_entry(git_index *index, size_t pos)
{
int error = 0;
git_index_entry *entry = git_vector_get(&index->entries, pos);
if (entry != NULL) {
git_tree_cache_invalidate_path(index->tree, entry->path);
index_map_delete(index->entries_map, entry, index->ignore_case);
}
error = git_vector_remove(&index->entries, pos);
if (!error) {
if (git_atomic32_get(&index->readers) > 0) {
error = git_vector_insert(&index->deleted, entry);
} else {
index_entry_free(entry);
}
index->dirty = 1;
}
return error;
}
int git_index_clear(git_index *index)
{
int error = 0;
GIT_ASSERT_ARG(index);
index->dirty = 1;
index->tree = NULL;
git_pool_clear(&index->tree_pool);
git_idxmap_clear(index->entries_map);
while (!error && index->entries.length > 0)
error = index_remove_entry(index, index->entries.length - 1);
if (error)
goto done;
index_free_deleted(index);
if ((error = git_index_name_clear(index)) < 0 ||
(error = git_index_reuc_clear(index)) < 0)
goto done;
git_futils_filestamp_set(&index->stamp, NULL);
done:
return error;
}
static int create_index_error(int error, const char *msg)
{
git_error_set_str(GIT_ERROR_INDEX, msg);
return error;
}
int git_index_set_caps(git_index *index, int caps)
{
unsigned int old_ignore_case;
GIT_ASSERT_ARG(index);
old_ignore_case = index->ignore_case;
if (caps == GIT_INDEX_CAPABILITY_FROM_OWNER) {
git_repository *repo = INDEX_OWNER(index);
int val;
if (!repo)
return create_index_error(
-1, "cannot access repository to set index caps");
if (!git_repository__configmap_lookup(&val, repo, GIT_CONFIGMAP_IGNORECASE))
index->ignore_case = (val != 0);
if (!git_repository__configmap_lookup(&val, repo, GIT_CONFIGMAP_FILEMODE))
index->distrust_filemode = (val == 0);
if (!git_repository__configmap_lookup(&val, repo, GIT_CONFIGMAP_SYMLINKS))
index->no_symlinks = (val == 0);
}
else {
index->ignore_case = ((caps & GIT_INDEX_CAPABILITY_IGNORE_CASE) != 0);
index->distrust_filemode = ((caps & GIT_INDEX_CAPABILITY_NO_FILEMODE) != 0);
index->no_symlinks = ((caps & GIT_INDEX_CAPABILITY_NO_SYMLINKS) != 0);
}
if (old_ignore_case != index->ignore_case) {
git_index__set_ignore_case(index, (bool)index->ignore_case);
}
return 0;
}
int git_index_caps(const git_index *index)
{
return ((index->ignore_case ? GIT_INDEX_CAPABILITY_IGNORE_CASE : 0) |
(index->distrust_filemode ? GIT_INDEX_CAPABILITY_NO_FILEMODE : 0) |
(index->no_symlinks ? GIT_INDEX_CAPABILITY_NO_SYMLINKS : 0));
}
const git_oid *git_index_checksum(git_index *index)
{
return &index->checksum;
}
/**
* Returns 1 for changed, 0 for not changed and <0 for errors
*/
static int compare_checksum(git_index *index)
{
int fd;
ssize_t bytes_read;
git_oid checksum = {{ 0 }};
if ((fd = p_open(index->index_file_path, O_RDONLY)) < 0)
return fd;
if (p_lseek(fd, -20, SEEK_END) < 0) {
p_close(fd);
git_error_set(GIT_ERROR_OS, "failed to seek to end of file");
return -1;
}
bytes_read = p_read(fd, &checksum, GIT_OID_RAWSZ);
p_close(fd);
if (bytes_read < 0)
return -1;
return !!git_oid_cmp(&checksum, &index->checksum);
}
int git_index_read(git_index *index, int force)
{
int error = 0, updated;
git_buf buffer = GIT_BUF_INIT;
git_futils_filestamp stamp = index->stamp;
if (!index->index_file_path)
return create_index_error(-1,
"failed to read index: The index is in-memory only");
index->on_disk = git_path_exists(index->index_file_path);
if (!index->on_disk) {
if (force && (error = git_index_clear(index)) < 0)
return error;
index->dirty = 0;
return 0;
}
if ((updated = git_futils_filestamp_check(&stamp, index->index_file_path) < 0) ||
((updated = compare_checksum(index)) < 0)) {
git_error_set(
GIT_ERROR_INDEX,
"failed to read index: '%s' no longer exists",
index->index_file_path);
return updated;
}
if (!updated && !force)
return 0;
error = git_futils_readbuffer(&buffer, index->index_file_path);
if (error < 0)
return error;
index->tree = NULL;
git_pool_clear(&index->tree_pool);
error = git_index_clear(index);
if (!error)
error = parse_index(index, buffer.ptr, buffer.size);
if (!error) {
git_futils_filestamp_set(&index->stamp, &stamp);
index->dirty = 0;
}
git_buf_dispose(&buffer);
return error;
}
int git_index_read_safely(git_index *index)
{
if (git_index__enforce_unsaved_safety && index->dirty) {
git_error_set(GIT_ERROR_INDEX,
"the index has unsaved changes that would be overwritten by this operation");
return GIT_EINDEXDIRTY;
}
return git_index_read(index, false);
}
int git_index__changed_relative_to(
git_index *index, const git_oid *checksum)
{
/* attempt to update index (ignoring errors) */
if (git_index_read(index, false) < 0)
git_error_clear();
return !!git_oid_cmp(&index->checksum, checksum);
}
static bool is_racy_entry(git_index *index, const git_index_entry *entry)
{
/* Git special-cases submodules in the check */
if (S_ISGITLINK(entry->mode))
return false;
return git_index_entry_newer_than_index(entry, index);
}
/*
* Force the next diff to take a look at those entries which have the
* same timestamp as the current index.
*/
static int truncate_racily_clean(git_index *index)
{
size_t i;
int error;
git_index_entry *entry;
git_diff_options diff_opts = GIT_DIFF_OPTIONS_INIT;
git_diff *diff = NULL;
git_vector paths = GIT_VECTOR_INIT;
git_diff_delta *delta;
/* Nothing to do if there's no repo to talk about */
if (!INDEX_OWNER(index))
return 0;
/* If there's no workdir, we can't know where to even check */
if (!git_repository_workdir(INDEX_OWNER(index)))
return 0;
diff_opts.flags |= GIT_DIFF_INCLUDE_TYPECHANGE | GIT_DIFF_IGNORE_SUBMODULES | GIT_DIFF_DISABLE_PATHSPEC_MATCH;
git_vector_foreach(&index->entries, i, entry) {
if ((entry->flags_extended & GIT_INDEX_ENTRY_UPTODATE) == 0 &&
is_racy_entry(index, entry))
git_vector_insert(&paths, (char *)entry->path);
}
if (paths.length == 0)
goto done;
diff_opts.pathspec.count = paths.length;
diff_opts.pathspec.strings = (char **)paths.contents;
if ((error = git_diff_index_to_workdir(&diff, INDEX_OWNER(index), index, &diff_opts)) < 0)
return error;
git_vector_foreach(&diff->deltas, i, delta) {
entry = (git_index_entry *)git_index_get_bypath(index, delta->old_file.path, 0);
/* Ensure that we have a stage 0 for this file (ie, it's not a
* conflict), otherwise smudging it is quite pointless.
*/
if (entry) {
entry->file_size = 0;
index->dirty = 1;
}
}
done:
git_diff_free(diff);
git_vector_free(&paths);
return 0;
}
unsigned git_index_version(git_index *index)
{
GIT_ASSERT_ARG(index);
return index->version;
}
int git_index_set_version(git_index *index, unsigned int version)
{
GIT_ASSERT_ARG(index);
if (version < INDEX_VERSION_NUMBER_LB ||
version > INDEX_VERSION_NUMBER_UB) {
git_error_set(GIT_ERROR_INDEX, "invalid version number");
return -1;
}
index->version = version;
return 0;
}
int git_index_write(git_index *index)
{
git_indexwriter writer = GIT_INDEXWRITER_INIT;
int error;
truncate_racily_clean(index);
if ((error = git_indexwriter_init(&writer, index)) == 0 &&
(error = git_indexwriter_commit(&writer)) == 0)
index->dirty = 0;
git_indexwriter_cleanup(&writer);
return error;
}
const char *git_index_path(const git_index *index)
{
GIT_ASSERT_ARG_WITH_RETVAL(index, NULL);
return index->index_file_path;
}
int git_index_write_tree(git_oid *oid, git_index *index)
{
git_repository *repo;
GIT_ASSERT_ARG(oid);
GIT_ASSERT_ARG(index);
repo = INDEX_OWNER(index);
if (repo == NULL)
return create_index_error(-1, "Failed to write tree. "
"the index file is not backed up by an existing repository");
return git_tree__write_index(oid, index, repo);
}
int git_index_write_tree_to(
git_oid *oid, git_index *index, git_repository *repo)
{
GIT_ASSERT_ARG(oid);
GIT_ASSERT_ARG(index);
GIT_ASSERT_ARG(repo);
return git_tree__write_index(oid, index, repo);
}
size_t git_index_entrycount(const git_index *index)
{
GIT_ASSERT_ARG(index);
return index->entries.length;
}
const git_index_entry *git_index_get_byindex(
git_index *index, size_t n)
{
GIT_ASSERT_ARG_WITH_RETVAL(index, NULL);
git_vector_sort(&index->entries);
return git_vector_get(&index->entries, n);
}
const git_index_entry *git_index_get_bypath(
git_index *index, const char *path, int stage)
{
git_index_entry key = {{ 0 }};
git_index_entry *value;
GIT_ASSERT_ARG_WITH_RETVAL(index, NULL);
key.path = path;
GIT_INDEX_ENTRY_STAGE_SET(&key, stage);
if (index->ignore_case)
value = git_idxmap_icase_get((git_idxmap_icase *) index->entries_map, &key);
else
value = git_idxmap_get(index->entries_map, &key);
if (!value) {
git_error_set(GIT_ERROR_INDEX, "index does not contain '%s'", path);
return NULL;
}
return value;
}
void git_index_entry__init_from_stat(
git_index_entry *entry, struct stat *st, bool trust_mode)
{
entry->ctime.seconds = (int32_t)st->st_ctime;
entry->mtime.seconds = (int32_t)st->st_mtime;
#if defined(GIT_USE_NSEC)
entry->mtime.nanoseconds = st->st_mtime_nsec;
entry->ctime.nanoseconds = st->st_ctime_nsec;
#endif
entry->dev = st->st_rdev;
entry->ino = st->st_ino;
entry->mode = (!trust_mode && S_ISREG(st->st_mode)) ?
git_index__create_mode(0666) : git_index__create_mode(st->st_mode);
entry->uid = st->st_uid;
entry->gid = st->st_gid;
entry->file_size = (uint32_t)st->st_size;
}
static void index_entry_adjust_namemask(
git_index_entry *entry,
size_t path_length)
{
entry->flags &= ~GIT_INDEX_ENTRY_NAMEMASK;
if (path_length < GIT_INDEX_ENTRY_NAMEMASK)
entry->flags |= path_length & GIT_INDEX_ENTRY_NAMEMASK;
else
entry->flags |= GIT_INDEX_ENTRY_NAMEMASK;
}
/* When `from_workdir` is true, we will validate the paths to avoid placing
* paths that are invalid for the working directory on the current filesystem
* (eg, on Windows, we will disallow `GIT~1`, `AUX`, `COM1`, etc). This
* function will *always* prevent `.git` and directory traversal `../` from
* being added to the index.
*/
static int index_entry_create(
git_index_entry **out,
git_repository *repo,
const char *path,
struct stat *st,
bool from_workdir)
{
size_t pathlen = strlen(path), alloclen;
struct entry_internal *entry;
unsigned int path_valid_flags = GIT_PATH_REJECT_INDEX_DEFAULTS;
uint16_t mode = 0;
/* always reject placing `.git` in the index and directory traversal.
* when requested, disallow platform-specific filenames and upgrade to
* the platform-specific `.git` tests (eg, `git~1`, etc).
*/
if (from_workdir)
path_valid_flags |= GIT_PATH_REJECT_WORKDIR_DEFAULTS;
if (st)
mode = st->st_mode;
if (!git_path_validate(repo, path, mode, path_valid_flags)) {
git_error_set(GIT_ERROR_INDEX, "invalid path: '%s'", path);
return -1;
}
GIT_ERROR_CHECK_ALLOC_ADD(&alloclen, sizeof(struct entry_internal), pathlen);
GIT_ERROR_CHECK_ALLOC_ADD(&alloclen, alloclen, 1);
entry = git__calloc(1, alloclen);
GIT_ERROR_CHECK_ALLOC(entry);
entry->pathlen = pathlen;
memcpy(entry->path, path, pathlen);
entry->entry.path = entry->path;
*out = (git_index_entry *)entry;
return 0;
}
static int index_entry_init(
git_index_entry **entry_out,
git_index *index,
const char *rel_path)
{
int error = 0;
git_index_entry *entry = NULL;
git_buf path = GIT_BUF_INIT;
struct stat st;
git_oid oid;
git_repository *repo;
if (INDEX_OWNER(index) == NULL)
return create_index_error(-1,
"could not initialize index entry. "
"Index is not backed up by an existing repository.");
/*
* FIXME: this is duplicated with the work in
* git_blob__create_from_paths. It should accept an optional stat
* structure so we can pass in the one we have to do here.
*/
repo = INDEX_OWNER(index);
if (git_repository__ensure_not_bare(repo, "create blob from file") < 0)
return GIT_EBAREREPO;
if (git_repository_workdir_path(&path, repo, rel_path) < 0)
return -1;
error = git_path_lstat(path.ptr, &st);
git_buf_dispose(&path);
if (error < 0)
return error;
if (index_entry_create(&entry, INDEX_OWNER(index), rel_path, &st, true) < 0)
return -1;
/* write the blob to disk and get the oid and stat info */
error = git_blob__create_from_paths(
&oid, &st, INDEX_OWNER(index), NULL, rel_path, 0, true);
if (error < 0) {
index_entry_free(entry);
return error;
}
entry->id = oid;
git_index_entry__init_from_stat(entry, &st, !index->distrust_filemode);
*entry_out = (git_index_entry *)entry;
return 0;
}
static git_index_reuc_entry *reuc_entry_alloc(const char *path)
{
size_t pathlen = strlen(path),
structlen = sizeof(struct reuc_entry_internal),
alloclen;
struct reuc_entry_internal *entry;
if (GIT_ADD_SIZET_OVERFLOW(&alloclen, structlen, pathlen) ||
GIT_ADD_SIZET_OVERFLOW(&alloclen, alloclen, 1))
return NULL;
entry = git__calloc(1, alloclen);
if (!entry)
return NULL;
entry->pathlen = pathlen;
memcpy(entry->path, path, pathlen);
entry->entry.path = entry->path;
return (git_index_reuc_entry *)entry;
}
static int index_entry_reuc_init(git_index_reuc_entry **reuc_out,
const char *path,
int ancestor_mode, const git_oid *ancestor_oid,
int our_mode, const git_oid *our_oid,
int their_mode, const git_oid *their_oid)
{
git_index_reuc_entry *reuc = NULL;
GIT_ASSERT_ARG(reuc_out);
GIT_ASSERT_ARG(path);
*reuc_out = reuc = reuc_entry_alloc(path);
GIT_ERROR_CHECK_ALLOC(reuc);
if ((reuc->mode[0] = ancestor_mode) > 0) {
GIT_ASSERT(ancestor_oid);
git_oid_cpy(&reuc->oid[0], ancestor_oid);
}
if ((reuc->mode[1] = our_mode) > 0) {
GIT_ASSERT(our_oid);
git_oid_cpy(&reuc->oid[1], our_oid);
}
if ((reuc->mode[2] = their_mode) > 0) {
GIT_ASSERT(their_oid);
git_oid_cpy(&reuc->oid[2], their_oid);
}
return 0;
}
static void index_entry_cpy(
git_index_entry *tgt,
const git_index_entry *src)
{
const char *tgt_path = tgt->path;
memcpy(tgt, src, sizeof(*tgt));
tgt->path = tgt_path;
}
static int index_entry_dup(
git_index_entry **out,
git_index *index,
const git_index_entry *src)
{
if (index_entry_create(out, INDEX_OWNER(index), src->path, NULL, false) < 0)
return -1;
index_entry_cpy(*out, src);
return 0;
}
static void index_entry_cpy_nocache(
git_index_entry *tgt,
const git_index_entry *src)
{
git_oid_cpy(&tgt->id, &src->id);
tgt->mode = src->mode;
tgt->flags = src->flags;
tgt->flags_extended = (src->flags_extended & GIT_INDEX_ENTRY_EXTENDED_FLAGS);
}
static int index_entry_dup_nocache(
git_index_entry **out,
git_index *index,
const git_index_entry *src)
{
if (index_entry_create(out, INDEX_OWNER(index), src->path, NULL, false) < 0)
return -1;
index_entry_cpy_nocache(*out, src);
return 0;
}
static int has_file_name(git_index *index,
const git_index_entry *entry, size_t pos, int ok_to_replace)
{
size_t len = strlen(entry->path);
int stage = GIT_INDEX_ENTRY_STAGE(entry);
const char *name = entry->path;
while (pos < index->entries.length) {
struct entry_internal *p = index->entries.contents[pos++];
if (len >= p->pathlen)
break;
if (memcmp(name, p->path, len))
break;
if (GIT_INDEX_ENTRY_STAGE(&p->entry) != stage)
continue;
if (p->path[len] != '/')
continue;
if (!ok_to_replace)
return -1;
if (index_remove_entry(index, --pos) < 0)
break;
}
return 0;
}
/*
* Do we have another file with a pathname that is a proper
* subset of the name we're trying to add?
*/
static int has_dir_name(git_index *index,
const git_index_entry *entry, int ok_to_replace)
{
int stage = GIT_INDEX_ENTRY_STAGE(entry);
const char *name = entry->path;
const char *slash = name + strlen(name);
for (;;) {
size_t len, pos;
for (;;) {
if (*--slash == '/')
break;
if (slash <= entry->path)
return 0;
}
len = slash - name;
if (!index_find(&pos, index, name, len, stage)) {
if (!ok_to_replace)
return -1;
if (index_remove_entry(index, pos) < 0)
break;
continue;
}
/*
* Trivial optimization: if we find an entry that
* already matches the sub-directory, then we know
* we're ok, and we can exit.
*/
for (; pos < index->entries.length; ++pos) {
struct entry_internal *p = index->entries.contents[pos];
if (p->pathlen <= len ||
p->path[len] != '/' ||
memcmp(p->path, name, len))
break; /* not our subdirectory */
if (GIT_INDEX_ENTRY_STAGE(&p->entry) == stage)
return 0;
}
}
return 0;
}
static int check_file_directory_collision(git_index *index,
git_index_entry *entry, size_t pos, int ok_to_replace)
{
if (has_file_name(index, entry, pos, ok_to_replace) < 0 ||
has_dir_name(index, entry, ok_to_replace) < 0) {
git_error_set(GIT_ERROR_INDEX,
"'%s' appears as both a file and a directory", entry->path);
return -1;
}
return 0;
}
static int canonicalize_directory_path(
git_index *index,
git_index_entry *entry,
git_index_entry *existing)
{
const git_index_entry *match, *best = NULL;
char *search, *sep;
size_t pos, search_len, best_len;
if (!index->ignore_case)
return 0;
/* item already exists in the index, simply re-use the existing case */
if (existing) {
memcpy((char *)entry->path, existing->path, strlen(existing->path));
return 0;
}
/* nothing to do */
if (strchr(entry->path, '/') == NULL)
return 0;
if ((search = git__strdup(entry->path)) == NULL)
return -1;
/* starting at the parent directory and descending to the root, find the
* common parent directory.
*/
while (!best && (sep = strrchr(search, '/'))) {
sep[1] = '\0';
search_len = strlen(search);
git_vector_bsearch2(
&pos, &index->entries, index->entries_search_path, search);
while ((match = git_vector_get(&index->entries, pos))) {
if (GIT_INDEX_ENTRY_STAGE(match) != 0) {
/* conflicts do not contribute to canonical paths */
} else if (strncmp(search, match->path, search_len) == 0) {
/* prefer an exact match to the input filename */
best = match;
best_len = search_len;
break;
} else if (strncasecmp(search, match->path, search_len) == 0) {
/* continue walking, there may be a path with an exact
* (case sensitive) match later in the index, but use this
* as the best match until that happens.
*/
if (!best) {
best = match;
best_len = search_len;
}
} else {
break;
}
pos++;
}
sep[0] = '\0';
}
if (best)
memcpy((char *)entry->path, best->path, best_len);
git__free(search);
return 0;
}
static int index_no_dups(void **old, void *new)
{
const git_index_entry *entry = new;
GIT_UNUSED(old);
git_error_set(GIT_ERROR_INDEX, "'%s' appears multiple times at stage %d",
entry->path, GIT_INDEX_ENTRY_STAGE(entry));
return GIT_EEXISTS;
}
static void index_existing_and_best(
git_index_entry **existing,
size_t *existing_position,
git_index_entry **best,
git_index *index,
const git_index_entry *entry)
{
git_index_entry *e;
size_t pos;
int error;
error = index_find(&pos,
index, entry->path, 0, GIT_INDEX_ENTRY_STAGE(entry));
if (error == 0) {
*existing = index->entries.contents[pos];
*existing_position = pos;
*best = index->entries.contents[pos];
return;
}
*existing = NULL;
*existing_position = 0;
*best = NULL;
if (GIT_INDEX_ENTRY_STAGE(entry) == 0) {
for (; pos < index->entries.length; pos++) {
int (*strcomp)(const char *a, const char *b) =
index->ignore_case ? git__strcasecmp : git__strcmp;
e = index->entries.contents[pos];
if (strcomp(entry->path, e->path) != 0)
break;
if (GIT_INDEX_ENTRY_STAGE(e) == GIT_INDEX_STAGE_ANCESTOR) {
*best = e;
continue;
} else {
*best = e;
break;
}
}
}
}
/* index_insert takes ownership of the new entry - if it can't insert
* it, then it will return an error **and also free the entry**. When
* it replaces an existing entry, it will update the entry_ptr with the
* actual entry in the index (and free the passed in one).
*
* trust_path is whether we use the given path, or whether (on case
* insensitive systems only) we try to canonicalize the given path to
* be within an existing directory.
*
* trust_mode is whether we trust the mode in entry_ptr.
*
* trust_id is whether we trust the id or it should be validated.
*/
static int index_insert(
git_index *index,
git_index_entry **entry_ptr,
int replace,
bool trust_path,
bool trust_mode,
bool trust_id)
{
git_index_entry *existing, *best, *entry;
size_t path_length, position;
int error;
GIT_ASSERT_ARG(index);
GIT_ASSERT_ARG(entry_ptr);
entry = *entry_ptr;
/* Make sure that the path length flag is correct */
path_length = ((struct entry_internal *)entry)->pathlen;
index_entry_adjust_namemask(entry, path_length);
/* This entry is now up-to-date and should not be checked for raciness */
entry->flags_extended |= GIT_INDEX_ENTRY_UPTODATE;
git_vector_sort(&index->entries);
/*
* Look if an entry with this path already exists, either staged, or (if
* this entry is a regular staged item) as the "ours" side of a conflict.
*/
index_existing_and_best(&existing, &position, &best, index, entry);
/* Update the file mode */
entry->mode = trust_mode ?
git_index__create_mode(entry->mode) :
index_merge_mode(index, best, entry->mode);
/* Canonicalize the directory name */
if (!trust_path && (error = canonicalize_directory_path(index, entry, best)) < 0)
goto out;
/* Ensure that the given id exists (unless it's a submodule) */
if (!trust_id && INDEX_OWNER(index) &&
(entry->mode & GIT_FILEMODE_COMMIT) != GIT_FILEMODE_COMMIT) {
if (!git_object__is_valid(INDEX_OWNER(index), &entry->id,
git_object__type_from_filemode(entry->mode))) {
error = -1;
goto out;
}
}
/* Look for tree / blob name collisions, removing conflicts if requested */
if ((error = check_file_directory_collision(index, entry, position, replace)) < 0)
goto out;
/*
* If we are replacing an existing item, overwrite the existing entry
* and return it in place of the passed in one.
*/
if (existing) {
if (replace) {
index_entry_cpy(existing, entry);
if (trust_path)
memcpy((char *)existing->path, entry->path, strlen(entry->path));
}
index_entry_free(entry);
*entry_ptr = existing;
} else {
/*
* If replace is not requested or no existing entry exists, insert
* at the sorted position. (Since we re-sort after each insert to
* check for dups, this is actually cheaper in the long run.)
*/
if ((error = git_vector_insert_sorted(&index->entries, entry, index_no_dups)) < 0 ||
(error = index_map_set(index->entries_map, entry, index->ignore_case)) < 0)
goto out;
}
index->dirty = 1;
out:
if (error < 0) {
index_entry_free(*entry_ptr);
*entry_ptr = NULL;
}
return error;
}
static int index_conflict_to_reuc(git_index *index, const char *path)
{
const git_index_entry *conflict_entries[3];
int ancestor_mode, our_mode, their_mode;
git_oid const *ancestor_oid, *our_oid, *their_oid;
int ret;
if ((ret = git_index_conflict_get(&conflict_entries[0],
&conflict_entries[1], &conflict_entries[2], index, path)) < 0)
return ret;
ancestor_mode = conflict_entries[0] == NULL ? 0 : conflict_entries[0]->mode;
our_mode = conflict_entries[1] == NULL ? 0 : conflict_entries[1]->mode;
their_mode = conflict_entries[2] == NULL ? 0 : conflict_entries[2]->mode;
ancestor_oid = conflict_entries[0] == NULL ? NULL : &conflict_entries[0]->id;
our_oid = conflict_entries[1] == NULL ? NULL : &conflict_entries[1]->id;
their_oid = conflict_entries[2] == NULL ? NULL : &conflict_entries[2]->id;
if ((ret = git_index_reuc_add(index, path, ancestor_mode, ancestor_oid,
our_mode, our_oid, their_mode, their_oid)) >= 0)
ret = git_index_conflict_remove(index, path);
return ret;
}
GIT_INLINE(bool) is_file_or_link(const int filemode)
{
return (filemode == GIT_FILEMODE_BLOB ||
filemode == GIT_FILEMODE_BLOB_EXECUTABLE ||
filemode == GIT_FILEMODE_LINK);
}
GIT_INLINE(bool) valid_filemode(const int filemode)
{
return (is_file_or_link(filemode) || filemode == GIT_FILEMODE_COMMIT);
}
int git_index_add_from_buffer(
git_index *index, const git_index_entry *source_entry,
const void *buffer, size_t len)
{
git_index_entry *entry = NULL;
int error = 0;
git_oid id;
GIT_ASSERT_ARG(index);
GIT_ASSERT_ARG(source_entry && source_entry->path);
if (INDEX_OWNER(index) == NULL)
return create_index_error(-1,
"could not initialize index entry. "
"Index is not backed up by an existing repository.");
if (!is_file_or_link(source_entry->mode)) {
git_error_set(GIT_ERROR_INDEX, "invalid filemode");
return -1;
}
if (len > UINT32_MAX) {
git_error_set(GIT_ERROR_INDEX, "buffer is too large");
return -1;
}
if (index_entry_dup(&entry, index, source_entry) < 0)
return -1;
error = git_blob_create_from_buffer(&id, INDEX_OWNER(index), buffer, len);
if (error < 0) {
index_entry_free(entry);
return error;
}
git_oid_cpy(&entry->id, &id);
entry->file_size = (uint32_t)len;
if ((error = index_insert(index, &entry, 1, true, true, true)) < 0)
return error;
/* Adding implies conflict was resolved, move conflict entries to REUC */
if ((error = index_conflict_to_reuc(index, entry->path)) < 0 && error != GIT_ENOTFOUND)
return error;
git_tree_cache_invalidate_path(index->tree, entry->path);
return 0;
}
static int add_repo_as_submodule(git_index_entry **out, git_index *index, const char *path)
{
git_repository *sub;
git_buf abspath = GIT_BUF_INIT;
git_repository *repo = INDEX_OWNER(index);
git_reference *head;
git_index_entry *entry;
struct stat st;
int error;
if ((error = git_repository_workdir_path(&abspath, repo, path)) < 0)
return error;
if ((error = p_stat(abspath.ptr, &st)) < 0) {
git_error_set(GIT_ERROR_OS, "failed to stat repository dir");
return -1;
}
if (index_entry_create(&entry, INDEX_OWNER(index), path, &st, true) < 0)
return -1;
git_index_entry__init_from_stat(entry, &st, !index->distrust_filemode);
if ((error = git_repository_open(&sub, abspath.ptr)) < 0)
return error;
if ((error = git_repository_head(&head, sub)) < 0)
return error;
git_oid_cpy(&entry->id, git_reference_target(head));
entry->mode = GIT_FILEMODE_COMMIT;
git_reference_free(head);
git_repository_free(sub);
git_buf_dispose(&abspath);
*out = entry;
return 0;
}
int git_index_add_bypath(git_index *index, const char *path)
{
git_index_entry *entry = NULL;
int ret;
GIT_ASSERT_ARG(index);
GIT_ASSERT_ARG(path);
if ((ret = index_entry_init(&entry, index, path)) == 0)
ret = index_insert(index, &entry, 1, false, false, true);
/* If we were given a directory, let's see if it's a submodule */
if (ret < 0 && ret != GIT_EDIRECTORY)
return ret;
if (ret == GIT_EDIRECTORY) {
git_submodule *sm;
git_error_state err;
git_error_state_capture(&err, ret);
ret = git_submodule_lookup(&sm, INDEX_OWNER(index), path);
if (ret == GIT_ENOTFOUND)
return git_error_state_restore(&err);
git_error_state_free(&err);
/*
* EEXISTS means that there is a repository at that path, but it's not known
* as a submodule. We add its HEAD as an entry and don't register it.
*/
if (ret == GIT_EEXISTS) {
if ((ret = add_repo_as_submodule(&entry, index, path)) < 0)
return ret;
if ((ret = index_insert(index, &entry, 1, false, false, true)) < 0)
return ret;
} else if (ret < 0) {
return ret;
} else {
ret = git_submodule_add_to_index(sm, false);
git_submodule_free(sm);
return ret;
}
}
/* Adding implies conflict was resolved, move conflict entries to REUC */
if ((ret = index_conflict_to_reuc(index, path)) < 0 && ret != GIT_ENOTFOUND)
return ret;
git_tree_cache_invalidate_path(index->tree, entry->path);
return 0;
}
int git_index_remove_bypath(git_index *index, const char *path)
{
int ret;
GIT_ASSERT_ARG(index);
GIT_ASSERT_ARG(path);
if (((ret = git_index_remove(index, path, 0)) < 0 &&
ret != GIT_ENOTFOUND) ||
((ret = index_conflict_to_reuc(index, path)) < 0 &&
ret != GIT_ENOTFOUND))
return ret;
if (ret == GIT_ENOTFOUND)
git_error_clear();
return 0;
}
int git_index__fill(git_index *index, const git_vector *source_entries)
{
const git_index_entry *source_entry = NULL;
int error = 0;
size_t i;
GIT_ASSERT_ARG(index);
if (!source_entries->length)
return 0;
if (git_vector_size_hint(&index->entries, source_entries->length) < 0 ||
index_map_resize(index->entries_map, (size_t)(source_entries->length * 1.3),
index->ignore_case) < 0)
return -1;
git_vector_foreach(source_entries, i, source_entry) {
git_index_entry *entry = NULL;
if ((error = index_entry_dup(&entry, index, source_entry)) < 0)
break;
index_entry_adjust_namemask(entry, ((struct entry_internal *)entry)->pathlen);
entry->flags_extended |= GIT_INDEX_ENTRY_UPTODATE;
entry->mode = git_index__create_mode(entry->mode);
if ((error = git_vector_insert(&index->entries, entry)) < 0)
break;
if ((error = index_map_set(index->entries_map, entry, index->ignore_case)) < 0)
break;
index->dirty = 1;
}
if (!error)
git_vector_sort(&index->entries);
return error;
}
int git_index_add(git_index *index, const git_index_entry *source_entry)
{
git_index_entry *entry = NULL;
int ret;
GIT_ASSERT_ARG(index);
GIT_ASSERT_ARG(source_entry && source_entry->path);
if (!valid_filemode(source_entry->mode)) {
git_error_set(GIT_ERROR_INDEX, "invalid entry mode");
return -1;
}
if ((ret = index_entry_dup(&entry, index, source_entry)) < 0 ||
(ret = index_insert(index, &entry, 1, true, true, false)) < 0)
return ret;
git_tree_cache_invalidate_path(index->tree, entry->path);
return 0;
}
int git_index_remove(git_index *index, const char *path, int stage)
{
int error;
size_t position;
git_index_entry remove_key = {{ 0 }};
remove_key.path = path;
GIT_INDEX_ENTRY_STAGE_SET(&remove_key, stage);
index_map_delete(index->entries_map, &remove_key, index->ignore_case);
if (index_find(&position, index, path, 0, stage) < 0) {
git_error_set(
GIT_ERROR_INDEX, "index does not contain %s at stage %d", path, stage);
error = GIT_ENOTFOUND;
} else {
error = index_remove_entry(index, position);
}
return error;
}
int git_index_remove_directory(git_index *index, const char *dir, int stage)
{
git_buf pfx = GIT_BUF_INIT;
int error = 0;
size_t pos;
git_index_entry *entry;
if (!(error = git_buf_sets(&pfx, dir)) &&
!(error = git_path_to_dir(&pfx)))
index_find(&pos, index, pfx.ptr, pfx.size, GIT_INDEX_STAGE_ANY);
while (!error) {
entry = git_vector_get(&index->entries, pos);
if (!entry || git__prefixcmp(entry->path, pfx.ptr) != 0)
break;
if (GIT_INDEX_ENTRY_STAGE(entry) != stage) {
++pos;
continue;
}
error = index_remove_entry(index, pos);
/* removed entry at 'pos' so we don't need to increment */
}
git_buf_dispose(&pfx);
return error;
}
int git_index_find_prefix(size_t *at_pos, git_index *index, const char *prefix)
{
int error = 0;
size_t pos;
const git_index_entry *entry;
index_find(&pos, index, prefix, strlen(prefix), GIT_INDEX_STAGE_ANY);
entry = git_vector_get(&index->entries, pos);
if (!entry || git__prefixcmp(entry->path, prefix) != 0)
error = GIT_ENOTFOUND;
if (!error && at_pos)
*at_pos = pos;
return error;
}
int git_index__find_pos(
size_t *out, git_index *index, const char *path, size_t path_len, int stage)
{
GIT_ASSERT_ARG(index);
GIT_ASSERT_ARG(path);
return index_find(out, index, path, path_len, stage);
}
int git_index_find(size_t *at_pos, git_index *index, const char *path)
{
size_t pos;
GIT_ASSERT_ARG(index);
GIT_ASSERT_ARG(path);
if (git_vector_bsearch2(
&pos, &index->entries, index->entries_search_path, path) < 0) {
git_error_set(GIT_ERROR_INDEX, "index does not contain %s", path);
return GIT_ENOTFOUND;
}
/* Since our binary search only looked at path, we may be in the
* middle of a list of stages.
*/
for (; pos > 0; --pos) {
const git_index_entry *prev = git_vector_get(&index->entries, pos - 1);
if (index->entries_cmp_path(prev->path, path) != 0)
break;
}
if (at_pos)
*at_pos = pos;
return 0;
}
int git_index_conflict_add(git_index *index,
const git_index_entry *ancestor_entry,
const git_index_entry *our_entry,
const git_index_entry *their_entry)
{
git_index_entry *entries[3] = { 0 };
unsigned short i;
int ret = 0;
GIT_ASSERT_ARG(index);
if ((ancestor_entry &&
(ret = index_entry_dup(&entries[0], index, ancestor_entry)) < 0) ||
(our_entry &&
(ret = index_entry_dup(&entries[1], index, our_entry)) < 0) ||
(their_entry &&
(ret = index_entry_dup(&entries[2], index, their_entry)) < 0))
goto on_error;
/* Validate entries */
for (i = 0; i < 3; i++) {
if (entries[i] && !valid_filemode(entries[i]->mode)) {
git_error_set(GIT_ERROR_INDEX, "invalid filemode for stage %d entry",
i + 1);
ret = -1;
goto on_error;
}
}
/* Remove existing index entries for each path */
for (i = 0; i < 3; i++) {
if (entries[i] == NULL)
continue;
if ((ret = git_index_remove(index, entries[i]->path, 0)) != 0) {
if (ret != GIT_ENOTFOUND)
goto on_error;
git_error_clear();
ret = 0;
}
}
/* Add the conflict entries */
for (i = 0; i < 3; i++) {
if (entries[i] == NULL)
continue;
/* Make sure stage is correct */
GIT_INDEX_ENTRY_STAGE_SET(entries[i], i + 1);
if ((ret = index_insert(index, &entries[i], 1, true, true, false)) < 0)
goto on_error;
entries[i] = NULL; /* don't free if later entry fails */
}
return 0;
on_error:
for (i = 0; i < 3; i++) {
if (entries[i] != NULL)
index_entry_free(entries[i]);
}
return ret;
}
static int index_conflict__get_byindex(
const git_index_entry **ancestor_out,
const git_index_entry **our_out,
const git_index_entry **their_out,
git_index *index,
size_t n)
{
const git_index_entry *conflict_entry;
const char *path = NULL;
size_t count;
int stage, len = 0;
GIT_ASSERT_ARG(ancestor_out);
GIT_ASSERT_ARG(our_out);
GIT_ASSERT_ARG(their_out);
GIT_ASSERT_ARG(index);
*ancestor_out = NULL;
*our_out = NULL;
*their_out = NULL;
for (count = git_index_entrycount(index); n < count; ++n) {
conflict_entry = git_vector_get(&index->entries, n);
if (path && index->entries_cmp_path(conflict_entry->path, path) != 0)
break;
stage = GIT_INDEX_ENTRY_STAGE(conflict_entry);
path = conflict_entry->path;
switch (stage) {
case 3:
*their_out = conflict_entry;
len++;
break;
case 2:
*our_out = conflict_entry;
len++;
break;
case 1:
*ancestor_out = conflict_entry;
len++;
break;
default:
break;
};
}
return len;
}
int git_index_conflict_get(
const git_index_entry **ancestor_out,
const git_index_entry **our_out,
const git_index_entry **their_out,
git_index *index,
const char *path)
{
size_t pos;
int len = 0;
GIT_ASSERT_ARG(ancestor_out);
GIT_ASSERT_ARG(our_out);
GIT_ASSERT_ARG(their_out);
GIT_ASSERT_ARG(index);
GIT_ASSERT_ARG(path);
*ancestor_out = NULL;
*our_out = NULL;
*their_out = NULL;
if (git_index_find(&pos, index, path) < 0)
return GIT_ENOTFOUND;
if ((len = index_conflict__get_byindex(
ancestor_out, our_out, their_out, index, pos)) < 0)
return len;
else if (len == 0)
return GIT_ENOTFOUND;
return 0;
}
static int index_conflict_remove(git_index *index, const char *path)
{
size_t pos = 0;
git_index_entry *conflict_entry;
int error = 0;
if (path != NULL && git_index_find(&pos, index, path) < 0)
return GIT_ENOTFOUND;
while ((conflict_entry = git_vector_get(&index->entries, pos)) != NULL) {
if (path != NULL &&
index->entries_cmp_path(conflict_entry->path, path) != 0)
break;
if (GIT_INDEX_ENTRY_STAGE(conflict_entry) == 0) {
pos++;
continue;
}
if ((error = index_remove_entry(index, pos)) < 0)
break;
}
return error;
}
int git_index_conflict_remove(git_index *index, const char *path)
{
GIT_ASSERT_ARG(index);
GIT_ASSERT_ARG(path);
return index_conflict_remove(index, path);
}
int git_index_conflict_cleanup(git_index *index)
{
GIT_ASSERT_ARG(index);
return index_conflict_remove(index, NULL);
}
int git_index_has_conflicts(const git_index *index)
{
size_t i;
git_index_entry *entry;
GIT_ASSERT_ARG(index);
git_vector_foreach(&index->entries, i, entry) {
if (GIT_INDEX_ENTRY_STAGE(entry) > 0)
return 1;
}
return 0;
}
int git_index_iterator_new(
git_index_iterator **iterator_out,
git_index *index)
{
git_index_iterator *it;
int error;
GIT_ASSERT_ARG(iterator_out);
GIT_ASSERT_ARG(index);
it = git__calloc(1, sizeof(git_index_iterator));
GIT_ERROR_CHECK_ALLOC(it);
if ((error = git_index_snapshot_new(&it->snap, index)) < 0) {
git__free(it);
return error;
}
it->index = index;
*iterator_out = it;
return 0;
}
int git_index_iterator_next(
const git_index_entry **out,
git_index_iterator *it)
{
GIT_ASSERT_ARG(out);
GIT_ASSERT_ARG(it);
if (it->cur >= git_vector_length(&it->snap))
return GIT_ITEROVER;
*out = (git_index_entry *)git_vector_get(&it->snap, it->cur++);
return 0;
}
void git_index_iterator_free(git_index_iterator *it)
{
if (it == NULL)
return;
git_index_snapshot_release(&it->snap, it->index);
git__free(it);
}
int git_index_conflict_iterator_new(
git_index_conflict_iterator **iterator_out,
git_index *index)
{
git_index_conflict_iterator *it = NULL;
GIT_ASSERT_ARG(iterator_out);
GIT_ASSERT_ARG(index);
it = git__calloc(1, sizeof(git_index_conflict_iterator));
GIT_ERROR_CHECK_ALLOC(it);
it->index = index;
*iterator_out = it;
return 0;
}
int git_index_conflict_next(
const git_index_entry **ancestor_out,
const git_index_entry **our_out,
const git_index_entry **their_out,
git_index_conflict_iterator *iterator)
{
const git_index_entry *entry;
int len;
GIT_ASSERT_ARG(ancestor_out);
GIT_ASSERT_ARG(our_out);
GIT_ASSERT_ARG(their_out);
GIT_ASSERT_ARG(iterator);
*ancestor_out = NULL;
*our_out = NULL;
*their_out = NULL;
while (iterator->cur < iterator->index->entries.length) {
entry = git_index_get_byindex(iterator->index, iterator->cur);
if (git_index_entry_is_conflict(entry)) {
if ((len = index_conflict__get_byindex(
ancestor_out,
our_out,
their_out,
iterator->index,
iterator->cur)) < 0)
return len;
iterator->cur += len;
return 0;
}
iterator->cur++;
}
return GIT_ITEROVER;
}
void git_index_conflict_iterator_free(git_index_conflict_iterator *iterator)
{
if (iterator == NULL)
return;
git__free(iterator);
}
size_t git_index_name_entrycount(git_index *index)
{
GIT_ASSERT_ARG(index);
return index->names.length;
}
const git_index_name_entry *git_index_name_get_byindex(
git_index *index, size_t n)
{
GIT_ASSERT_ARG_WITH_RETVAL(index, NULL);
git_vector_sort(&index->names);
return git_vector_get(&index->names, n);
}
static void index_name_entry_free(git_index_name_entry *ne)
{
if (!ne)
return;
git__free(ne->ancestor);
git__free(ne->ours);
git__free(ne->theirs);
git__free(ne);
}
int git_index_name_add(git_index *index,
const char *ancestor, const char *ours, const char *theirs)
{
git_index_name_entry *conflict_name;
GIT_ASSERT_ARG((ancestor && ours) || (ancestor && theirs) || (ours && theirs));
conflict_name = git__calloc(1, sizeof(git_index_name_entry));
GIT_ERROR_CHECK_ALLOC(conflict_name);
if ((ancestor && !(conflict_name->ancestor = git__strdup(ancestor))) ||
(ours && !(conflict_name->ours = git__strdup(ours))) ||
(theirs && !(conflict_name->theirs = git__strdup(theirs))) ||
git_vector_insert(&index->names, conflict_name) < 0)
{
index_name_entry_free(conflict_name);
return -1;
}
index->dirty = 1;
return 0;
}
int git_index_name_clear(git_index *index)
{
size_t i;
git_index_name_entry *conflict_name;
GIT_ASSERT_ARG(index);
git_vector_foreach(&index->names, i, conflict_name)
index_name_entry_free(conflict_name);
git_vector_clear(&index->names);
index->dirty = 1;
return 0;
}
size_t git_index_reuc_entrycount(git_index *index)
{
GIT_ASSERT_ARG(index);
return index->reuc.length;
}
static int index_reuc_on_dup(void **old, void *new)
{
index_entry_reuc_free(*old);
*old = new;
return GIT_EEXISTS;
}
static int index_reuc_insert(
git_index *index,
git_index_reuc_entry *reuc)
{
int res;
GIT_ASSERT_ARG(index);
GIT_ASSERT_ARG(reuc && reuc->path != NULL);
GIT_ASSERT(git_vector_is_sorted(&index->reuc));
res = git_vector_insert_sorted(&index->reuc, reuc, &index_reuc_on_dup);
index->dirty = 1;
return res == GIT_EEXISTS ? 0 : res;
}
int git_index_reuc_add(git_index *index, const char *path,
int ancestor_mode, const git_oid *ancestor_oid,
int our_mode, const git_oid *our_oid,
int their_mode, const git_oid *their_oid)
{
git_index_reuc_entry *reuc = NULL;
int error = 0;
GIT_ASSERT_ARG(index);
GIT_ASSERT_ARG(path);
if ((error = index_entry_reuc_init(&reuc, path, ancestor_mode,
ancestor_oid, our_mode, our_oid, their_mode, their_oid)) < 0 ||
(error = index_reuc_insert(index, reuc)) < 0)
index_entry_reuc_free(reuc);
return error;
}
int git_index_reuc_find(size_t *at_pos, git_index *index, const char *path)
{
return git_vector_bsearch2(at_pos, &index->reuc, index->reuc_search, path);
}
const git_index_reuc_entry *git_index_reuc_get_bypath(
git_index *index, const char *path)
{
size_t pos;
GIT_ASSERT_ARG_WITH_RETVAL(index, NULL);
GIT_ASSERT_ARG_WITH_RETVAL(path, NULL);
if (!index->reuc.length)
return NULL;
GIT_ASSERT_WITH_RETVAL(git_vector_is_sorted(&index->reuc), NULL);
if (git_index_reuc_find(&pos, index, path) < 0)
return NULL;
return git_vector_get(&index->reuc, pos);
}
const git_index_reuc_entry *git_index_reuc_get_byindex(
git_index *index, size_t n)
{
GIT_ASSERT_ARG_WITH_RETVAL(index, NULL);
GIT_ASSERT_WITH_RETVAL(git_vector_is_sorted(&index->reuc), NULL);
return git_vector_get(&index->reuc, n);
}
int git_index_reuc_remove(git_index *index, size_t position)
{
int error;
git_index_reuc_entry *reuc;
GIT_ASSERT_ARG(index);
GIT_ASSERT(git_vector_is_sorted(&index->reuc));
reuc = git_vector_get(&index->reuc, position);
error = git_vector_remove(&index->reuc, position);
if (!error)
index_entry_reuc_free(reuc);
index->dirty = 1;
return error;
}
int git_index_reuc_clear(git_index *index)
{
size_t i;
GIT_ASSERT_ARG(index);
for (i = 0; i < index->reuc.length; ++i)
index_entry_reuc_free(git_atomic_swap(index->reuc.contents[i], NULL));
git_vector_clear(&index->reuc);
index->dirty = 1;
return 0;
}
static int index_error_invalid(const char *message)
{
git_error_set(GIT_ERROR_INDEX, "invalid data in index - %s", message);
return -1;
}
static int read_reuc(git_index *index, const char *buffer, size_t size)
{
const char *endptr;
size_t len;
int i;
/* If called multiple times, the vector might already be initialized */
if (index->reuc._alloc_size == 0 &&
git_vector_init(&index->reuc, 16, reuc_cmp) < 0)
return -1;
while (size) {
git_index_reuc_entry *lost;
len = p_strnlen(buffer, size) + 1;
if (size <= len)
return index_error_invalid("reading reuc entries");
lost = reuc_entry_alloc(buffer);
GIT_ERROR_CHECK_ALLOC(lost);
size -= len;
buffer += len;
/* read 3 ASCII octal numbers for stage entries */
for (i = 0; i < 3; i++) {
int64_t tmp;
if (git__strntol64(&tmp, buffer, size, &endptr, 8) < 0 ||
!endptr || endptr == buffer || *endptr ||
tmp < 0 || tmp > UINT32_MAX) {
index_entry_reuc_free(lost);
return index_error_invalid("reading reuc entry stage");
}
lost->mode[i] = (uint32_t)tmp;
len = (endptr + 1) - buffer;
if (size <= len) {
index_entry_reuc_free(lost);
return index_error_invalid("reading reuc entry stage");
}
size -= len;
buffer += len;
}
/* read up to 3 OIDs for stage entries */
for (i = 0; i < 3; i++) {
if (!lost->mode[i])
continue;
if (size < 20) {
index_entry_reuc_free(lost);
return index_error_invalid("reading reuc entry oid");
}
git_oid_fromraw(&lost->oid[i], (const unsigned char *) buffer);
size -= 20;
buffer += 20;
}
/* entry was read successfully - insert into reuc vector */
if (git_vector_insert(&index->reuc, lost) < 0)
return -1;
}
/* entries are guaranteed to be sorted on-disk */
git_vector_set_sorted(&index->reuc, true);
return 0;
}
static int read_conflict_names(git_index *index, const char *buffer, size_t size)
{
size_t len;
/* This gets called multiple times, the vector might already be initialized */
if (index->names._alloc_size == 0 &&
git_vector_init(&index->names, 16, conflict_name_cmp) < 0)
return -1;
#define read_conflict_name(ptr) \
len = p_strnlen(buffer, size) + 1; \
if (size < len) { \
index_error_invalid("reading conflict name entries"); \
goto out_err; \
} \
if (len == 1) \
ptr = NULL; \
else { \
ptr = git__malloc(len); \
GIT_ERROR_CHECK_ALLOC(ptr); \
memcpy(ptr, buffer, len); \
} \
\
buffer += len; \
size -= len;
while (size) {
git_index_name_entry *conflict_name = git__calloc(1, sizeof(git_index_name_entry));
GIT_ERROR_CHECK_ALLOC(conflict_name);
read_conflict_name(conflict_name->ancestor);
read_conflict_name(conflict_name->ours);
read_conflict_name(conflict_name->theirs);
if (git_vector_insert(&index->names, conflict_name) < 0)
goto out_err;
continue;
out_err:
git__free(conflict_name->ancestor);
git__free(conflict_name->ours);
git__free(conflict_name->theirs);
git__free(conflict_name);
return -1;
}
#undef read_conflict_name
/* entries are guaranteed to be sorted on-disk */
git_vector_set_sorted(&index->names, true);
return 0;
}
static size_t index_entry_size(size_t path_len, size_t varint_len, uint32_t flags)
{
if (varint_len) {
if (flags & GIT_INDEX_ENTRY_EXTENDED)
return offsetof(struct entry_long, path) + path_len + 1 + varint_len;
else
return offsetof(struct entry_short, path) + path_len + 1 + varint_len;
} else {
#define entry_size(type,len) ((offsetof(type, path) + (len) + 8) & ~7)
if (flags & GIT_INDEX_ENTRY_EXTENDED)
return entry_size(struct entry_long, path_len);
else
return entry_size(struct entry_short, path_len);
#undef entry_size
}
}
static int read_entry(
git_index_entry **out,
size_t *out_size,
git_index *index,
const void *buffer,
size_t buffer_size,
const char *last)
{
size_t path_length, entry_size;
const char *path_ptr;
struct entry_short source;
git_index_entry entry = {{0}};
bool compressed = index->version >= INDEX_VERSION_NUMBER_COMP;
char *tmp_path = NULL;
if (INDEX_FOOTER_SIZE + minimal_entry_size > buffer_size)
return -1;
/* buffer is not guaranteed to be aligned */
memcpy(&source, buffer, sizeof(struct entry_short));
entry.ctime.seconds = (git_time_t)ntohl(source.ctime.seconds);
entry.ctime.nanoseconds = ntohl(source.ctime.nanoseconds);
entry.mtime.seconds = (git_time_t)ntohl(source.mtime.seconds);
entry.mtime.nanoseconds = ntohl(source.mtime.nanoseconds);
entry.dev = ntohl(source.dev);
entry.ino = ntohl(source.ino);
entry.mode = ntohl(source.mode);
entry.uid = ntohl(source.uid);
entry.gid = ntohl(source.gid);
entry.file_size = ntohl(source.file_size);
git_oid_cpy(&entry.id, &source.oid);
entry.flags = ntohs(source.flags);
if (entry.flags & GIT_INDEX_ENTRY_EXTENDED) {
uint16_t flags_raw;
size_t flags_offset;
flags_offset = offsetof(struct entry_long, flags_extended);
memcpy(&flags_raw, (const char *) buffer + flags_offset,
sizeof(flags_raw));
flags_raw = ntohs(flags_raw);
memcpy(&entry.flags_extended, &flags_raw, sizeof(flags_raw));
path_ptr = (const char *) buffer + offsetof(struct entry_long, path);
} else
path_ptr = (const char *) buffer + offsetof(struct entry_short, path);
if (!compressed) {
path_length = entry.flags & GIT_INDEX_ENTRY_NAMEMASK;
/* if this is a very long string, we must find its
* real length without overflowing */
if (path_length == 0xFFF) {
const char *path_end;
path_end = memchr(path_ptr, '\0', buffer_size);
if (path_end == NULL)
return -1;
path_length = path_end - path_ptr;
}
entry_size = index_entry_size(path_length, 0, entry.flags);
entry.path = (char *)path_ptr;
} else {
size_t varint_len, last_len, prefix_len, suffix_len, path_len;
uintmax_t strip_len;
strip_len = git_decode_varint((const unsigned char *)path_ptr, &varint_len);
last_len = strlen(last);
if (varint_len == 0 || last_len < strip_len)
return index_error_invalid("incorrect prefix length");
prefix_len = last_len - (size_t)strip_len;
suffix_len = strlen(path_ptr + varint_len);
GIT_ERROR_CHECK_ALLOC_ADD(&path_len, prefix_len, suffix_len);
GIT_ERROR_CHECK_ALLOC_ADD(&path_len, path_len, 1);
if (path_len > GIT_PATH_MAX)
return index_error_invalid("unreasonable path length");
tmp_path = git__malloc(path_len);
GIT_ERROR_CHECK_ALLOC(tmp_path);
memcpy(tmp_path, last, prefix_len);
memcpy(tmp_path + prefix_len, path_ptr + varint_len, suffix_len + 1);
entry_size = index_entry_size(suffix_len, varint_len, entry.flags);
entry.path = tmp_path;
}
if (entry_size == 0)
return -1;
if (INDEX_FOOTER_SIZE + entry_size > buffer_size)
return -1;
if (index_entry_dup(out, index, &entry) < 0) {
git__free(tmp_path);
return -1;
}
git__free(tmp_path);
*out_size = entry_size;
return 0;
}
static int read_header(struct index_header *dest, const void *buffer)
{
const struct index_header *source = buffer;
dest->signature = ntohl(source->signature);
if (dest->signature != INDEX_HEADER_SIG)
return index_error_invalid("incorrect header signature");
dest->version = ntohl(source->version);
if (dest->version < INDEX_VERSION_NUMBER_LB ||
dest->version > INDEX_VERSION_NUMBER_UB)
return index_error_invalid("incorrect header version");
dest->entry_count = ntohl(source->entry_count);
return 0;
}
static int read_extension(size_t *read_len, git_index *index, const char *buffer, size_t buffer_size)
{
struct index_extension dest;
size_t total_size;
/* buffer is not guaranteed to be aligned */
memcpy(&dest, buffer, sizeof(struct index_extension));
dest.extension_size = ntohl(dest.extension_size);
total_size = dest.extension_size + sizeof(struct index_extension);
if (dest.extension_size > total_size ||
buffer_size < total_size ||
buffer_size - total_size < INDEX_FOOTER_SIZE) {
index_error_invalid("extension is truncated");
return -1;
}
/* optional extension */
if (dest.signature[0] >= 'A' && dest.signature[0] <= 'Z') {
/* tree cache */
if (memcmp(dest.signature, INDEX_EXT_TREECACHE_SIG, 4) == 0) {
if (git_tree_cache_read(&index->tree, buffer + 8, dest.extension_size, &index->tree_pool) < 0)
return -1;
} else if (memcmp(dest.signature, INDEX_EXT_UNMERGED_SIG, 4) == 0) {
if (read_reuc(index, buffer + 8, dest.extension_size) < 0)
return -1;
} else if (memcmp(dest.signature, INDEX_EXT_CONFLICT_NAME_SIG, 4) == 0) {
if (read_conflict_names(index, buffer + 8, dest.extension_size) < 0)
return -1;
}
/* else, unsupported extension. We cannot parse this, but we can skip
* it by returning `total_size */
} else {
/* we cannot handle non-ignorable extensions;
* in fact they aren't even defined in the standard */
git_error_set(GIT_ERROR_INDEX, "unsupported mandatory extension: '%.4s'", dest.signature);
return -1;
}
*read_len = total_size;
return 0;
}
static int parse_index(git_index *index, const char *buffer, size_t buffer_size)
{
int error = 0;
unsigned int i;
struct index_header header = { 0 };
git_oid checksum_calculated, checksum_expected;
const char *last = NULL;
const char *empty = "";
#define seek_forward(_increase) { \
if (_increase >= buffer_size) { \
error = index_error_invalid("ran out of data while parsing"); \
goto done; } \
buffer += _increase; \
buffer_size -= _increase;\
}
if (buffer_size < INDEX_HEADER_SIZE + INDEX_FOOTER_SIZE)
return index_error_invalid("insufficient buffer space");
/* Precalculate the SHA1 of the files's contents -- we'll match it to
* the provided SHA1 in the footer */
git_hash_buf(&checksum_calculated, buffer, buffer_size - INDEX_FOOTER_SIZE);
/* Parse header */
if ((error = read_header(&header, buffer)) < 0)
return error;
index->version = header.version;
if (index->version >= INDEX_VERSION_NUMBER_COMP)
last = empty;
seek_forward(INDEX_HEADER_SIZE);
GIT_ASSERT(!index->entries.length);
if ((error = index_map_resize(index->entries_map, header.entry_count, index->ignore_case)) < 0)
return error;
/* Parse all the entries */
for (i = 0; i < header.entry_count && buffer_size > INDEX_FOOTER_SIZE; ++i) {
git_index_entry *entry = NULL;
size_t entry_size;
if ((error = read_entry(&entry, &entry_size, index, buffer, buffer_size, last)) < 0) {
error = index_error_invalid("invalid entry");
goto done;
}
if ((error = git_vector_insert(&index->entries, entry)) < 0) {
index_entry_free(entry);
goto done;
}
if ((error = index_map_set(index->entries_map, entry, index->ignore_case)) < 0) {
index_entry_free(entry);
goto done;
}
error = 0;
if (index->version >= INDEX_VERSION_NUMBER_COMP)
last = entry->path;
seek_forward(entry_size);
}
if (i != header.entry_count) {
error = index_error_invalid("header entries changed while parsing");
goto done;
}
/* There's still space for some extensions! */
while (buffer_size > INDEX_FOOTER_SIZE) {
size_t extension_size;
if ((error = read_extension(&extension_size, index, buffer, buffer_size)) < 0) {
goto done;
}
seek_forward(extension_size);
}
if (buffer_size != INDEX_FOOTER_SIZE) {
error = index_error_invalid(
"buffer size does not match index footer size");
goto done;
}
/* 160-bit SHA-1 over the content of the index file before this checksum. */
git_oid_fromraw(&checksum_expected, (const unsigned char *)buffer);
if (git_oid__cmp(&checksum_calculated, &checksum_expected) != 0) {
error = index_error_invalid(
"calculated checksum does not match expected");
goto done;
}
git_oid_cpy(&index->checksum, &checksum_calculated);
#undef seek_forward
/* Entries are stored case-sensitively on disk, so re-sort now if
* in-memory index is supposed to be case-insensitive
*/
git_vector_set_sorted(&index->entries, !index->ignore_case);
git_vector_sort(&index->entries);
index->dirty = 0;
done:
return error;
}
static bool is_index_extended(git_index *index)
{
size_t i, extended;
git_index_entry *entry;
extended = 0;
git_vector_foreach(&index->entries, i, entry) {
entry->flags &= ~GIT_INDEX_ENTRY_EXTENDED;
if (entry->flags_extended & GIT_INDEX_ENTRY_EXTENDED_FLAGS) {
extended++;
entry->flags |= GIT_INDEX_ENTRY_EXTENDED;
}
}
return (extended > 0);
}
static int write_disk_entry(git_filebuf *file, git_index_entry *entry, const char *last)
{
void *mem = NULL;
struct entry_short ondisk;
size_t path_len, disk_size;
int varint_len = 0;
char *path;
const char *path_start = entry->path;
size_t same_len = 0;
path_len = ((struct entry_internal *)entry)->pathlen;
if (last) {
const char *last_c = last;
while (*path_start == *last_c) {
if (!*path_start || !*last_c)
break;
++path_start;
++last_c;
++same_len;
}
path_len -= same_len;
varint_len = git_encode_varint(NULL, 0, strlen(last) - same_len);
}
disk_size = index_entry_size(path_len, varint_len, entry->flags);
if (git_filebuf_reserve(file, &mem, disk_size) < 0)
return -1;
memset(mem, 0x0, disk_size);
/**
* Yes, we have to truncate.
*
* The on-disk format for Index entries clearly defines
* the time and size fields to be 4 bytes each -- so even if
* we store these values with 8 bytes on-memory, they must
* be truncated to 4 bytes before writing to disk.
*
* In 2038 I will be either too dead or too rich to care about this
*/
ondisk.ctime.seconds = htonl((uint32_t)entry->ctime.seconds);
ondisk.mtime.seconds = htonl((uint32_t)entry->mtime.seconds);
ondisk.ctime.nanoseconds = htonl(entry->ctime.nanoseconds);
ondisk.mtime.nanoseconds = htonl(entry->mtime.nanoseconds);
ondisk.dev = htonl(entry->dev);
ondisk.ino = htonl(entry->ino);
ondisk.mode = htonl(entry->mode);
ondisk.uid = htonl(entry->uid);
ondisk.gid = htonl(entry->gid);
ondisk.file_size = htonl((uint32_t)entry->file_size);
git_oid_cpy(&ondisk.oid, &entry->id);
ondisk.flags = htons(entry->flags);
if (entry->flags & GIT_INDEX_ENTRY_EXTENDED) {
const size_t path_offset = offsetof(struct entry_long, path);
struct entry_long ondisk_ext;
memcpy(&ondisk_ext, &ondisk, sizeof(struct entry_short));
ondisk_ext.flags_extended = htons(entry->flags_extended &
GIT_INDEX_ENTRY_EXTENDED_FLAGS);
memcpy(mem, &ondisk_ext, path_offset);
path = (char *)mem + path_offset;
disk_size -= path_offset;
} else {
const size_t path_offset = offsetof(struct entry_short, path);
memcpy(mem, &ondisk, path_offset);
path = (char *)mem + path_offset;
disk_size -= path_offset;
}
if (last) {
varint_len = git_encode_varint((unsigned char *) path,
disk_size, strlen(last) - same_len);
GIT_ASSERT(varint_len > 0);
path += varint_len;
disk_size -= varint_len;
/*
* If using path compression, we are not allowed
* to have additional trailing NULs.
*/
GIT_ASSERT(disk_size == path_len + 1);
} else {
/*
* If no path compression is used, we do have
* NULs as padding. As such, simply assert that
* we have enough space left to write the path.
*/
GIT_ASSERT(disk_size > path_len);
}
memcpy(path, path_start, path_len + 1);
return 0;
}
static int write_entries(git_index *index, git_filebuf *file)
{
int error = 0;
size_t i;
git_vector case_sorted = GIT_VECTOR_INIT, *entries = NULL;
git_index_entry *entry;
const char *last = NULL;
/* If index->entries is sorted case-insensitively, then we need
* to re-sort it case-sensitively before writing */
if (index->ignore_case) {
if ((error = git_vector_dup(&case_sorted, &index->entries, git_index_entry_cmp)) < 0)
goto done;
git_vector_sort(&case_sorted);
entries = &case_sorted;
} else {
entries = &index->entries;
}
if (index->version >= INDEX_VERSION_NUMBER_COMP)
last = "";
git_vector_foreach(entries, i, entry) {
if ((error = write_disk_entry(file, entry, last)) < 0)
break;
if (index->version >= INDEX_VERSION_NUMBER_COMP)
last = entry->path;
}
done:
git_vector_free(&case_sorted);
return error;
}
static int write_extension(git_filebuf *file, struct index_extension *header, git_buf *data)
{
struct index_extension ondisk;
memset(&ondisk, 0x0, sizeof(struct index_extension));
memcpy(&ondisk, header, 4);
ondisk.extension_size = htonl(header->extension_size);
git_filebuf_write(file, &ondisk, sizeof(struct index_extension));
return git_filebuf_write(file, data->ptr, data->size);
}
static int create_name_extension_data(git_buf *name_buf, git_index_name_entry *conflict_name)
{
int error = 0;
if (conflict_name->ancestor == NULL)
error = git_buf_put(name_buf, "\0", 1);
else
error = git_buf_put(name_buf, conflict_name->ancestor, strlen(conflict_name->ancestor) + 1);
if (error != 0)
goto on_error;
if (conflict_name->ours == NULL)
error = git_buf_put(name_buf, "\0", 1);
else
error = git_buf_put(name_buf, conflict_name->ours, strlen(conflict_name->ours) + 1);
if (error != 0)
goto on_error;
if (conflict_name->theirs == NULL)
error = git_buf_put(name_buf, "\0", 1);
else
error = git_buf_put(name_buf, conflict_name->theirs, strlen(conflict_name->theirs) + 1);
on_error:
return error;
}
static int write_name_extension(git_index *index, git_filebuf *file)
{
git_buf name_buf = GIT_BUF_INIT;
git_vector *out = &index->names;
git_index_name_entry *conflict_name;
struct index_extension extension;
size_t i;
int error = 0;
git_vector_foreach(out, i, conflict_name) {
if ((error = create_name_extension_data(&name_buf, conflict_name)) < 0)
goto done;
}
memset(&extension, 0x0, sizeof(struct index_extension));
memcpy(&extension.signature, INDEX_EXT_CONFLICT_NAME_SIG, 4);
extension.extension_size = (uint32_t)name_buf.size;
error = write_extension(file, &extension, &name_buf);
git_buf_dispose(&name_buf);
done:
return error;
}
static int create_reuc_extension_data(git_buf *reuc_buf, git_index_reuc_entry *reuc)
{
int i;
int error = 0;
if ((error = git_buf_put(reuc_buf, reuc->path, strlen(reuc->path) + 1)) < 0)
return error;
for (i = 0; i < 3; i++) {
if ((error = git_buf_printf(reuc_buf, "%o", reuc->mode[i])) < 0 ||
(error = git_buf_put(reuc_buf, "\0", 1)) < 0)
return error;
}
for (i = 0; i < 3; i++) {
if (reuc->mode[i] && (error = git_buf_put(reuc_buf, (char *)&reuc->oid[i].id, GIT_OID_RAWSZ)) < 0)
return error;
}
return 0;
}
static int write_reuc_extension(git_index *index, git_filebuf *file)
{
git_buf reuc_buf = GIT_BUF_INIT;
git_vector *out = &index->reuc;
git_index_reuc_entry *reuc;
struct index_extension extension;
size_t i;
int error = 0;
git_vector_foreach(out, i, reuc) {
if ((error = create_reuc_extension_data(&reuc_buf, reuc)) < 0)
goto done;
}
memset(&extension, 0x0, sizeof(struct index_extension));
memcpy(&extension.signature, INDEX_EXT_UNMERGED_SIG, 4);
extension.extension_size = (uint32_t)reuc_buf.size;
error = write_extension(file, &extension, &reuc_buf);
git_buf_dispose(&reuc_buf);
done:
return error;
}
static int write_tree_extension(git_index *index, git_filebuf *file)
{
struct index_extension extension;
git_buf buf = GIT_BUF_INIT;
int error;
if (index->tree == NULL)
return 0;
if ((error = git_tree_cache_write(&buf, index->tree)) < 0)
return error;
memset(&extension, 0x0, sizeof(struct index_extension));
memcpy(&extension.signature, INDEX_EXT_TREECACHE_SIG, 4);
extension.extension_size = (uint32_t)buf.size;
error = write_extension(file, &extension, &buf);
git_buf_dispose(&buf);
return error;
}
static void clear_uptodate(git_index *index)
{
git_index_entry *entry;
size_t i;
git_vector_foreach(&index->entries, i, entry)
entry->flags_extended &= ~GIT_INDEX_ENTRY_UPTODATE;
}
static int write_index(git_oid *checksum, git_index *index, git_filebuf *file)
{
git_oid hash_final;
struct index_header header;
bool is_extended;
uint32_t index_version_number;
GIT_ASSERT_ARG(index);
GIT_ASSERT_ARG(file);
if (index->version <= INDEX_VERSION_NUMBER_EXT) {
is_extended = is_index_extended(index);
index_version_number = is_extended ? INDEX_VERSION_NUMBER_EXT : INDEX_VERSION_NUMBER_LB;
} else {
index_version_number = index->version;
}
header.signature = htonl(INDEX_HEADER_SIG);
header.version = htonl(index_version_number);
header.entry_count = htonl((uint32_t)index->entries.length);
if (git_filebuf_write(file, &header, sizeof(struct index_header)) < 0)
return -1;
if (write_entries(index, file) < 0)
return -1;
/* write the tree cache extension */
if (index->tree != NULL && write_tree_extension(index, file) < 0)
return -1;
/* write the rename conflict extension */
if (index->names.length > 0 && write_name_extension(index, file) < 0)
return -1;
/* write the reuc extension */
if (index->reuc.length > 0 && write_reuc_extension(index, file) < 0)
return -1;
/* get out the hash for all the contents we've appended to the file */
git_filebuf_hash(&hash_final, file);
git_oid_cpy(checksum, &hash_final);
/* write it at the end of the file */
if (git_filebuf_write(file, hash_final.id, GIT_OID_RAWSZ) < 0)
return -1;
/* file entries are no longer up to date */
clear_uptodate(index);
return 0;
}
int git_index_entry_stage(const git_index_entry *entry)
{
return GIT_INDEX_ENTRY_STAGE(entry);
}
int git_index_entry_is_conflict(const git_index_entry *entry)
{
return (GIT_INDEX_ENTRY_STAGE(entry) > 0);
}
typedef struct read_tree_data {
git_index *index;
git_vector *old_entries;
git_vector *new_entries;
git_vector_cmp entry_cmp;
git_tree_cache *tree;
} read_tree_data;
static int read_tree_cb(
const char *root, const git_tree_entry *tentry, void *payload)
{
read_tree_data *data = payload;
git_index_entry *entry = NULL, *old_entry;
git_buf path = GIT_BUF_INIT;
size_t pos;
if (git_tree_entry__is_tree(tentry))
return 0;
if (git_buf_joinpath(&path, root, tentry->filename) < 0)
return -1;
if (index_entry_create(&entry, INDEX_OWNER(data->index), path.ptr, NULL, false) < 0)
return -1;
entry->mode = tentry->attr;
git_oid_cpy(&entry->id, git_tree_entry_id(tentry));
/* look for corresponding old entry and copy data to new entry */
if (data->old_entries != NULL &&
!index_find_in_entries(
&pos, data->old_entries, data->entry_cmp, path.ptr, 0, 0) &&
(old_entry = git_vector_get(data->old_entries, pos)) != NULL &&
entry->mode == old_entry->mode &&
git_oid_equal(&entry->id, &old_entry->id))
{
index_entry_cpy(entry, old_entry);
entry->flags_extended = 0;
}
index_entry_adjust_namemask(entry, path.size);
git_buf_dispose(&path);
if (git_vector_insert(data->new_entries, entry) < 0) {
index_entry_free(entry);
return -1;
}
return 0;
}
int git_index_read_tree(git_index *index, const git_tree *tree)
{
int error = 0;
git_vector entries = GIT_VECTOR_INIT;
git_idxmap *entries_map;
read_tree_data data;
size_t i;
git_index_entry *e;
if (git_idxmap_new(&entries_map) < 0)
return -1;
git_vector_set_cmp(&entries, index->entries._cmp); /* match sort */
data.index = index;
data.old_entries = &index->entries;
data.new_entries = &entries;
data.entry_cmp = index->entries_search;
index->tree = NULL;
git_pool_clear(&index->tree_pool);
git_vector_sort(&index->entries);
if ((error = git_tree_walk(tree, GIT_TREEWALK_POST, read_tree_cb, &data)) < 0)
goto cleanup;
if ((error = index_map_resize(entries_map, entries.length, index->ignore_case)) < 0)
goto cleanup;
git_vector_foreach(&entries, i, e) {
if ((error = index_map_set(entries_map, e, index->ignore_case)) < 0) {
git_error_set(GIT_ERROR_INDEX, "failed to insert entry into map");
return error;
}
}
error = 0;
git_vector_sort(&entries);
if ((error = git_index_clear(index)) < 0) {
/* well, this isn't good */;
} else {
git_vector_swap(&entries, &index->entries);
entries_map = git_atomic_swap(index->entries_map, entries_map);
}
index->dirty = 1;
cleanup:
git_vector_free(&entries);
git_idxmap_free(entries_map);
if (error < 0)
return error;
error = git_tree_cache_read_tree(&index->tree, tree, &index->tree_pool);
return error;
}
static int git_index_read_iterator(
git_index *index,
git_iterator *new_iterator,
size_t new_length_hint)
{
git_vector new_entries = GIT_VECTOR_INIT,
remove_entries = GIT_VECTOR_INIT;
git_idxmap *new_entries_map = NULL;
git_iterator *index_iterator = NULL;
git_iterator_options opts = GIT_ITERATOR_OPTIONS_INIT;
const git_index_entry *old_entry, *new_entry;
git_index_entry *entry;
size_t i;
int error;
GIT_ASSERT((new_iterator->flags & GIT_ITERATOR_DONT_IGNORE_CASE));
if ((error = git_vector_init(&new_entries, new_length_hint, index->entries._cmp)) < 0 ||
(error = git_vector_init(&remove_entries, index->entries.length, NULL)) < 0 ||
(error = git_idxmap_new(&new_entries_map)) < 0)
goto done;
if (new_length_hint && (error = index_map_resize(new_entries_map, new_length_hint,
index->ignore_case)) < 0)
goto done;
opts.flags = GIT_ITERATOR_DONT_IGNORE_CASE |
GIT_ITERATOR_INCLUDE_CONFLICTS;
if ((error = git_iterator_for_index(&index_iterator,
git_index_owner(index), index, &opts)) < 0 ||
((error = git_iterator_current(&old_entry, index_iterator)) < 0 &&
error != GIT_ITEROVER) ||
((error = git_iterator_current(&new_entry, new_iterator)) < 0 &&
error != GIT_ITEROVER))
goto done;
while (true) {
git_index_entry
*dup_entry = NULL,
*add_entry = NULL,
*remove_entry = NULL;
int diff;
error = 0;
if (old_entry && new_entry)
diff = git_index_entry_cmp(old_entry, new_entry);
else if (!old_entry && new_entry)
diff = 1;
else if (old_entry && !new_entry)
diff = -1;
else
break;
if (diff < 0) {
remove_entry = (git_index_entry *)old_entry;
} else if (diff > 0) {
dup_entry = (git_index_entry *)new_entry;
} else {
/* Path and stage are equal, if the OID is equal, keep it to
* keep the stat cache data.
*/
if (git_oid_equal(&old_entry->id, &new_entry->id) &&
old_entry->mode == new_entry->mode) {
add_entry = (git_index_entry *)old_entry;
} else {
dup_entry = (git_index_entry *)new_entry;
remove_entry = (git_index_entry *)old_entry;
}
}
if (dup_entry) {
if ((error = index_entry_dup_nocache(&add_entry, index, dup_entry)) < 0)
goto done;
index_entry_adjust_namemask(add_entry,
((struct entry_internal *)add_entry)->pathlen);
}
/* invalidate this path in the tree cache if this is new (to
* invalidate the parent trees)
*/
if (dup_entry && !remove_entry && index->tree)
git_tree_cache_invalidate_path(index->tree, dup_entry->path);
if (add_entry) {
if ((error = git_vector_insert(&new_entries, add_entry)) == 0)
error = index_map_set(new_entries_map, add_entry,
index->ignore_case);
}
if (remove_entry && error >= 0)
error = git_vector_insert(&remove_entries, remove_entry);
if (error < 0) {
git_error_set(GIT_ERROR_INDEX, "failed to insert entry");
goto done;
}
if (diff <= 0) {
if ((error = git_iterator_advance(&old_entry, index_iterator)) < 0 &&
error != GIT_ITEROVER)
goto done;
}
if (diff >= 0) {
if ((error = git_iterator_advance(&new_entry, new_iterator)) < 0 &&
error != GIT_ITEROVER)
goto done;
}
}
if ((error = git_index_name_clear(index)) < 0 ||
(error = git_index_reuc_clear(index)) < 0)
goto done;
git_vector_swap(&new_entries, &index->entries);
new_entries_map = git_atomic_swap(index->entries_map, new_entries_map);
git_vector_foreach(&remove_entries, i, entry) {
if (index->tree)
git_tree_cache_invalidate_path(index->tree, entry->path);
index_entry_free(entry);
}
clear_uptodate(index);
index->dirty = 1;
error = 0;
done:
git_idxmap_free(new_entries_map);
git_vector_free(&new_entries);
git_vector_free(&remove_entries);
git_iterator_free(index_iterator);
return error;
}
int git_index_read_index(
git_index *index,
const git_index *new_index)
{
git_iterator *new_iterator = NULL;
git_iterator_options opts = GIT_ITERATOR_OPTIONS_INIT;
int error;
opts.flags = GIT_ITERATOR_DONT_IGNORE_CASE |
GIT_ITERATOR_INCLUDE_CONFLICTS;
if ((error = git_iterator_for_index(&new_iterator,
git_index_owner(new_index), (git_index *)new_index, &opts)) < 0 ||
(error = git_index_read_iterator(index, new_iterator,
new_index->entries.length)) < 0)
goto done;
done:
git_iterator_free(new_iterator);
return error;
}
git_repository *git_index_owner(const git_index *index)
{
return INDEX_OWNER(index);
}
enum {
INDEX_ACTION_NONE = 0,
INDEX_ACTION_UPDATE = 1,
INDEX_ACTION_REMOVE = 2,
INDEX_ACTION_ADDALL = 3,
};
int git_index_add_all(
git_index *index,
const git_strarray *paths,
unsigned int flags,
git_index_matched_path_cb cb,
void *payload)
{
int error;
git_repository *repo;
git_iterator *wditer = NULL;
git_pathspec ps;
bool no_fnmatch = (flags & GIT_INDEX_ADD_DISABLE_PATHSPEC_MATCH) != 0;
GIT_ASSERT_ARG(index);
repo = INDEX_OWNER(index);
if ((error = git_repository__ensure_not_bare(repo, "index add all")) < 0)
return error;
if ((error = git_pathspec__init(&ps, paths)) < 0)
return error;
/* optionally check that pathspec doesn't mention any ignored files */
if ((flags & GIT_INDEX_ADD_CHECK_PATHSPEC) != 0 &&
(flags & GIT_INDEX_ADD_FORCE) == 0 &&
(error = git_ignore__check_pathspec_for_exact_ignores(
repo, &ps.pathspec, no_fnmatch)) < 0)
goto cleanup;
error = index_apply_to_wd_diff(index, INDEX_ACTION_ADDALL, paths, flags, cb, payload);
if (error)
git_error_set_after_callback(error);
cleanup:
git_iterator_free(wditer);
git_pathspec__clear(&ps);
return error;
}
struct foreach_diff_data {
git_index *index;
const git_pathspec *pathspec;
unsigned int flags;
git_index_matched_path_cb cb;
void *payload;
};
static int apply_each_file(const git_diff_delta *delta, float progress, void *payload)
{
struct foreach_diff_data *data = payload;
const char *match, *path;
int error = 0;
GIT_UNUSED(progress);
path = delta->old_file.path;
/* We only want those which match the pathspecs */
if (!git_pathspec__match(
&data->pathspec->pathspec, path, false, (bool)data->index->ignore_case,
&match, NULL))
return 0;
if (data->cb)
error = data->cb(path, match, data->payload);
if (error > 0) /* skip this entry */
return 0;
if (error < 0) /* actual error */
return error;
/* If the workdir item does not exist, remove it from the index. */
if ((delta->new_file.flags & GIT_DIFF_FLAG_EXISTS) == 0)
error = git_index_remove_bypath(data->index, path);
else
error = git_index_add_bypath(data->index, delta->new_file.path);
return error;
}
static int index_apply_to_wd_diff(git_index *index, int action, const git_strarray *paths,
unsigned int flags,
git_index_matched_path_cb cb, void *payload)
{
int error;
git_diff *diff;
git_pathspec ps;
git_repository *repo;
git_diff_options opts = GIT_DIFF_OPTIONS_INIT;
struct foreach_diff_data data = {
index,
NULL,
flags,
cb,
payload,
};
GIT_ASSERT_ARG(index);
GIT_ASSERT_ARG(action == INDEX_ACTION_UPDATE || action == INDEX_ACTION_ADDALL);
repo = INDEX_OWNER(index);
if (!repo) {
return create_index_error(-1,
"cannot run update; the index is not backed up by a repository.");
}
/*
* We do the matching ourselves intead of passing the list to
* diff because we want to tell the callback which one
* matched, which we do not know if we ask diff to filter for us.
*/
if ((error = git_pathspec__init(&ps, paths)) < 0)
return error;
opts.flags = GIT_DIFF_INCLUDE_TYPECHANGE;
if (action == INDEX_ACTION_ADDALL) {
opts.flags |= GIT_DIFF_INCLUDE_UNTRACKED |
GIT_DIFF_RECURSE_UNTRACKED_DIRS;
if (flags == GIT_INDEX_ADD_FORCE)
opts.flags |= GIT_DIFF_INCLUDE_IGNORED;
}
if ((error = git_diff_index_to_workdir(&diff, repo, index, &opts)) < 0)
goto cleanup;
data.pathspec = &ps;
error = git_diff_foreach(diff, apply_each_file, NULL, NULL, NULL, &data);
git_diff_free(diff);
if (error) /* make sure error is set if callback stopped iteration */
git_error_set_after_callback(error);
cleanup:
git_pathspec__clear(&ps);
return error;
}
static int index_apply_to_all(
git_index *index,
int action,
const git_strarray *paths,
git_index_matched_path_cb cb,
void *payload)
{
int error = 0;
size_t i;
git_pathspec ps;
const char *match;
git_buf path = GIT_BUF_INIT;
GIT_ASSERT_ARG(index);
if ((error = git_pathspec__init(&ps, paths)) < 0)
return error;
git_vector_sort(&index->entries);
for (i = 0; !error && i < index->entries.length; ++i) {
git_index_entry *entry = git_vector_get(&index->entries, i);
/* check if path actually matches */
if (!git_pathspec__match(
&ps.pathspec, entry->path, false, (bool)index->ignore_case,
&match, NULL))
continue;
/* issue notification callback if requested */
if (cb && (error = cb(entry->path, match, payload)) != 0) {
if (error > 0) { /* return > 0 means skip this one */
error = 0;
continue;
}
if (error < 0) /* return < 0 means abort */
break;
}
/* index manipulation may alter entry, so don't depend on it */
if ((error = git_buf_sets(&path, entry->path)) < 0)
break;
switch (action) {
case INDEX_ACTION_NONE:
break;
case INDEX_ACTION_UPDATE:
error = git_index_add_bypath(index, path.ptr);
if (error == GIT_ENOTFOUND) {
git_error_clear();
error = git_index_remove_bypath(index, path.ptr);
if (!error) /* back up foreach if we removed this */
i--;
}
break;
case INDEX_ACTION_REMOVE:
if (!(error = git_index_remove_bypath(index, path.ptr)))
i--; /* back up foreach if we removed this */
break;
default:
git_error_set(GIT_ERROR_INVALID, "unknown index action %d", action);
error = -1;
break;
}
}
git_buf_dispose(&path);
git_pathspec__clear(&ps);
return error;
}
int git_index_remove_all(
git_index *index,
const git_strarray *pathspec,
git_index_matched_path_cb cb,
void *payload)
{
int error = index_apply_to_all(
index, INDEX_ACTION_REMOVE, pathspec, cb, payload);
if (error) /* make sure error is set if callback stopped iteration */
git_error_set_after_callback(error);
return error;
}
int git_index_update_all(
git_index *index,
const git_strarray *pathspec,
git_index_matched_path_cb cb,
void *payload)
{
int error = index_apply_to_wd_diff(index, INDEX_ACTION_UPDATE, pathspec, 0, cb, payload);
if (error) /* make sure error is set if callback stopped iteration */
git_error_set_after_callback(error);
return error;
}
int git_index_snapshot_new(git_vector *snap, git_index *index)
{
int error;
GIT_REFCOUNT_INC(index);
git_atomic32_inc(&index->readers);
git_vector_sort(&index->entries);
error = git_vector_dup(snap, &index->entries, index->entries._cmp);
if (error < 0)
git_index_snapshot_release(snap, index);
return error;
}
void git_index_snapshot_release(git_vector *snap, git_index *index)
{
git_vector_free(snap);
git_atomic32_dec(&index->readers);
git_index_free(index);
}
int git_index_snapshot_find(
size_t *out, git_vector *entries, git_vector_cmp entry_srch,
const char *path, size_t path_len, int stage)
{
return index_find_in_entries(out, entries, entry_srch, path, path_len, stage);
}
int git_indexwriter_init(
git_indexwriter *writer,
git_index *index)
{
int error;
GIT_REFCOUNT_INC(index);
writer->index = index;
if (!index->index_file_path)
return create_index_error(-1,
"failed to write index: The index is in-memory only");
if ((error = git_filebuf_open(
&writer->file, index->index_file_path, GIT_FILEBUF_HASH_CONTENTS, GIT_INDEX_FILE_MODE)) < 0) {
if (error == GIT_ELOCKED)
git_error_set(GIT_ERROR_INDEX, "the index is locked; this might be due to a concurrent or crashed process");
return error;
}
writer->should_write = 1;
return 0;
}
int git_indexwriter_init_for_operation(
git_indexwriter *writer,
git_repository *repo,
unsigned int *checkout_strategy)
{
git_index *index;
int error;
if ((error = git_repository_index__weakptr(&index, repo)) < 0 ||
(error = git_indexwriter_init(writer, index)) < 0)
return error;
writer->should_write = (*checkout_strategy & GIT_CHECKOUT_DONT_WRITE_INDEX) == 0;
*checkout_strategy |= GIT_CHECKOUT_DONT_WRITE_INDEX;
return 0;
}
int git_indexwriter_commit(git_indexwriter *writer)
{
int error;
git_oid checksum = {{ 0 }};
if (!writer->should_write)
return 0;
git_vector_sort(&writer->index->entries);
git_vector_sort(&writer->index->reuc);
if ((error = write_index(&checksum, writer->index, &writer->file)) < 0) {
git_indexwriter_cleanup(writer);
return error;
}
if ((error = git_filebuf_commit(&writer->file)) < 0)
return error;
if ((error = git_futils_filestamp_check(
&writer->index->stamp, writer->index->index_file_path)) < 0) {
git_error_set(GIT_ERROR_OS, "could not read index timestamp");
return -1;
}
writer->index->dirty = 0;
writer->index->on_disk = 1;
git_oid_cpy(&writer->index->checksum, &checksum);
git_index_free(writer->index);
writer->index = NULL;
return 0;
}
void git_indexwriter_cleanup(git_indexwriter *writer)
{
git_filebuf_cleanup(&writer->file);
git_index_free(writer->index);
writer->index = NULL;
}
/* Deprecated functions */
#ifndef GIT_DEPRECATE_HARD
int git_index_add_frombuffer(
git_index *index, const git_index_entry *source_entry,
const void *buffer, size_t len)
{
return git_index_add_from_buffer(index, source_entry, buffer, len);
}
#endif
|
0 |
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2
|
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2/src/email.c
|
/*
* Copyright (C) the libgit2 contributors. All rights reserved.
*
* This file is part of libgit2, distributed under the GNU GPL v2 with
* a Linking Exception. For full terms see the included COPYING file.
*/
#include "email.h"
#include "buffer.h"
#include "common.h"
#include "diff_generate.h"
#include "git2/email.h"
#include "git2/patch.h"
#include "git2/version.h"
/*
* Git uses a "magic" timestamp to indicate that an email message
* is from `git format-patch` (or our equivalent).
*/
#define EMAIL_TIMESTAMP "Mon Sep 17 00:00:00 2001"
GIT_INLINE(int) include_prefix(
size_t patch_count,
git_email_create_options *opts)
{
return ((!opts->subject_prefix || *opts->subject_prefix) ||
(opts->flags & GIT_EMAIL_CREATE_ALWAYS_NUMBER) != 0 ||
opts->reroll_number ||
(patch_count > 1 && !(opts->flags & GIT_EMAIL_CREATE_OMIT_NUMBERS)));
}
static int append_prefix(
git_buf *out,
size_t patch_idx,
size_t patch_count,
git_email_create_options *opts)
{
const char *subject_prefix = opts->subject_prefix ?
opts->subject_prefix : "PATCH";
git_buf_putc(out, '[');
if (*subject_prefix)
git_buf_puts(out, subject_prefix);
if (opts->reroll_number) {
if (*subject_prefix)
git_buf_putc(out, ' ');
git_buf_printf(out, "v%" PRIuZ, opts->reroll_number);
}
if ((opts->flags & GIT_EMAIL_CREATE_ALWAYS_NUMBER) != 0 ||
(patch_count > 1 && !(opts->flags & GIT_EMAIL_CREATE_OMIT_NUMBERS))) {
size_t start_number = opts->start_number ?
opts->start_number : 1;
if (*subject_prefix || opts->reroll_number)
git_buf_putc(out, ' ');
git_buf_printf(out, "%" PRIuZ "/%" PRIuZ,
patch_idx + (start_number - 1),
patch_count + (start_number - 1));
}
git_buf_puts(out, "]");
return git_buf_oom(out) ? -1 : 0;
}
static int append_subject(
git_buf *out,
size_t patch_idx,
size_t patch_count,
const char *summary,
git_email_create_options *opts)
{
bool prefix = include_prefix(patch_count, opts);
size_t summary_len = summary ? strlen(summary) : 0;
int error;
if (summary_len) {
const char *nl = strchr(summary, '\n');
if (nl)
summary_len = (nl - summary);
}
if ((error = git_buf_puts(out, "Subject: ")) < 0)
return error;
if (prefix &&
(error = append_prefix(out, patch_idx, patch_count, opts)) < 0)
return error;
if (prefix && summary_len && (error = git_buf_putc(out, ' ')) < 0)
return error;
if (summary_len &&
(error = git_buf_put(out, summary, summary_len)) < 0)
return error;
return git_buf_putc(out, '\n');
}
static int append_header(
git_buf *out,
size_t patch_idx,
size_t patch_count,
const git_oid *commit_id,
const char *summary,
const git_signature *author,
git_email_create_options *opts)
{
char id[GIT_OID_HEXSZ];
char date[GIT_DATE_RFC2822_SZ];
int error;
if ((error = git_oid_fmt(id, commit_id)) < 0 ||
(error = git_buf_printf(out, "From %.*s %s\n", GIT_OID_HEXSZ, id, EMAIL_TIMESTAMP)) < 0 ||
(error = git_buf_printf(out, "From: %s <%s>\n", author->name, author->email)) < 0 ||
(error = git__date_rfc2822_fmt(date, sizeof(date), &author->when)) < 0 ||
(error = git_buf_printf(out, "Date: %s\n", date)) < 0 ||
(error = append_subject(out, patch_idx, patch_count, summary, opts)) < 0)
return error;
if ((error = git_buf_putc(out, '\n')) < 0)
return error;
return 0;
}
static int append_body(git_buf *out, const char *body)
{
size_t body_len;
int error;
if (!body)
return 0;
body_len = strlen(body);
if ((error = git_buf_puts(out, body)) < 0)
return error;
if (body_len && body[body_len - 1] != '\n')
error = git_buf_putc(out, '\n');
return error;
}
static int append_diffstat(git_buf *out, git_diff *diff)
{
git_diff_stats *stats = NULL;
unsigned int format_flags;
int error;
format_flags = GIT_DIFF_STATS_FULL | GIT_DIFF_STATS_INCLUDE_SUMMARY;
if ((error = git_diff_get_stats(&stats, diff)) == 0 &&
(error = git_diff_stats_to_buf(out, stats, format_flags, 0)) == 0)
error = git_buf_putc(out, '\n');
git_diff_stats_free(stats);
return error;
}
static int append_patches(git_buf *out, git_diff *diff)
{
size_t i, deltas;
int error = 0;
deltas = git_diff_num_deltas(diff);
for (i = 0; i < deltas; ++i) {
git_patch *patch = NULL;
if ((error = git_patch_from_diff(&patch, diff, i)) >= 0)
error = git_patch_to_buf(out, patch);
git_patch_free(patch);
if (error < 0)
break;
}
return error;
}
int git_email__append_from_diff(
git_buf *out,
git_diff *diff,
size_t patch_idx,
size_t patch_count,
const git_oid *commit_id,
const char *summary,
const char *body,
const git_signature *author,
const git_email_create_options *given_opts)
{
git_email_create_options opts = GIT_EMAIL_CREATE_OPTIONS_INIT;
int error;
GIT_ASSERT_ARG(out);
GIT_ASSERT_ARG(diff);
GIT_ASSERT_ARG(!patch_idx || patch_idx <= patch_count);
GIT_ASSERT_ARG(commit_id);
GIT_ASSERT_ARG(author);
GIT_ERROR_CHECK_VERSION(given_opts,
GIT_EMAIL_CREATE_OPTIONS_VERSION,
"git_email_create_options");
if (given_opts)
memcpy(&opts, given_opts, sizeof(git_email_create_options));
git_buf_sanitize(out);
if ((error = append_header(out, patch_idx, patch_count, commit_id, summary, author, &opts)) == 0 &&
(error = append_body(out, body)) == 0 &&
(error = git_buf_puts(out, "---\n")) == 0 &&
(error = append_diffstat(out, diff)) == 0 &&
(error = append_patches(out, diff)) == 0)
error = git_buf_puts(out, "--\nlibgit2 " LIBGIT2_VERSION "\n\n");
return error;
}
int git_email_create_from_diff(
git_buf *out,
git_diff *diff,
size_t patch_idx,
size_t patch_count,
const git_oid *commit_id,
const char *summary,
const char *body,
const git_signature *author,
const git_email_create_options *given_opts)
{
int error;
git_buf_sanitize(out);
git_buf_clear(out);
error = git_email__append_from_diff(out, diff, patch_idx,
patch_count, commit_id, summary, body, author,
given_opts);
return error;
}
int git_email_create_from_commit(
git_buf *out,
git_commit *commit,
const git_email_create_options *given_opts)
{
git_email_create_options opts = GIT_EMAIL_CREATE_OPTIONS_INIT;
git_diff *diff = NULL;
git_repository *repo;
git_diff_options *diff_opts;
git_diff_find_options *find_opts;
const git_signature *author;
const char *summary, *body;
const git_oid *commit_id;
int error = -1;
GIT_ASSERT_ARG(out);
GIT_ASSERT_ARG(commit);
GIT_ERROR_CHECK_VERSION(given_opts,
GIT_EMAIL_CREATE_OPTIONS_VERSION,
"git_email_create_options");
if (given_opts)
memcpy(&opts, given_opts, sizeof(git_email_create_options));
repo = git_commit_owner(commit);
author = git_commit_author(commit);
summary = git_commit_summary(commit);
body = git_commit_body(commit);
commit_id = git_commit_id(commit);
diff_opts = &opts.diff_opts;
find_opts = &opts.diff_find_opts;
if ((error = git_diff__commit(&diff, repo, commit, diff_opts)) < 0)
goto done;
if ((opts.flags & GIT_EMAIL_CREATE_NO_RENAMES) == 0 &&
(error = git_diff_find_similar(diff, find_opts)) < 0)
goto done;
error = git_email_create_from_diff(out, diff, 1, 1, commit_id, summary, body, author, &opts);
done:
git_diff_free(diff);
return error;
}
|
0 |
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2
|
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2/src/pool.h
|
/*
* Copyright (C) the libgit2 contributors. All rights reserved.
*
* This file is part of libgit2, distributed under the GNU GPL v2 with
* a Linking Exception. For full terms see the included COPYING file.
*/
#ifndef INCLUDE_pool_h__
#define INCLUDE_pool_h__
#include "common.h"
#include "vector.h"
typedef struct git_pool_page git_pool_page;
#ifndef GIT_DEBUG_POOL
/**
* Chunked allocator.
*
* A `git_pool` can be used when you want to cheaply allocate
* multiple items of the same type and are willing to free them
* all together with a single call. The two most common cases
* are a set of fixed size items (such as lots of OIDs) or a
* bunch of strings.
*
* Internally, a `git_pool` allocates pages of memory and then
* deals out blocks from the trailing unused portion of each page.
* The pages guarantee that the number of actual allocations done
* will be much smaller than the number of items needed.
*
* For examples of how to set up a `git_pool` see `git_pool_init`.
*/
typedef struct {
git_pool_page *pages; /* allocated pages */
size_t item_size; /* size of single alloc unit in bytes */
size_t page_size; /* size of page in bytes */
} git_pool;
#define GIT_POOL_INIT { NULL, 0, 0 }
#else
/**
* Debug chunked allocator.
*
* Acts just like `git_pool` but instead of actually pooling allocations it
* passes them through to `git__malloc`. This makes it possible to easily debug
* systems that use `git_pool` using valgrind.
*
* In order to track allocations during the lifetime of the pool we use a
* `git_vector`. When the pool is deallocated everything in the vector is
* freed.
*
* `API is exactly the same as the standard `git_pool` with one exception.
* Since we aren't allocating pages to hand out in chunks we can't easily
* implement `git_pool__open_pages`.
*/
typedef struct {
git_vector allocations;
size_t item_size;
size_t page_size;
} git_pool;
#define GIT_POOL_INIT { GIT_VECTOR_INIT, 0, 0 }
#endif
/**
* Initialize a pool.
*
* To allocation strings, use like this:
*
* git_pool_init(&string_pool, 1);
* my_string = git_pool_strdup(&string_pool, your_string);
*
* To allocate items of fixed size, use like this:
*
* git_pool_init(&pool, sizeof(item));
* my_item = git_pool_malloc(&pool, 1);
*
* Of course, you can use this in other ways, but those are the
* two most common patterns.
*/
extern int git_pool_init(git_pool *pool, size_t item_size);
/**
* Free all items in pool
*/
extern void git_pool_clear(git_pool *pool);
/**
* Swap two pools with one another
*/
extern void git_pool_swap(git_pool *a, git_pool *b);
/**
* Allocate space for one or more items from a pool.
*/
extern void *git_pool_malloc(git_pool *pool, size_t items);
extern void *git_pool_mallocz(git_pool *pool, size_t items);
/**
* Allocate space and duplicate string data into it.
*
* This is allowed only for pools with item_size == sizeof(char)
*/
extern char *git_pool_strndup(git_pool *pool, const char *str, size_t n);
/**
* Allocate space and duplicate a string into it.
*
* This is allowed only for pools with item_size == sizeof(char)
*/
extern char *git_pool_strdup(git_pool *pool, const char *str);
/**
* Allocate space and duplicate a string into it, NULL is no error.
*
* This is allowed only for pools with item_size == sizeof(char)
*/
extern char *git_pool_strdup_safe(git_pool *pool, const char *str);
/**
* Allocate space for the concatenation of two strings.
*
* This is allowed only for pools with item_size == sizeof(char)
*/
extern char *git_pool_strcat(git_pool *pool, const char *a, const char *b);
/*
* Misc utilities
*/
#ifndef GIT_DEBUG_POOL
extern uint32_t git_pool__open_pages(git_pool *pool);
#endif
extern bool git_pool__ptr_in_pool(git_pool *pool, void *ptr);
/**
* This function is being called by our global setup routines to
* initialize the system pool size.
*
* @return 0 on success, <0 on failure
*/
extern int git_pool_global_init(void);
#endif
|
0 |
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2
|
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2/src/refdb.h
|
/*
* Copyright (C) the libgit2 contributors. All rights reserved.
*
* This file is part of libgit2, distributed under the GNU GPL v2 with
* a Linking Exception. For full terms see the included COPYING file.
*/
#ifndef INCLUDE_refdb_h__
#define INCLUDE_refdb_h__
#include "common.h"
#include "git2/refdb.h"
#include "repository.h"
struct git_refdb {
git_refcount rc;
git_repository *repo;
git_refdb_backend *backend;
};
void git_refdb__free(git_refdb *db);
int git_refdb_exists(
int *exists,
git_refdb *refdb,
const char *ref_name);
int git_refdb_lookup(
git_reference **out,
git_refdb *refdb,
const char *ref_name);
/**
* Resolve the reference by following symbolic references.
*
* Given a reference name, this function will follow any symbolic references up
* to `max_nesting` deep and return the resolved direct reference. If any of
* the intermediate symbolic references points to a non-existing reference,
* then that symbolic reference is returned instead with an error code of `0`.
* If the given reference is a direct reference already, it is returned
* directly.
*
* If `max_nesting` is `0`, the reference will not be resolved. If it's
* negative, it will be set to the default resolve depth which is `5`.
*
* @param out Pointer to store the result in.
* @param db The refdb to use for resolving the reference.
* @param ref_name The reference name to lookup and resolve.
* @param max_nesting The maximum nesting depth.
* @return `0` on success, a negative error code otherwise.
*/
int git_refdb_resolve(
git_reference **out,
git_refdb *db,
const char *ref_name,
int max_nesting);
int git_refdb_rename(
git_reference **out,
git_refdb *db,
const char *old_name,
const char *new_name,
int force,
const git_signature *who,
const char *message);
int git_refdb_iterator(git_reference_iterator **out, git_refdb *db, const char *glob);
int git_refdb_iterator_next(git_reference **out, git_reference_iterator *iter);
int git_refdb_iterator_next_name(const char **out, git_reference_iterator *iter);
void git_refdb_iterator_free(git_reference_iterator *iter);
int git_refdb_write(git_refdb *refdb, git_reference *ref, int force, const git_signature *who, const char *message, const git_oid *old_id, const char *old_target);
int git_refdb_delete(git_refdb *refdb, const char *ref_name, const git_oid *old_id, const char *old_target);
int git_refdb_reflog_read(git_reflog **out, git_refdb *db, const char *name);
int git_refdb_reflog_write(git_reflog *reflog);
/**
* Determine whether a reflog entry should be created for the given reference.
*
* Whether or not writing to a reference should create a reflog entry is
* dependent on a number of things. Most importantly, there's the
* "core.logAllRefUpdates" setting that controls in which situations a
* reference should get a corresponding reflog entry. The following values for
* it are understood:
*
* - "false": Do not log reference updates.
*
* - "true": Log normal reference updates. This will write entries for
* references in "refs/heads", "refs/remotes", "refs/notes" and
* "HEAD" or if the reference already has a log entry.
*
* - "always": Always create a reflog entry.
*
* If unset, the value will default to "true" for non-bare repositories and
* "false" for bare ones.
*
* @param out pointer to which the result will be written, `1` means a reflog
* entry should be written, `0` means none should be written.
* @param db The refdb to decide this for.
* @param ref The reference one wants to check.
* @return `0` on success, a negative error code otherwise.
*/
int git_refdb_should_write_reflog(int *out, git_refdb *db, const git_reference *ref);
/**
* Determine whether a reflog entry should be created for HEAD if creating one
* for the given reference
*
* In case the given reference is being pointed to by HEAD, then creating a
* reflog entry for this reference also requires us to create a corresponding
* reflog entry for HEAD. This function can be used to determine that scenario.
*
* @param out pointer to which the result will be written, `1` means a reflog
* entry should be written, `0` means none should be written.
* @param db The refdb to decide this for.
* @param ref The reference one wants to check.
* @return `0` on success, a negative error code otherwise.
*/
int git_refdb_should_write_head_reflog(int *out, git_refdb *db, const git_reference *ref);
int git_refdb_has_log(git_refdb *db, const char *refname);
int git_refdb_ensure_log(git_refdb *refdb, const char *refname);
int git_refdb_lock(void **payload, git_refdb *db, const char *refname);
int git_refdb_unlock(git_refdb *db, void *payload, int success, int update_reflog, const git_reference *ref, const git_signature *sig, const char *message);
#endif
|
0 |
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2
|
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2/src/refdb.c
|
/*
* Copyright (C) the libgit2 contributors. All rights reserved.
*
* This file is part of libgit2, distributed under the GNU GPL v2 with
* a Linking Exception. For full terms see the included COPYING file.
*/
#include "refdb.h"
#include "git2/object.h"
#include "git2/refs.h"
#include "git2/refdb.h"
#include "git2/sys/refdb_backend.h"
#include "hash.h"
#include "refs.h"
#include "reflog.h"
#include "posix.h"
#define DEFAULT_NESTING_LEVEL 5
#define MAX_NESTING_LEVEL 10
int git_refdb_new(git_refdb **out, git_repository *repo)
{
git_refdb *db;
GIT_ASSERT_ARG(out);
GIT_ASSERT_ARG(repo);
db = git__calloc(1, sizeof(*db));
GIT_ERROR_CHECK_ALLOC(db);
db->repo = repo;
*out = db;
GIT_REFCOUNT_INC(db);
return 0;
}
int git_refdb_open(git_refdb **out, git_repository *repo)
{
git_refdb *db;
git_refdb_backend *dir;
GIT_ASSERT_ARG(out);
GIT_ASSERT_ARG(repo);
*out = NULL;
if (git_refdb_new(&db, repo) < 0)
return -1;
/* Add the default (filesystem) backend */
if (git_refdb_backend_fs(&dir, repo) < 0) {
git_refdb_free(db);
return -1;
}
db->repo = repo;
db->backend = dir;
*out = db;
return 0;
}
static void refdb_free_backend(git_refdb *db)
{
if (db->backend)
db->backend->free(db->backend);
}
int git_refdb_set_backend(git_refdb *db, git_refdb_backend *backend)
{
GIT_ERROR_CHECK_VERSION(backend, GIT_REFDB_BACKEND_VERSION, "git_refdb_backend");
if (!backend->exists || !backend->lookup || !backend->iterator ||
!backend->write || !backend->rename || !backend->del ||
!backend->has_log || !backend->ensure_log || !backend->free ||
!backend->reflog_read || !backend->reflog_write ||
!backend->reflog_rename || !backend->reflog_delete ||
(backend->lock && !backend->unlock)) {
git_error_set(GIT_ERROR_REFERENCE, "incomplete refdb backend implementation");
return GIT_EINVALID;
}
refdb_free_backend(db);
db->backend = backend;
return 0;
}
int git_refdb_compress(git_refdb *db)
{
GIT_ASSERT_ARG(db);
if (db->backend->compress)
return db->backend->compress(db->backend);
return 0;
}
void git_refdb__free(git_refdb *db)
{
refdb_free_backend(db);
git__memzero(db, sizeof(*db));
git__free(db);
}
void git_refdb_free(git_refdb *db)
{
if (db == NULL)
return;
GIT_REFCOUNT_DEC(db, git_refdb__free);
}
int git_refdb_exists(int *exists, git_refdb *refdb, const char *ref_name)
{
GIT_ASSERT_ARG(exists);
GIT_ASSERT_ARG(refdb);
GIT_ASSERT_ARG(refdb->backend);
return refdb->backend->exists(exists, refdb->backend, ref_name);
}
int git_refdb_lookup(git_reference **out, git_refdb *db, const char *ref_name)
{
git_reference *ref;
int error;
GIT_ASSERT_ARG(db);
GIT_ASSERT_ARG(db->backend);
GIT_ASSERT_ARG(out);
GIT_ASSERT_ARG(ref_name);
error = db->backend->lookup(&ref, db->backend, ref_name);
if (error < 0)
return error;
GIT_REFCOUNT_INC(db);
ref->db = db;
*out = ref;
return 0;
}
int git_refdb_resolve(
git_reference **out,
git_refdb *db,
const char *ref_name,
int max_nesting)
{
git_reference *ref = NULL;
int error = 0, nesting;
*out = NULL;
if (max_nesting > MAX_NESTING_LEVEL)
max_nesting = MAX_NESTING_LEVEL;
else if (max_nesting < 0)
max_nesting = DEFAULT_NESTING_LEVEL;
if ((error = git_refdb_lookup(&ref, db, ref_name)) < 0)
goto out;
for (nesting = 0; nesting < max_nesting; nesting++) {
git_reference *resolved;
if (ref->type == GIT_REFERENCE_DIRECT)
break;
if ((error = git_refdb_lookup(&resolved, db, git_reference_symbolic_target(ref))) < 0) {
/* If we found a symbolic reference with a nonexistent target, return it. */
if (error == GIT_ENOTFOUND) {
error = 0;
*out = ref;
ref = NULL;
}
goto out;
}
git_reference_free(ref);
ref = resolved;
}
if (ref->type != GIT_REFERENCE_DIRECT && max_nesting != 0) {
git_error_set(GIT_ERROR_REFERENCE,
"cannot resolve reference (>%u levels deep)", max_nesting);
error = -1;
goto out;
}
*out = ref;
ref = NULL;
out:
git_reference_free(ref);
return error;
}
int git_refdb_iterator(git_reference_iterator **out, git_refdb *db, const char *glob)
{
int error;
if (!db->backend || !db->backend->iterator) {
git_error_set(GIT_ERROR_REFERENCE, "this backend doesn't support iterators");
return -1;
}
if ((error = db->backend->iterator(out, db->backend, glob)) < 0)
return error;
GIT_REFCOUNT_INC(db);
(*out)->db = db;
return 0;
}
int git_refdb_iterator_next(git_reference **out, git_reference_iterator *iter)
{
int error;
if ((error = iter->next(out, iter)) < 0)
return error;
GIT_REFCOUNT_INC(iter->db);
(*out)->db = iter->db;
return 0;
}
int git_refdb_iterator_next_name(const char **out, git_reference_iterator *iter)
{
return iter->next_name(out, iter);
}
void git_refdb_iterator_free(git_reference_iterator *iter)
{
GIT_REFCOUNT_DEC(iter->db, git_refdb__free);
iter->free(iter);
}
int git_refdb_write(git_refdb *db, git_reference *ref, int force, const git_signature *who, const char *message, const git_oid *old_id, const char *old_target)
{
GIT_ASSERT_ARG(db);
GIT_ASSERT_ARG(db->backend);
GIT_REFCOUNT_INC(db);
ref->db = db;
return db->backend->write(db->backend, ref, force, who, message, old_id, old_target);
}
int git_refdb_rename(
git_reference **out,
git_refdb *db,
const char *old_name,
const char *new_name,
int force,
const git_signature *who,
const char *message)
{
int error;
GIT_ASSERT_ARG(db);
GIT_ASSERT_ARG(db->backend);
error = db->backend->rename(out, db->backend, old_name, new_name, force, who, message);
if (error < 0)
return error;
if (out) {
GIT_REFCOUNT_INC(db);
(*out)->db = db;
}
return 0;
}
int git_refdb_delete(struct git_refdb *db, const char *ref_name, const git_oid *old_id, const char *old_target)
{
GIT_ASSERT_ARG(db);
GIT_ASSERT_ARG(db->backend);
return db->backend->del(db->backend, ref_name, old_id, old_target);
}
int git_refdb_reflog_read(git_reflog **out, git_refdb *db, const char *name)
{
int error;
GIT_ASSERT_ARG(db);
GIT_ASSERT_ARG(db->backend);
if ((error = db->backend->reflog_read(out, db->backend, name)) < 0)
return error;
GIT_REFCOUNT_INC(db);
(*out)->db = db;
return 0;
}
int git_refdb_should_write_reflog(int *out, git_refdb *db, const git_reference *ref)
{
int error, logall;
error = git_repository__configmap_lookup(&logall, db->repo, GIT_CONFIGMAP_LOGALLREFUPDATES);
if (error < 0)
return error;
/* Defaults to the opposite of the repo being bare */
if (logall == GIT_LOGALLREFUPDATES_UNSET)
logall = !git_repository_is_bare(db->repo);
*out = 0;
switch (logall) {
case GIT_LOGALLREFUPDATES_FALSE:
*out = 0;
break;
case GIT_LOGALLREFUPDATES_TRUE:
/* Only write if it already has a log,
* or if it's under heads/, remotes/ or notes/
*/
*out = git_refdb_has_log(db, ref->name) ||
!git__prefixcmp(ref->name, GIT_REFS_HEADS_DIR) ||
!git__strcmp(ref->name, GIT_HEAD_FILE) ||
!git__prefixcmp(ref->name, GIT_REFS_REMOTES_DIR) ||
!git__prefixcmp(ref->name, GIT_REFS_NOTES_DIR);
break;
case GIT_LOGALLREFUPDATES_ALWAYS:
*out = 1;
break;
}
return 0;
}
int git_refdb_should_write_head_reflog(int *out, git_refdb *db, const git_reference *ref)
{
git_reference *head = NULL, *resolved = NULL;
const char *name;
int error;
*out = 0;
if (ref->type == GIT_REFERENCE_SYMBOLIC) {
error = 0;
goto out;
}
if ((error = git_refdb_lookup(&head, db, GIT_HEAD_FILE)) < 0)
goto out;
if (git_reference_type(head) == GIT_REFERENCE_DIRECT)
goto out;
/* Go down the symref chain until we find the branch */
if ((error = git_refdb_resolve(&resolved, db, git_reference_symbolic_target(head), -1)) < 0) {
if (error != GIT_ENOTFOUND)
goto out;
error = 0;
name = git_reference_symbolic_target(head);
} else if (git_reference_type(resolved) == GIT_REFERENCE_SYMBOLIC) {
name = git_reference_symbolic_target(resolved);
} else {
name = git_reference_name(resolved);
}
if (strcmp(name, ref->name))
goto out;
*out = 1;
out:
git_reference_free(resolved);
git_reference_free(head);
return error;
}
int git_refdb_has_log(git_refdb *db, const char *refname)
{
GIT_ASSERT_ARG(db);
GIT_ASSERT_ARG(refname);
return db->backend->has_log(db->backend, refname);
}
int git_refdb_ensure_log(git_refdb *db, const char *refname)
{
GIT_ASSERT_ARG(db);
GIT_ASSERT_ARG(refname);
return db->backend->ensure_log(db->backend, refname);
}
int git_refdb_init_backend(git_refdb_backend *backend, unsigned int version)
{
GIT_INIT_STRUCTURE_FROM_TEMPLATE(
backend, version, git_refdb_backend, GIT_REFDB_BACKEND_INIT);
return 0;
}
int git_refdb_lock(void **payload, git_refdb *db, const char *refname)
{
GIT_ASSERT_ARG(payload);
GIT_ASSERT_ARG(db);
GIT_ASSERT_ARG(refname);
if (!db->backend->lock) {
git_error_set(GIT_ERROR_REFERENCE, "backend does not support locking");
return -1;
}
return db->backend->lock(payload, db->backend, refname);
}
int git_refdb_unlock(git_refdb *db, void *payload, int success, int update_reflog, const git_reference *ref, const git_signature *sig, const char *message)
{
GIT_ASSERT_ARG(db);
return db->backend->unlock(db->backend, payload, success, update_reflog, ref, sig, message);
}
|
0 |
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2
|
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2/src/zstream.c
|
/*
* Copyright (C) the libgit2 contributors. All rights reserved.
*
* This file is part of libgit2, distributed under the GNU GPL v2 with
* a Linking Exception. For full terms see the included COPYING file.
*/
#include "zstream.h"
#include <zlib.h>
#include "buffer.h"
#define ZSTREAM_BUFFER_SIZE (1024 * 1024)
#define ZSTREAM_BUFFER_MIN_EXTRA 8
GIT_INLINE(int) zstream_seterr(git_zstream *zs)
{
switch (zs->zerr) {
case Z_OK:
case Z_STREAM_END:
case Z_BUF_ERROR: /* not fatal; we retry with a larger buffer */
return 0;
case Z_MEM_ERROR:
git_error_set_oom();
break;
default:
if (zs->z.msg)
git_error_set_str(GIT_ERROR_ZLIB, zs->z.msg);
else
git_error_set(GIT_ERROR_ZLIB, "unknown compression error");
}
return -1;
}
int git_zstream_init(git_zstream *zstream, git_zstream_t type)
{
zstream->type = type;
if (zstream->type == GIT_ZSTREAM_INFLATE)
zstream->zerr = inflateInit(&zstream->z);
else
zstream->zerr = deflateInit(&zstream->z, Z_DEFAULT_COMPRESSION);
return zstream_seterr(zstream);
}
void git_zstream_free(git_zstream *zstream)
{
if (zstream->type == GIT_ZSTREAM_INFLATE)
inflateEnd(&zstream->z);
else
deflateEnd(&zstream->z);
}
void git_zstream_reset(git_zstream *zstream)
{
if (zstream->type == GIT_ZSTREAM_INFLATE)
inflateReset(&zstream->z);
else
deflateReset(&zstream->z);
zstream->in = NULL;
zstream->in_len = 0;
zstream->zerr = Z_STREAM_END;
}
int git_zstream_set_input(git_zstream *zstream, const void *in, size_t in_len)
{
zstream->in = in;
zstream->in_len = in_len;
zstream->zerr = Z_OK;
return 0;
}
bool git_zstream_done(git_zstream *zstream)
{
return (!zstream->in_len && zstream->zerr == Z_STREAM_END);
}
bool git_zstream_eos(git_zstream *zstream)
{
return zstream->zerr == Z_STREAM_END;
}
size_t git_zstream_suggest_output_len(git_zstream *zstream)
{
if (zstream->in_len > ZSTREAM_BUFFER_SIZE)
return ZSTREAM_BUFFER_SIZE;
else if (zstream->in_len > ZSTREAM_BUFFER_MIN_EXTRA)
return zstream->in_len;
else
return ZSTREAM_BUFFER_MIN_EXTRA;
}
int git_zstream_get_output_chunk(
void *out, size_t *out_len, git_zstream *zstream)
{
size_t in_queued, in_used, out_queued;
/* set up input data */
zstream->z.next_in = (Bytef *)zstream->in;
/* feed as much data to zlib as it can consume, at most UINT_MAX */
if (zstream->in_len > UINT_MAX) {
zstream->z.avail_in = UINT_MAX;
zstream->flush = Z_NO_FLUSH;
} else {
zstream->z.avail_in = (uInt)zstream->in_len;
zstream->flush = Z_FINISH;
}
in_queued = (size_t)zstream->z.avail_in;
/* set up output data */
zstream->z.next_out = out;
zstream->z.avail_out = (uInt)*out_len;
if ((size_t)zstream->z.avail_out != *out_len)
zstream->z.avail_out = UINT_MAX;
out_queued = (size_t)zstream->z.avail_out;
/* compress next chunk */
if (zstream->type == GIT_ZSTREAM_INFLATE)
zstream->zerr = inflate(&zstream->z, zstream->flush);
else
zstream->zerr = deflate(&zstream->z, zstream->flush);
if (zstream_seterr(zstream))
return -1;
in_used = (in_queued - zstream->z.avail_in);
zstream->in_len -= in_used;
zstream->in += in_used;
*out_len = (out_queued - zstream->z.avail_out);
return 0;
}
int git_zstream_get_output(void *out, size_t *out_len, git_zstream *zstream)
{
size_t out_remain = *out_len;
if (zstream->in_len && zstream->zerr == Z_STREAM_END) {
git_error_set(GIT_ERROR_ZLIB, "zlib input had trailing garbage");
return -1;
}
while (out_remain > 0 && zstream->zerr != Z_STREAM_END) {
size_t out_written = out_remain;
if (git_zstream_get_output_chunk(out, &out_written, zstream) < 0)
return -1;
out_remain -= out_written;
out = ((char *)out) + out_written;
}
/* either we finished the input or we did not flush the data */
GIT_ASSERT(zstream->in_len > 0 || zstream->flush == Z_FINISH);
/* set out_size to number of bytes actually written to output */
*out_len = *out_len - out_remain;
return 0;
}
static int zstream_buf(git_buf *out, const void *in, size_t in_len, git_zstream_t type)
{
git_zstream zs = GIT_ZSTREAM_INIT;
int error = 0;
if ((error = git_zstream_init(&zs, type)) < 0)
return error;
if ((error = git_zstream_set_input(&zs, in, in_len)) < 0)
goto done;
while (!git_zstream_done(&zs)) {
size_t step = git_zstream_suggest_output_len(&zs), written;
if ((error = git_buf_grow_by(out, step)) < 0)
goto done;
written = out->asize - out->size;
if ((error = git_zstream_get_output(
out->ptr + out->size, &written, &zs)) < 0)
goto done;
out->size += written;
}
/* NULL terminate for consistency if possible */
if (out->size < out->asize)
out->ptr[out->size] = '\0';
done:
git_zstream_free(&zs);
return error;
}
int git_zstream_deflatebuf(git_buf *out, const void *in, size_t in_len)
{
return zstream_buf(out, in, in_len, GIT_ZSTREAM_DEFLATE);
}
int git_zstream_inflatebuf(git_buf *out, const void *in, size_t in_len)
{
return zstream_buf(out, in, in_len, GIT_ZSTREAM_INFLATE);
}
|
0 |
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2
|
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2/src/assert_safe.h
|
/*
* Copyright (C) the libgit2 contributors. All rights reserved.
*
* This file is part of libgit2, distributed under the GNU GPL v2 with
* a Linking Exception. For full terms see the included COPYING file.
*/
#ifndef INCLUDE_assert_safe_h__
#define INCLUDE_assert_safe_h__
/*
* In a debug build, we'll assert(3) for aide in debugging. In release
* builds, we will provide macros that will set an error message that
* indicate a failure and return. Note that memory leaks can occur in
* a release-mode assertion failure -- it is impractical to provide
* safe clean up routines in these very extreme failures, but care
* should be taken to not leak very large objects.
*/
#if (defined(_DEBUG) || defined(GIT_ASSERT_HARD)) && GIT_ASSERT_HARD != 0
# include <assert.h>
# define GIT_ASSERT(expr) assert(expr)
# define GIT_ASSERT_ARG(expr) assert(expr)
# define GIT_ASSERT_WITH_RETVAL(expr, fail) assert(expr)
# define GIT_ASSERT_ARG_WITH_RETVAL(expr, fail) assert(expr)
#else
/** Internal consistency check to stop the function. */
# define GIT_ASSERT(expr) GIT_ASSERT_WITH_RETVAL(expr, -1)
/**
* Assert that a consumer-provided argument is valid, setting an
* actionable error message and returning -1 if it is not.
*/
# define GIT_ASSERT_ARG(expr) GIT_ASSERT_ARG_WITH_RETVAL(expr, -1)
/** Internal consistency check to return the `fail` param on failure. */
# define GIT_ASSERT_WITH_RETVAL(expr, fail) \
GIT_ASSERT__WITH_RETVAL(expr, GIT_ERROR_INTERNAL, "unrecoverable internal error", fail)
/**
* Assert that a consumer-provided argument is valid, setting an
* actionable error message and returning the `fail` param if not.
*/
# define GIT_ASSERT_ARG_WITH_RETVAL(expr, fail) \
GIT_ASSERT__WITH_RETVAL(expr, GIT_ERROR_INVALID, "invalid argument", fail)
# define GIT_ASSERT__WITH_RETVAL(expr, code, msg, fail) do { \
if (!(expr)) { \
git_error_set(code, "%s: '%s'", msg, #expr); \
return fail; \
} \
} while(0)
#endif /* GIT_ASSERT_HARD */
#endif
|
0 |
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2
|
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2/src/branch.h
|
/*
* Copyright (C) the libgit2 contributors. All rights reserved.
*
* This file is part of libgit2, distributed under the GNU GPL v2 with
* a Linking Exception. For full terms see the included COPYING file.
*/
#ifndef INCLUDE_branch_h__
#define INCLUDE_branch_h__
#include "common.h"
#include "buffer.h"
int git_branch_upstream__name(
git_buf *tracking_name,
git_repository *repo,
const char *canonical_branch_name);
#endif
|
0 |
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2
|
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2/src/pool.c
|
/*
* Copyright (C) the libgit2 contributors. All rights reserved.
*
* This file is part of libgit2, distributed under the GNU GPL v2 with
* a Linking Exception. For full terms see the included COPYING file.
*/
#include "pool.h"
#include "posix.h"
#ifndef GIT_WIN32
#include <unistd.h>
#endif
struct git_pool_page {
git_pool_page *next;
size_t size;
size_t avail;
GIT_ALIGN(char data[GIT_FLEX_ARRAY], 8);
};
static void *pool_alloc_page(git_pool *pool, size_t size);
#ifndef GIT_DEBUG_POOL
static size_t system_page_size = 0;
int git_pool_global_init(void)
{
if (git__page_size(&system_page_size) < 0)
system_page_size = 4096;
/* allow space for malloc overhead */
system_page_size -= (2 * sizeof(void *)) + sizeof(git_pool_page);
return 0;
}
int git_pool_init(git_pool *pool, size_t item_size)
{
GIT_ASSERT_ARG(pool);
GIT_ASSERT_ARG(item_size >= 1);
memset(pool, 0, sizeof(git_pool));
pool->item_size = item_size;
pool->page_size = system_page_size;
return 0;
}
void git_pool_clear(git_pool *pool)
{
git_pool_page *scan, *next;
for (scan = pool->pages; scan != NULL; scan = next) {
next = scan->next;
git__free(scan);
}
pool->pages = NULL;
}
static void *pool_alloc_page(git_pool *pool, size_t size)
{
git_pool_page *page;
const size_t new_page_size = (size <= pool->page_size) ? pool->page_size : size;
size_t alloc_size;
if (GIT_ADD_SIZET_OVERFLOW(&alloc_size, new_page_size, sizeof(git_pool_page)) ||
!(page = git__malloc(alloc_size)))
return NULL;
page->size = new_page_size;
page->avail = new_page_size - size;
page->next = pool->pages;
pool->pages = page;
return page->data;
}
static void *pool_alloc(git_pool *pool, size_t size)
{
git_pool_page *page = pool->pages;
void *ptr = NULL;
if (!page || page->avail < size)
return pool_alloc_page(pool, size);
ptr = &page->data[page->size - page->avail];
page->avail -= size;
return ptr;
}
uint32_t git_pool__open_pages(git_pool *pool)
{
uint32_t ct = 0;
git_pool_page *scan;
for (scan = pool->pages; scan != NULL; scan = scan->next) ct++;
return ct;
}
bool git_pool__ptr_in_pool(git_pool *pool, void *ptr)
{
git_pool_page *scan;
for (scan = pool->pages; scan != NULL; scan = scan->next)
if ((void *)scan->data <= ptr &&
(void *)(((char *)scan->data) + scan->size) > ptr)
return true;
return false;
}
#else
int git_pool_global_init(void)
{
return 0;
}
static int git_pool__ptr_cmp(const void * a, const void * b)
{
if(a > b) {
return 1;
}
if(a < b) {
return -1;
}
else {
return 0;
}
}
int git_pool_init(git_pool *pool, size_t item_size)
{
GIT_ASSERT_ARG(pool);
GIT_ASSERT_ARG(item_size >= 1);
memset(pool, 0, sizeof(git_pool));
pool->item_size = item_size;
pool->page_size = git_pool__system_page_size();
git_vector_init(&pool->allocations, 100, git_pool__ptr_cmp);
return 0;
}
void git_pool_clear(git_pool *pool)
{
git_vector_free_deep(&pool->allocations);
}
static void *pool_alloc(git_pool *pool, size_t size) {
void *ptr = NULL;
if((ptr = git__malloc(size)) == NULL) {
return NULL;
}
git_vector_insert_sorted(&pool->allocations, ptr, NULL);
return ptr;
}
bool git_pool__ptr_in_pool(git_pool *pool, void *ptr)
{
size_t pos;
return git_vector_bsearch(&pos, &pool->allocations, ptr) != GIT_ENOTFOUND;
}
#endif
void git_pool_swap(git_pool *a, git_pool *b)
{
git_pool temp;
if (a == b)
return;
memcpy(&temp, a, sizeof(temp));
memcpy(a, b, sizeof(temp));
memcpy(b, &temp, sizeof(temp));
}
static size_t alloc_size(git_pool *pool, size_t count)
{
const size_t align = sizeof(void *) - 1;
if (pool->item_size > 1) {
const size_t item_size = (pool->item_size + align) & ~align;
return item_size * count;
}
return (count + align) & ~align;
}
void *git_pool_malloc(git_pool *pool, size_t items)
{
return pool_alloc(pool, alloc_size(pool, items));
}
void *git_pool_mallocz(git_pool *pool, size_t items)
{
const size_t size = alloc_size(pool, items);
void *ptr = pool_alloc(pool, size);
if (ptr)
memset(ptr, 0x0, size);
return ptr;
}
char *git_pool_strndup(git_pool *pool, const char *str, size_t n)
{
char *ptr = NULL;
GIT_ASSERT_ARG_WITH_RETVAL(pool, NULL);
GIT_ASSERT_ARG_WITH_RETVAL(str, NULL);
GIT_ASSERT_ARG_WITH_RETVAL(pool->item_size == sizeof(char), NULL);
if (n == SIZE_MAX)
return NULL;
if ((ptr = git_pool_malloc(pool, (n + 1))) != NULL) {
memcpy(ptr, str, n);
ptr[n] = '\0';
}
return ptr;
}
char *git_pool_strdup(git_pool *pool, const char *str)
{
GIT_ASSERT_ARG_WITH_RETVAL(pool, NULL);
GIT_ASSERT_ARG_WITH_RETVAL(str, NULL);
GIT_ASSERT_ARG_WITH_RETVAL(pool->item_size == sizeof(char), NULL);
return git_pool_strndup(pool, str, strlen(str));
}
char *git_pool_strdup_safe(git_pool *pool, const char *str)
{
return str ? git_pool_strdup(pool, str) : NULL;
}
char *git_pool_strcat(git_pool *pool, const char *a, const char *b)
{
void *ptr;
size_t len_a, len_b, total;
GIT_ASSERT_ARG_WITH_RETVAL(pool, NULL);
GIT_ASSERT_ARG_WITH_RETVAL(pool->item_size == sizeof(char), NULL);
len_a = a ? strlen(a) : 0;
len_b = b ? strlen(b) : 0;
if (GIT_ADD_SIZET_OVERFLOW(&total, len_a, len_b) ||
GIT_ADD_SIZET_OVERFLOW(&total, total, 1))
return NULL;
if ((ptr = git_pool_malloc(pool, total)) != NULL) {
if (len_a)
memcpy(ptr, a, len_a);
if (len_b)
memcpy(((char *)ptr) + len_a, b, len_b);
*(((char *)ptr) + len_a + len_b) = '\0';
}
return ptr;
}
|
0 |
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2
|
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2/src/reader.h
|
/*
* Copyright (C) the libgit2 contributors. All rights reserved.
*
* This file is part of libgit2, distributed under the GNU GPL v2 with
* a Linking Exception. For full terms see the included COPYING file.
*/
#ifndef INCLUDE_reader_h__
#define INCLUDE_reader_h__
#include "common.h"
/* Returned when the workdir does not match the index */
#define GIT_READER_MISMATCH 1
typedef struct git_reader git_reader;
/*
* The `git_reader` structure is a generic interface for reading the
* contents of a file by its name, and implementations are provided
* for reading out of a tree, the index, and the working directory.
*
* Note that the reader implementation is meant to have a short
* lifecycle and does not increase the refcount of the object that
* it's reading. Callers should ensure that they do not use a
* reader after disposing the underlying object that it reads.
*/
struct git_reader {
int (*read)(git_buf *out, git_oid *out_oid, git_filemode_t *mode, git_reader *reader, const char *filename);
};
/**
* Create a `git_reader` that will allow random access to the given
* tree. Paths requested via `git_reader_read` will be rooted at this
* tree, callers are not expected to recurse through tree lookups. Thus,
* you can request to read `/src/foo.c` and the tree provided to this
* function will be searched to find another tree named `src`, which
* will then be opened to find `foo.c`.
*
* @param out The reader for the given tree
* @param tree The tree object to read
* @return 0 on success, or an error code < 0
*/
extern int git_reader_for_tree(
git_reader **out,
git_tree *tree);
/**
* Create a `git_reader` that will allow random access to the given
* index, or the repository's index.
*
* @param out The reader for the given index
* @param repo The repository containing the index
* @param index The index to read, or NULL to use the repository's index
* @return 0 on success, or an error code < 0
*/
extern int git_reader_for_index(
git_reader **out,
git_repository *repo,
git_index *index);
/**
* Create a `git_reader` that will allow random access to the given
* repository's working directory. Note that the contents are read
* in repository format, meaning any workdir -> odb filters are
* applied.
*
* If `validate_index` is set to true, reads of files will hash the
* on-disk contents and ensure that the resulting object ID matches
* the repository's index. This ensures that the working directory
* is unmodified from the index contents.
*
* @param out The reader for the given working directory
* @param repo The repository containing the working directory
* @param validate_index If true, the working directory contents will
* be compared to the index contents during read to ensure that
* the working directory is unmodified.
* @return 0 on success, or an error code < 0
*/
extern int git_reader_for_workdir(
git_reader **out,
git_repository *repo,
bool validate_index);
/**
* Read the given filename from the reader and populate the given buffer
* with the contents and the given oid with the object ID.
*
* @param out The buffer to populate with the file contents
* @param out_id The oid to populate with the object ID
* @param reader The reader to read
* @param filename The filename to read from the reader
*/
extern int git_reader_read(
git_buf *out,
git_oid *out_id,
git_filemode_t *out_filemode,
git_reader *reader,
const char *filename);
/**
* Free the given reader and any associated objects.
*
* @param reader The reader to free
*/
extern void git_reader_free(git_reader *reader);
#endif
|
0 |
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2
|
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2/src/clone.h
|
/*
* Copyright (C) the libgit2 contributors. All rights reserved.
*
* This file is part of libgit2, distributed under the GNU GPL v2 with
* a Linking Exception. For full terms see the included COPYING file.
*/
#ifndef INCLUDE_clone_h__
#define INCLUDE_clone_h__
#include "common.h"
#include "git2/clone.h"
extern int git_clone__submodule(git_repository **out,
const char *url, const char *local_path,
const git_clone_options *_options);
extern int git_clone__should_clone_local(const char *url, git_clone_local_t local);
#endif
|
0 |
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2
|
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2/src/tree.c
|
/*
* Copyright (C) the libgit2 contributors. All rights reserved.
*
* This file is part of libgit2, distributed under the GNU GPL v2 with
* a Linking Exception. For full terms see the included COPYING file.
*/
#include "tree.h"
#include "commit.h"
#include "git2/repository.h"
#include "git2/object.h"
#include "futils.h"
#include "tree-cache.h"
#include "index.h"
#define DEFAULT_TREE_SIZE 16
#define MAX_FILEMODE_BYTES 6
#define TREE_ENTRY_CHECK_NAMELEN(n) \
if (n > UINT16_MAX) { git_error_set(GIT_ERROR_INVALID, "tree entry path too long"); }
static bool valid_filemode(const int filemode)
{
return (filemode == GIT_FILEMODE_TREE
|| filemode == GIT_FILEMODE_BLOB
|| filemode == GIT_FILEMODE_BLOB_EXECUTABLE
|| filemode == GIT_FILEMODE_LINK
|| filemode == GIT_FILEMODE_COMMIT);
}
GIT_INLINE(git_filemode_t) normalize_filemode(git_filemode_t filemode)
{
/* Tree bits set, but it's not a commit */
if (GIT_MODE_TYPE(filemode) == GIT_FILEMODE_TREE)
return GIT_FILEMODE_TREE;
/* If any of the x bits are set */
if (GIT_PERMS_IS_EXEC(filemode))
return GIT_FILEMODE_BLOB_EXECUTABLE;
/* 16XXXX means commit */
if (GIT_MODE_TYPE(filemode) == GIT_FILEMODE_COMMIT)
return GIT_FILEMODE_COMMIT;
/* 12XXXX means symlink */
if (GIT_MODE_TYPE(filemode) == GIT_FILEMODE_LINK)
return GIT_FILEMODE_LINK;
/* Otherwise, return a blob */
return GIT_FILEMODE_BLOB;
}
static int valid_entry_name(git_repository *repo, const char *filename)
{
return *filename != '\0' &&
git_path_validate(repo, filename, 0,
GIT_PATH_REJECT_TRAVERSAL | GIT_PATH_REJECT_DOT_GIT | GIT_PATH_REJECT_SLASH);
}
static int entry_sort_cmp(const void *a, const void *b)
{
const git_tree_entry *e1 = (const git_tree_entry *)a;
const git_tree_entry *e2 = (const git_tree_entry *)b;
return git_path_cmp(
e1->filename, e1->filename_len, git_tree_entry__is_tree(e1),
e2->filename, e2->filename_len, git_tree_entry__is_tree(e2),
git__strncmp);
}
int git_tree_entry_cmp(const git_tree_entry *e1, const git_tree_entry *e2)
{
return entry_sort_cmp(e1, e2);
}
/**
* Allocate a new self-contained entry, with enough space after it to
* store the filename and the id.
*/
static git_tree_entry *alloc_entry(const char *filename, size_t filename_len, const git_oid *id)
{
git_tree_entry *entry = NULL;
size_t tree_len;
TREE_ENTRY_CHECK_NAMELEN(filename_len);
if (GIT_ADD_SIZET_OVERFLOW(&tree_len, sizeof(git_tree_entry), filename_len) ||
GIT_ADD_SIZET_OVERFLOW(&tree_len, tree_len, 1) ||
GIT_ADD_SIZET_OVERFLOW(&tree_len, tree_len, GIT_OID_RAWSZ))
return NULL;
entry = git__calloc(1, tree_len);
if (!entry)
return NULL;
{
char *filename_ptr;
void *id_ptr;
filename_ptr = ((char *) entry) + sizeof(git_tree_entry);
memcpy(filename_ptr, filename, filename_len);
entry->filename = filename_ptr;
id_ptr = filename_ptr + filename_len + 1;
git_oid_cpy(id_ptr, id);
entry->oid = id_ptr;
}
entry->filename_len = (uint16_t)filename_len;
return entry;
}
struct tree_key_search {
const char *filename;
uint16_t filename_len;
};
static int homing_search_cmp(const void *key, const void *array_member)
{
const struct tree_key_search *ksearch = key;
const git_tree_entry *entry = array_member;
const uint16_t len1 = ksearch->filename_len;
const uint16_t len2 = entry->filename_len;
return memcmp(
ksearch->filename,
entry->filename,
len1 < len2 ? len1 : len2
);
}
/*
* Search for an entry in a given tree.
*
* Note that this search is performed in two steps because
* of the way tree entries are sorted internally in git:
*
* Entries in a tree are not sorted alphabetically; two entries
* with the same root prefix will have different positions
* depending on whether they are folders (subtrees) or normal files.
*
* Consequently, it is not possible to find an entry on the tree
* with a binary search if you don't know whether the filename
* you're looking for is a folder or a normal file.
*
* To work around this, we first perform a homing binary search
* on the tree, using the minimal length root prefix of our filename.
* Once the comparisons for this homing search start becoming
* ambiguous because of folder vs file sorting, we look linearly
* around the area for our target file.
*/
static int tree_key_search(
size_t *at_pos,
const git_tree *tree,
const char *filename,
size_t filename_len)
{
struct tree_key_search ksearch;
const git_tree_entry *entry;
size_t homing, i;
TREE_ENTRY_CHECK_NAMELEN(filename_len);
ksearch.filename = filename;
ksearch.filename_len = (uint16_t)filename_len;
/* Initial homing search; find an entry on the tree with
* the same prefix as the filename we're looking for */
if (git_array_search(&homing,
tree->entries, &homing_search_cmp, &ksearch) < 0)
return GIT_ENOTFOUND; /* just a signal error; not passed back to user */
/* We found a common prefix. Look forward as long as
* there are entries that share the common prefix */
for (i = homing; i < tree->entries.size; ++i) {
entry = git_array_get(tree->entries, i);
if (homing_search_cmp(&ksearch, entry) < 0)
break;
if (entry->filename_len == filename_len &&
memcmp(filename, entry->filename, filename_len) == 0) {
if (at_pos)
*at_pos = i;
return 0;
}
}
/* If we haven't found our filename yet, look backwards
* too as long as we have entries with the same prefix */
if (homing > 0) {
i = homing - 1;
do {
entry = git_array_get(tree->entries, i);
if (homing_search_cmp(&ksearch, entry) > 0)
break;
if (entry->filename_len == filename_len &&
memcmp(filename, entry->filename, filename_len) == 0) {
if (at_pos)
*at_pos = i;
return 0;
}
} while (i-- > 0);
}
/* The filename doesn't exist at all */
return GIT_ENOTFOUND;
}
void git_tree_entry_free(git_tree_entry *entry)
{
if (entry == NULL)
return;
git__free(entry);
}
int git_tree_entry_dup(git_tree_entry **dest, const git_tree_entry *source)
{
git_tree_entry *cpy;
GIT_ASSERT_ARG(source);
cpy = alloc_entry(source->filename, source->filename_len, source->oid);
if (cpy == NULL)
return -1;
cpy->attr = source->attr;
*dest = cpy;
return 0;
}
void git_tree__free(void *_tree)
{
git_tree *tree = _tree;
git_odb_object_free(tree->odb_obj);
git_array_clear(tree->entries);
git__free(tree);
}
git_filemode_t git_tree_entry_filemode(const git_tree_entry *entry)
{
return normalize_filemode(entry->attr);
}
git_filemode_t git_tree_entry_filemode_raw(const git_tree_entry *entry)
{
return entry->attr;
}
const char *git_tree_entry_name(const git_tree_entry *entry)
{
GIT_ASSERT_ARG_WITH_RETVAL(entry, NULL);
return entry->filename;
}
const git_oid *git_tree_entry_id(const git_tree_entry *entry)
{
GIT_ASSERT_ARG_WITH_RETVAL(entry, NULL);
return entry->oid;
}
git_object_t git_tree_entry_type(const git_tree_entry *entry)
{
GIT_ASSERT_ARG_WITH_RETVAL(entry, GIT_OBJECT_INVALID);
if (S_ISGITLINK(entry->attr))
return GIT_OBJECT_COMMIT;
else if (S_ISDIR(entry->attr))
return GIT_OBJECT_TREE;
else
return GIT_OBJECT_BLOB;
}
int git_tree_entry_to_object(
git_object **object_out,
git_repository *repo,
const git_tree_entry *entry)
{
GIT_ASSERT_ARG(entry);
GIT_ASSERT_ARG(object_out);
return git_object_lookup(object_out, repo, entry->oid, GIT_OBJECT_ANY);
}
static const git_tree_entry *entry_fromname(
const git_tree *tree, const char *name, size_t name_len)
{
size_t idx;
if (tree_key_search(&idx, tree, name, name_len) < 0)
return NULL;
return git_array_get(tree->entries, idx);
}
const git_tree_entry *git_tree_entry_byname(
const git_tree *tree, const char *filename)
{
GIT_ASSERT_ARG_WITH_RETVAL(tree, NULL);
GIT_ASSERT_ARG_WITH_RETVAL(filename, NULL);
return entry_fromname(tree, filename, strlen(filename));
}
const git_tree_entry *git_tree_entry_byindex(
const git_tree *tree, size_t idx)
{
GIT_ASSERT_ARG_WITH_RETVAL(tree, NULL);
return git_array_get(tree->entries, idx);
}
const git_tree_entry *git_tree_entry_byid(
const git_tree *tree, const git_oid *id)
{
size_t i;
const git_tree_entry *e;
GIT_ASSERT_ARG_WITH_RETVAL(tree, NULL);
git_array_foreach(tree->entries, i, e) {
if (memcmp(&e->oid->id, &id->id, sizeof(id->id)) == 0)
return e;
}
return NULL;
}
size_t git_tree_entrycount(const git_tree *tree)
{
GIT_ASSERT_ARG_WITH_RETVAL(tree, 0);
return tree->entries.size;
}
size_t git_treebuilder_entrycount(git_treebuilder *bld)
{
GIT_ASSERT_ARG_WITH_RETVAL(bld, 0);
return git_strmap_size(bld->map);
}
static int tree_error(const char *str, const char *path)
{
if (path)
git_error_set(GIT_ERROR_TREE, "%s - %s", str, path);
else
git_error_set(GIT_ERROR_TREE, "%s", str);
return -1;
}
static int parse_mode(uint16_t *mode_out, const char *buffer, size_t buffer_len, const char **buffer_out)
{
int32_t mode;
int error;
if (!buffer_len || git__isspace(*buffer))
return -1;
if ((error = git__strntol32(&mode, buffer, buffer_len, buffer_out, 8)) < 0)
return error;
if (mode < 0 || mode > UINT16_MAX)
return -1;
*mode_out = mode;
return 0;
}
int git_tree__parse_raw(void *_tree, const char *data, size_t size)
{
git_tree *tree = _tree;
const char *buffer;
const char *buffer_end;
buffer = data;
buffer_end = buffer + size;
tree->odb_obj = NULL;
git_array_init_to_size(tree->entries, DEFAULT_TREE_SIZE);
GIT_ERROR_CHECK_ARRAY(tree->entries);
while (buffer < buffer_end) {
git_tree_entry *entry;
size_t filename_len;
const char *nul;
uint16_t attr;
if (parse_mode(&attr, buffer, buffer_end - buffer, &buffer) < 0 || !buffer)
return tree_error("failed to parse tree: can't parse filemode", NULL);
if (buffer >= buffer_end || (*buffer++) != ' ')
return tree_error("failed to parse tree: missing space after filemode", NULL);
if ((nul = memchr(buffer, 0, buffer_end - buffer)) == NULL)
return tree_error("failed to parse tree: object is corrupted", NULL);
if ((filename_len = nul - buffer) == 0 || filename_len > UINT16_MAX)
return tree_error("failed to parse tree: can't parse filename", NULL);
if ((buffer_end - (nul + 1)) < GIT_OID_RAWSZ)
return tree_error("failed to parse tree: can't parse OID", NULL);
/* Allocate the entry */
{
entry = git_array_alloc(tree->entries);
GIT_ERROR_CHECK_ALLOC(entry);
entry->attr = attr;
entry->filename_len = (uint16_t)filename_len;
entry->filename = buffer;
entry->oid = (git_oid *) ((char *) buffer + filename_len + 1);
}
buffer += filename_len + 1;
buffer += GIT_OID_RAWSZ;
}
return 0;
}
int git_tree__parse(void *_tree, git_odb_object *odb_obj)
{
git_tree *tree = _tree;
if ((git_tree__parse_raw(tree,
git_odb_object_data(odb_obj),
git_odb_object_size(odb_obj))) < 0)
return -1;
if (git_odb_object_dup(&tree->odb_obj, odb_obj) < 0)
return -1;
return 0;
}
static size_t find_next_dir(const char *dirname, git_index *index, size_t start)
{
size_t dirlen, i, entries = git_index_entrycount(index);
dirlen = strlen(dirname);
for (i = start; i < entries; ++i) {
const git_index_entry *entry = git_index_get_byindex(index, i);
if (strlen(entry->path) < dirlen ||
memcmp(entry->path, dirname, dirlen) ||
(dirlen > 0 && entry->path[dirlen] != '/')) {
break;
}
}
return i;
}
static git_object_t otype_from_mode(git_filemode_t filemode)
{
switch (filemode) {
case GIT_FILEMODE_TREE:
return GIT_OBJECT_TREE;
case GIT_FILEMODE_COMMIT:
return GIT_OBJECT_COMMIT;
default:
return GIT_OBJECT_BLOB;
}
}
static int check_entry(git_repository *repo, const char *filename, const git_oid *id, git_filemode_t filemode)
{
if (!valid_filemode(filemode))
return tree_error("failed to insert entry: invalid filemode for file", filename);
if (!valid_entry_name(repo, filename))
return tree_error("failed to insert entry: invalid name for a tree entry", filename);
if (git_oid_is_zero(id))
return tree_error("failed to insert entry: invalid null OID", filename);
if (filemode != GIT_FILEMODE_COMMIT &&
!git_object__is_valid(repo, id, otype_from_mode(filemode)))
return tree_error("failed to insert entry: invalid object specified", filename);
return 0;
}
static int git_treebuilder__write_with_buffer(
git_oid *oid,
git_treebuilder *bld,
git_buf *buf)
{
int error = 0;
size_t i, entrycount;
git_odb *odb;
git_tree_entry *entry;
git_vector entries = GIT_VECTOR_INIT;
git_buf_clear(buf);
entrycount = git_strmap_size(bld->map);
if ((error = git_vector_init(&entries, entrycount, entry_sort_cmp)) < 0)
goto out;
if (buf->asize == 0 &&
(error = git_buf_grow(buf, entrycount * 72)) < 0)
goto out;
git_strmap_foreach_value(bld->map, entry, {
if ((error = git_vector_insert(&entries, entry)) < 0)
goto out;
});
git_vector_sort(&entries);
for (i = 0; i < entries.length && !error; ++i) {
entry = git_vector_get(&entries, i);
git_buf_printf(buf, "%o ", entry->attr);
git_buf_put(buf, entry->filename, entry->filename_len + 1);
git_buf_put(buf, (char *)entry->oid->id, GIT_OID_RAWSZ);
if (git_buf_oom(buf)) {
error = -1;
goto out;
}
}
if ((error = git_repository_odb__weakptr(&odb, bld->repo)) == 0)
error = git_odb_write(oid, odb, buf->ptr, buf->size, GIT_OBJECT_TREE);
out:
git_vector_free(&entries);
return error;
}
static int append_entry(
git_treebuilder *bld,
const char *filename,
const git_oid *id,
git_filemode_t filemode,
bool validate)
{
git_tree_entry *entry;
int error = 0;
if (validate && ((error = check_entry(bld->repo, filename, id, filemode)) < 0))
return error;
entry = alloc_entry(filename, strlen(filename), id);
GIT_ERROR_CHECK_ALLOC(entry);
entry->attr = (uint16_t)filemode;
if ((error = git_strmap_set(bld->map, entry->filename, entry)) < 0) {
git_tree_entry_free(entry);
git_error_set(GIT_ERROR_TREE, "failed to append entry %s to the tree builder", filename);
return -1;
}
return 0;
}
static int write_tree(
git_oid *oid,
git_repository *repo,
git_index *index,
const char *dirname,
size_t start,
git_buf *shared_buf)
{
git_treebuilder *bld = NULL;
size_t i, entries = git_index_entrycount(index);
int error;
size_t dirname_len = strlen(dirname);
const git_tree_cache *cache;
cache = git_tree_cache_get(index->tree, dirname);
if (cache != NULL && cache->entry_count >= 0){
git_oid_cpy(oid, &cache->oid);
return (int)find_next_dir(dirname, index, start);
}
if ((error = git_treebuilder_new(&bld, repo, NULL)) < 0 || bld == NULL)
return -1;
/*
* This loop is unfortunate, but necessary. The index doesn't have
* any directores, so we need to handle that manually, and we
* need to keep track of the current position.
*/
for (i = start; i < entries; ++i) {
const git_index_entry *entry = git_index_get_byindex(index, i);
const char *filename, *next_slash;
/*
* If we've left our (sub)tree, exit the loop and return. The
* first check is an early out (and security for the
* third). The second check is a simple prefix comparison. The
* third check catches situations where there is a directory
* win32/sys and a file win32mmap.c. Without it, the following
* code believes there is a file win32/mmap.c
*/
if (strlen(entry->path) < dirname_len ||
memcmp(entry->path, dirname, dirname_len) ||
(dirname_len > 0 && entry->path[dirname_len] != '/')) {
break;
}
filename = entry->path + dirname_len;
if (*filename == '/')
filename++;
next_slash = strchr(filename, '/');
if (next_slash) {
git_oid sub_oid;
int written;
char *subdir, *last_comp;
subdir = git__strndup(entry->path, next_slash - entry->path);
GIT_ERROR_CHECK_ALLOC(subdir);
/* Write out the subtree */
written = write_tree(&sub_oid, repo, index, subdir, i, shared_buf);
if (written < 0) {
git__free(subdir);
goto on_error;
} else {
i = written - 1; /* -1 because of the loop increment */
}
/*
* We need to figure out what we want toinsert
* into this tree. If we're traversing
* deps/zlib/, then we only want to write
* 'zlib' into the tree.
*/
last_comp = strrchr(subdir, '/');
if (last_comp) {
last_comp++; /* Get rid of the '/' */
} else {
last_comp = subdir;
}
error = append_entry(bld, last_comp, &sub_oid, S_IFDIR, true);
git__free(subdir);
if (error < 0)
goto on_error;
} else {
error = append_entry(bld, filename, &entry->id, entry->mode, true);
if (error < 0)
goto on_error;
}
}
if (git_treebuilder__write_with_buffer(oid, bld, shared_buf) < 0)
goto on_error;
git_treebuilder_free(bld);
return (int)i;
on_error:
git_treebuilder_free(bld);
return -1;
}
int git_tree__write_index(
git_oid *oid, git_index *index, git_repository *repo)
{
int ret;
git_tree *tree;
git_buf shared_buf = GIT_BUF_INIT;
bool old_ignore_case = false;
GIT_ASSERT_ARG(oid);
GIT_ASSERT_ARG(index);
GIT_ASSERT_ARG(repo);
if (git_index_has_conflicts(index)) {
git_error_set(GIT_ERROR_INDEX,
"cannot create a tree from a not fully merged index.");
return GIT_EUNMERGED;
}
if (index->tree != NULL && index->tree->entry_count >= 0) {
git_oid_cpy(oid, &index->tree->oid);
return 0;
}
/* The tree cache didn't help us; we'll have to write
* out a tree. If the index is ignore_case, we must
* make it case-sensitive for the duration of the tree-write
* operation. */
if (index->ignore_case) {
old_ignore_case = true;
git_index__set_ignore_case(index, false);
}
ret = write_tree(oid, repo, index, "", 0, &shared_buf);
git_buf_dispose(&shared_buf);
if (old_ignore_case)
git_index__set_ignore_case(index, true);
index->tree = NULL;
if (ret < 0)
return ret;
git_pool_clear(&index->tree_pool);
if ((ret = git_tree_lookup(&tree, repo, oid)) < 0)
return ret;
/* Read the tree cache into the index */
ret = git_tree_cache_read_tree(&index->tree, tree, &index->tree_pool);
git_tree_free(tree);
return ret;
}
int git_treebuilder_new(
git_treebuilder **builder_p,
git_repository *repo,
const git_tree *source)
{
git_treebuilder *bld;
size_t i;
GIT_ASSERT_ARG(builder_p);
GIT_ASSERT_ARG(repo);
bld = git__calloc(1, sizeof(git_treebuilder));
GIT_ERROR_CHECK_ALLOC(bld);
bld->repo = repo;
if (git_strmap_new(&bld->map) < 0) {
git__free(bld);
return -1;
}
if (source != NULL) {
git_tree_entry *entry_src;
git_array_foreach(source->entries, i, entry_src) {
if (append_entry(
bld, entry_src->filename,
entry_src->oid,
entry_src->attr,
false) < 0)
goto on_error;
}
}
*builder_p = bld;
return 0;
on_error:
git_treebuilder_free(bld);
return -1;
}
int git_treebuilder_insert(
const git_tree_entry **entry_out,
git_treebuilder *bld,
const char *filename,
const git_oid *id,
git_filemode_t filemode)
{
git_tree_entry *entry;
int error;
GIT_ASSERT_ARG(bld);
GIT_ASSERT_ARG(id);
GIT_ASSERT_ARG(filename);
if ((error = check_entry(bld->repo, filename, id, filemode)) < 0)
return error;
if ((entry = git_strmap_get(bld->map, filename)) != NULL) {
git_oid_cpy((git_oid *) entry->oid, id);
} else {
entry = alloc_entry(filename, strlen(filename), id);
GIT_ERROR_CHECK_ALLOC(entry);
if ((error = git_strmap_set(bld->map, entry->filename, entry)) < 0) {
git_tree_entry_free(entry);
git_error_set(GIT_ERROR_TREE, "failed to insert %s", filename);
return -1;
}
}
entry->attr = filemode;
if (entry_out)
*entry_out = entry;
return 0;
}
static git_tree_entry *treebuilder_get(git_treebuilder *bld, const char *filename)
{
GIT_ASSERT_ARG_WITH_RETVAL(bld, NULL);
GIT_ASSERT_ARG_WITH_RETVAL(filename, NULL);
return git_strmap_get(bld->map, filename);
}
const git_tree_entry *git_treebuilder_get(git_treebuilder *bld, const char *filename)
{
return treebuilder_get(bld, filename);
}
int git_treebuilder_remove(git_treebuilder *bld, const char *filename)
{
git_tree_entry *entry = treebuilder_get(bld, filename);
if (entry == NULL)
return tree_error("failed to remove entry: file isn't in the tree", filename);
git_strmap_delete(bld->map, filename);
git_tree_entry_free(entry);
return 0;
}
int git_treebuilder_write(git_oid *oid, git_treebuilder *bld)
{
GIT_ASSERT_ARG(oid);
GIT_ASSERT_ARG(bld);
return git_treebuilder__write_with_buffer(oid, bld, &bld->write_cache);
}
int git_treebuilder_filter(
git_treebuilder *bld,
git_treebuilder_filter_cb filter,
void *payload)
{
const char *filename;
git_tree_entry *entry;
GIT_ASSERT_ARG(bld);
GIT_ASSERT_ARG(filter);
git_strmap_foreach(bld->map, filename, entry, {
if (filter(entry, payload)) {
git_strmap_delete(bld->map, filename);
git_tree_entry_free(entry);
}
});
return 0;
}
int git_treebuilder_clear(git_treebuilder *bld)
{
git_tree_entry *e;
GIT_ASSERT_ARG(bld);
git_strmap_foreach_value(bld->map, e, git_tree_entry_free(e));
git_strmap_clear(bld->map);
return 0;
}
void git_treebuilder_free(git_treebuilder *bld)
{
if (bld == NULL)
return;
git_buf_dispose(&bld->write_cache);
git_treebuilder_clear(bld);
git_strmap_free(bld->map);
git__free(bld);
}
static size_t subpath_len(const char *path)
{
const char *slash_pos = strchr(path, '/');
if (slash_pos == NULL)
return strlen(path);
return slash_pos - path;
}
int git_tree_entry_bypath(
git_tree_entry **entry_out,
const git_tree *root,
const char *path)
{
int error = 0;
git_tree *subtree;
const git_tree_entry *entry;
size_t filename_len;
/* Find how long is the current path component (i.e.
* the filename between two slashes */
filename_len = subpath_len(path);
if (filename_len == 0) {
git_error_set(GIT_ERROR_TREE, "invalid tree path given");
return GIT_ENOTFOUND;
}
entry = entry_fromname(root, path, filename_len);
if (entry == NULL) {
git_error_set(GIT_ERROR_TREE,
"the path '%.*s' does not exist in the given tree", (int) filename_len, path);
return GIT_ENOTFOUND;
}
switch (path[filename_len]) {
case '/':
/* If there are more components in the path...
* then this entry *must* be a tree */
if (!git_tree_entry__is_tree(entry)) {
git_error_set(GIT_ERROR_TREE,
"the path '%.*s' exists but is not a tree", (int) filename_len, path);
return GIT_ENOTFOUND;
}
/* If there's only a slash left in the path, we
* return the current entry; otherwise, we keep
* walking down the path */
if (path[filename_len + 1] != '\0')
break;
/* fall through */
case '\0':
/* If there are no more components in the path, return
* this entry */
return git_tree_entry_dup(entry_out, entry);
}
if (git_tree_lookup(&subtree, root->object.repo, entry->oid) < 0)
return -1;
error = git_tree_entry_bypath(
entry_out,
subtree,
path + filename_len + 1
);
git_tree_free(subtree);
return error;
}
static int tree_walk(
const git_tree *tree,
git_treewalk_cb callback,
git_buf *path,
void *payload,
bool preorder)
{
int error = 0;
size_t i;
const git_tree_entry *entry;
git_array_foreach(tree->entries, i, entry) {
if (preorder) {
error = callback(path->ptr, entry, payload);
if (error < 0) { /* negative value stops iteration */
git_error_set_after_callback_function(error, "git_tree_walk");
break;
}
if (error > 0) { /* positive value skips this entry */
error = 0;
continue;
}
}
if (git_tree_entry__is_tree(entry)) {
git_tree *subtree;
size_t path_len = git_buf_len(path);
error = git_tree_lookup(&subtree, tree->object.repo, entry->oid);
if (error < 0)
break;
/* append the next entry to the path */
git_buf_puts(path, entry->filename);
git_buf_putc(path, '/');
if (git_buf_oom(path))
error = -1;
else
error = tree_walk(subtree, callback, path, payload, preorder);
git_tree_free(subtree);
if (error != 0)
break;
git_buf_truncate(path, path_len);
}
if (!preorder) {
error = callback(path->ptr, entry, payload);
if (error < 0) { /* negative value stops iteration */
git_error_set_after_callback_function(error, "git_tree_walk");
break;
}
error = 0;
}
}
return error;
}
int git_tree_walk(
const git_tree *tree,
git_treewalk_mode mode,
git_treewalk_cb callback,
void *payload)
{
int error = 0;
git_buf root_path = GIT_BUF_INIT;
if (mode != GIT_TREEWALK_POST && mode != GIT_TREEWALK_PRE) {
git_error_set(GIT_ERROR_INVALID, "invalid walking mode for tree walk");
return -1;
}
error = tree_walk(
tree, callback, &root_path, payload, (mode == GIT_TREEWALK_PRE));
git_buf_dispose(&root_path);
return error;
}
static int compare_entries(const void *_a, const void *_b)
{
const git_tree_update *a = (git_tree_update *) _a;
const git_tree_update *b = (git_tree_update *) _b;
return strcmp(a->path, b->path);
}
static int on_dup_entry(void **old, void *new)
{
GIT_UNUSED(old); GIT_UNUSED(new);
git_error_set(GIT_ERROR_TREE, "duplicate entries given for update");
return -1;
}
/*
* We keep the previous tree and the new one at each level of the
* stack. When we leave a level we're done with that tree and we can
* write it out to the odb.
*/
typedef struct {
git_treebuilder *bld;
git_tree *tree;
char *name;
} tree_stack_entry;
/** Count how many slashes (i.e. path components) there are in this string */
GIT_INLINE(size_t) count_slashes(const char *path)
{
size_t count = 0;
const char *slash;
while ((slash = strchr(path, '/')) != NULL) {
count++;
path = slash + 1;
}
return count;
}
static bool next_component(git_buf *out, const char *in)
{
const char *slash = strchr(in, '/');
git_buf_clear(out);
if (slash)
git_buf_put(out, in, slash - in);
return !!slash;
}
static int create_popped_tree(tree_stack_entry *current, tree_stack_entry *popped, git_buf *component)
{
int error;
git_oid new_tree;
git_tree_free(popped->tree);
/* If the tree would be empty, remove it from the one higher up */
if (git_treebuilder_entrycount(popped->bld) == 0) {
git_treebuilder_free(popped->bld);
error = git_treebuilder_remove(current->bld, popped->name);
git__free(popped->name);
return error;
}
error = git_treebuilder_write(&new_tree, popped->bld);
git_treebuilder_free(popped->bld);
if (error < 0) {
git__free(popped->name);
return error;
}
/* We've written out the tree, now we have to put the new value into its parent */
git_buf_clear(component);
git_buf_puts(component, popped->name);
git__free(popped->name);
GIT_ERROR_CHECK_ALLOC(component->ptr);
/* Error out if this would create a D/F conflict in this update */
if (current->tree) {
const git_tree_entry *to_replace;
to_replace = git_tree_entry_byname(current->tree, component->ptr);
if (to_replace && git_tree_entry_type(to_replace) != GIT_OBJECT_TREE) {
git_error_set(GIT_ERROR_TREE, "D/F conflict when updating tree");
return -1;
}
}
return git_treebuilder_insert(NULL, current->bld, component->ptr, &new_tree, GIT_FILEMODE_TREE);
}
int git_tree_create_updated(git_oid *out, git_repository *repo, git_tree *baseline, size_t nupdates, const git_tree_update *updates)
{
git_array_t(tree_stack_entry) stack = GIT_ARRAY_INIT;
tree_stack_entry *root_elem;
git_vector entries;
int error;
size_t i;
git_buf component = GIT_BUF_INIT;
if ((error = git_vector_init(&entries, nupdates, compare_entries)) < 0)
return error;
/* Sort the entries for treversal */
for (i = 0 ; i < nupdates; i++) {
if ((error = git_vector_insert_sorted(&entries, (void *) &updates[i], on_dup_entry)) < 0)
goto cleanup;
}
root_elem = git_array_alloc(stack);
GIT_ERROR_CHECK_ALLOC(root_elem);
memset(root_elem, 0, sizeof(*root_elem));
if (baseline && (error = git_tree_dup(&root_elem->tree, baseline)) < 0)
goto cleanup;
if ((error = git_treebuilder_new(&root_elem->bld, repo, root_elem->tree)) < 0)
goto cleanup;
for (i = 0; i < nupdates; i++) {
const git_tree_update *last_update = i == 0 ? NULL : git_vector_get(&entries, i-1);
const git_tree_update *update = git_vector_get(&entries, i);
size_t common_prefix = 0, steps_up, j;
const char *path;
/* Figure out how much we need to change from the previous tree */
if (last_update)
common_prefix = git_path_common_dirlen(last_update->path, update->path);
/*
* The entries are sorted, so when we find we're no
* longer in the same directory, we need to abandon
* the old tree (steps up) and dive down to the next
* one.
*/
steps_up = last_update == NULL ? 0 : count_slashes(&last_update->path[common_prefix]);
for (j = 0; j < steps_up; j++) {
tree_stack_entry *current, *popped = git_array_pop(stack);
GIT_ASSERT(popped);
current = git_array_last(stack);
GIT_ASSERT(current);
if ((error = create_popped_tree(current, popped, &component)) < 0)
goto cleanup;
}
/* Now that we've created the trees we popped from the stack, let's go back down */
path = &update->path[common_prefix];
while (next_component(&component, path)) {
tree_stack_entry *last, *new_entry;
const git_tree_entry *entry;
last = git_array_last(stack);
entry = last->tree ? git_tree_entry_byname(last->tree, component.ptr) : NULL;
if (!entry)
entry = treebuilder_get(last->bld, component.ptr);
if (entry && git_tree_entry_type(entry) != GIT_OBJECT_TREE) {
git_error_set(GIT_ERROR_TREE, "D/F conflict when updating tree");
error = -1;
goto cleanup;
}
new_entry = git_array_alloc(stack);
GIT_ERROR_CHECK_ALLOC(new_entry);
memset(new_entry, 0, sizeof(*new_entry));
new_entry->tree = NULL;
if (entry && (error = git_tree_lookup(&new_entry->tree, repo, git_tree_entry_id(entry))) < 0)
goto cleanup;
if ((error = git_treebuilder_new(&new_entry->bld, repo, new_entry->tree)) < 0)
goto cleanup;
new_entry->name = git__strdup(component.ptr);
GIT_ERROR_CHECK_ALLOC(new_entry->name);
/* Get to the start of the next component */
path += component.size + 1;
}
/* After all that, we're finally at the place where we want to perform the update */
switch (update->action) {
case GIT_TREE_UPDATE_UPSERT:
{
/* Make sure we're replacing something of the same type */
tree_stack_entry *last = git_array_last(stack);
char *basename = git_path_basename(update->path);
const git_tree_entry *e = git_treebuilder_get(last->bld, basename);
if (e && git_tree_entry_type(e) != git_object__type_from_filemode(update->filemode)) {
git__free(basename);
git_error_set(GIT_ERROR_TREE, "cannot replace '%s' with '%s' at '%s'",
git_object_type2string(git_tree_entry_type(e)),
git_object_type2string(git_object__type_from_filemode(update->filemode)),
update->path);
error = -1;
goto cleanup;
}
error = git_treebuilder_insert(NULL, last->bld, basename, &update->id, update->filemode);
git__free(basename);
break;
}
case GIT_TREE_UPDATE_REMOVE:
{
tree_stack_entry *last = git_array_last(stack);
char *basename = git_path_basename(update->path);
error = git_treebuilder_remove(last->bld, basename);
git__free(basename);
break;
}
default:
git_error_set(GIT_ERROR_TREE, "unknown action for update");
error = -1;
goto cleanup;
}
if (error < 0)
goto cleanup;
}
/* We're done, go up the stack again and write out the tree */
{
tree_stack_entry *current = NULL, *popped = NULL;
while ((popped = git_array_pop(stack)) != NULL) {
current = git_array_last(stack);
/* We've reached the top, current is the root tree */
if (!current)
break;
if ((error = create_popped_tree(current, popped, &component)) < 0)
goto cleanup;
}
/* Write out the root tree */
git__free(popped->name);
git_tree_free(popped->tree);
error = git_treebuilder_write(out, popped->bld);
git_treebuilder_free(popped->bld);
if (error < 0)
goto cleanup;
}
cleanup:
{
tree_stack_entry *e;
while ((e = git_array_pop(stack)) != NULL) {
git_treebuilder_free(e->bld);
git_tree_free(e->tree);
git__free(e->name);
}
}
git_buf_dispose(&component);
git_array_clear(stack);
git_vector_free(&entries);
return error;
}
/* Deprecated Functions */
#ifndef GIT_DEPRECATE_HARD
int git_treebuilder_write_with_buffer(git_oid *oid, git_treebuilder *bld, git_buf *buf)
{
GIT_UNUSED(buf);
return git_treebuilder_write(oid, bld);
}
#endif
|
0 |
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2
|
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2/src/hashsig.c
|
/*
* Copyright (C) the libgit2 contributors. All rights reserved.
*
* This file is part of libgit2, distributed under the GNU GPL v2 with
* a Linking Exception. For full terms see the included COPYING file.
*/
#include "common.h"
#include "git2/sys/hashsig.h"
#include "futils.h"
#include "util.h"
typedef uint32_t hashsig_t;
typedef uint64_t hashsig_state;
#define HASHSIG_SCALE 100
#define HASHSIG_MAX_RUN 80
#define HASHSIG_HASH_START INT64_C(0x012345678ABCDEF0)
#define HASHSIG_HASH_SHIFT 5
#define HASHSIG_HASH_MIX(S,CH) \
(S) = ((S) << HASHSIG_HASH_SHIFT) - (S) + (hashsig_state)(CH)
#define HASHSIG_HEAP_SIZE ((1 << 7) - 1)
#define HASHSIG_HEAP_MIN_SIZE 4
typedef int (*hashsig_cmp)(const void *a, const void *b, void *);
typedef struct {
int size, asize;
hashsig_cmp cmp;
hashsig_t values[HASHSIG_HEAP_SIZE];
} hashsig_heap;
struct git_hashsig {
hashsig_heap mins;
hashsig_heap maxs;
size_t lines;
git_hashsig_option_t opt;
};
#define HEAP_LCHILD_OF(I) (((I)<<1)+1)
#define HEAP_RCHILD_OF(I) (((I)<<1)+2)
#define HEAP_PARENT_OF(I) (((I)-1)>>1)
static void hashsig_heap_init(hashsig_heap *h, hashsig_cmp cmp)
{
h->size = 0;
h->asize = HASHSIG_HEAP_SIZE;
h->cmp = cmp;
}
static int hashsig_cmp_max(const void *a, const void *b, void *payload)
{
hashsig_t av = *(const hashsig_t *)a, bv = *(const hashsig_t *)b;
GIT_UNUSED(payload);
return (av < bv) ? -1 : (av > bv) ? 1 : 0;
}
static int hashsig_cmp_min(const void *a, const void *b, void *payload)
{
hashsig_t av = *(const hashsig_t *)a, bv = *(const hashsig_t *)b;
GIT_UNUSED(payload);
return (av > bv) ? -1 : (av < bv) ? 1 : 0;
}
static void hashsig_heap_up(hashsig_heap *h, int el)
{
int parent_el = HEAP_PARENT_OF(el);
while (el > 0 && h->cmp(&h->values[parent_el], &h->values[el], NULL) > 0) {
hashsig_t t = h->values[el];
h->values[el] = h->values[parent_el];
h->values[parent_el] = t;
el = parent_el;
parent_el = HEAP_PARENT_OF(el);
}
}
static void hashsig_heap_down(hashsig_heap *h, int el)
{
hashsig_t v, lv, rv;
/* 'el < h->size / 2' tests if el is bottom row of heap */
while (el < h->size / 2) {
int lel = HEAP_LCHILD_OF(el), rel = HEAP_RCHILD_OF(el), swapel;
v = h->values[el];
lv = h->values[lel];
rv = h->values[rel];
if (h->cmp(&v, &lv, NULL) < 0 && h->cmp(&v, &rv, NULL) < 0)
break;
swapel = (h->cmp(&lv, &rv, NULL) < 0) ? lel : rel;
h->values[el] = h->values[swapel];
h->values[swapel] = v;
el = swapel;
}
}
static void hashsig_heap_sort(hashsig_heap *h)
{
/* only need to do this at the end for signature comparison */
git__qsort_r(h->values, h->size, sizeof(hashsig_t), h->cmp, NULL);
}
static void hashsig_heap_insert(hashsig_heap *h, hashsig_t val)
{
/* if heap is not full, insert new element */
if (h->size < h->asize) {
h->values[h->size++] = val;
hashsig_heap_up(h, h->size - 1);
}
/* if heap is full, pop top if new element should replace it */
else if (h->cmp(&val, &h->values[0], NULL) > 0) {
h->size--;
h->values[0] = h->values[h->size];
hashsig_heap_down(h, 0);
}
}
typedef struct {
int use_ignores;
uint8_t ignore_ch[256];
} hashsig_in_progress;
static int hashsig_in_progress_init(
hashsig_in_progress *prog, git_hashsig *sig)
{
int i;
/* no more than one can be set */
GIT_ASSERT(!(sig->opt & GIT_HASHSIG_IGNORE_WHITESPACE) ||
!(sig->opt & GIT_HASHSIG_SMART_WHITESPACE));
if (sig->opt & GIT_HASHSIG_IGNORE_WHITESPACE) {
for (i = 0; i < 256; ++i)
prog->ignore_ch[i] = git__isspace_nonlf(i);
prog->use_ignores = 1;
} else if (sig->opt & GIT_HASHSIG_SMART_WHITESPACE) {
for (i = 0; i < 256; ++i)
prog->ignore_ch[i] = git__isspace(i);
prog->use_ignores = 1;
} else {
memset(prog, 0, sizeof(*prog));
}
return 0;
}
static int hashsig_add_hashes(
git_hashsig *sig,
const uint8_t *data,
size_t size,
hashsig_in_progress *prog)
{
const uint8_t *scan = data, *end = data + size;
hashsig_state state = HASHSIG_HASH_START;
int use_ignores = prog->use_ignores, len;
uint8_t ch;
while (scan < end) {
state = HASHSIG_HASH_START;
for (len = 0; scan < end && len < HASHSIG_MAX_RUN; ) {
ch = *scan;
if (use_ignores)
for (; scan < end && git__isspace_nonlf(ch); ch = *scan)
++scan;
else if (sig->opt &
(GIT_HASHSIG_IGNORE_WHITESPACE | GIT_HASHSIG_SMART_WHITESPACE))
for (; scan < end && ch == '\r'; ch = *scan)
++scan;
/* peek at next character to decide what to do next */
if (sig->opt & GIT_HASHSIG_SMART_WHITESPACE)
use_ignores = (ch == '\n');
if (scan >= end)
break;
++scan;
/* check run terminator */
if (ch == '\n' || ch == '\0') {
sig->lines++;
break;
}
++len;
HASHSIG_HASH_MIX(state, ch);
}
if (len > 0) {
hashsig_heap_insert(&sig->mins, (hashsig_t)state);
hashsig_heap_insert(&sig->maxs, (hashsig_t)state);
while (scan < end && (*scan == '\n' || !*scan))
++scan;
}
}
prog->use_ignores = use_ignores;
return 0;
}
static int hashsig_finalize_hashes(git_hashsig *sig)
{
if (sig->mins.size < HASHSIG_HEAP_MIN_SIZE &&
!(sig->opt & GIT_HASHSIG_ALLOW_SMALL_FILES)) {
git_error_set(GIT_ERROR_INVALID,
"file too small for similarity signature calculation");
return GIT_EBUFS;
}
hashsig_heap_sort(&sig->mins);
hashsig_heap_sort(&sig->maxs);
return 0;
}
static git_hashsig *hashsig_alloc(git_hashsig_option_t opts)
{
git_hashsig *sig = git__calloc(1, sizeof(git_hashsig));
if (!sig)
return NULL;
hashsig_heap_init(&sig->mins, hashsig_cmp_min);
hashsig_heap_init(&sig->maxs, hashsig_cmp_max);
sig->opt = opts;
return sig;
}
int git_hashsig_create(
git_hashsig **out,
const char *buf,
size_t buflen,
git_hashsig_option_t opts)
{
int error;
hashsig_in_progress prog;
git_hashsig *sig = hashsig_alloc(opts);
GIT_ERROR_CHECK_ALLOC(sig);
if ((error = hashsig_in_progress_init(&prog, sig)) < 0)
return error;
error = hashsig_add_hashes(sig, (const uint8_t *)buf, buflen, &prog);
if (!error)
error = hashsig_finalize_hashes(sig);
if (!error)
*out = sig;
else
git_hashsig_free(sig);
return error;
}
int git_hashsig_create_fromfile(
git_hashsig **out,
const char *path,
git_hashsig_option_t opts)
{
uint8_t buf[0x1000];
ssize_t buflen = 0;
int error = 0, fd;
hashsig_in_progress prog;
git_hashsig *sig = hashsig_alloc(opts);
GIT_ERROR_CHECK_ALLOC(sig);
if ((fd = git_futils_open_ro(path)) < 0) {
git__free(sig);
return fd;
}
if ((error = hashsig_in_progress_init(&prog, sig)) < 0) {
p_close(fd);
return error;
}
while (!error) {
if ((buflen = p_read(fd, buf, sizeof(buf))) <= 0) {
if ((error = (int)buflen) < 0)
git_error_set(GIT_ERROR_OS,
"read error on '%s' calculating similarity hashes", path);
break;
}
error = hashsig_add_hashes(sig, buf, buflen, &prog);
}
p_close(fd);
if (!error)
error = hashsig_finalize_hashes(sig);
if (!error)
*out = sig;
else
git_hashsig_free(sig);
return error;
}
void git_hashsig_free(git_hashsig *sig)
{
git__free(sig);
}
static int hashsig_heap_compare(const hashsig_heap *a, const hashsig_heap *b)
{
int matches = 0, i, j, cmp;
GIT_ASSERT_WITH_RETVAL(a->cmp == b->cmp, 0);
/* hash heaps are sorted - just look for overlap vs total */
for (i = 0, j = 0; i < a->size && j < b->size; ) {
cmp = a->cmp(&a->values[i], &b->values[j], NULL);
if (cmp < 0)
++i;
else if (cmp > 0)
++j;
else {
++i; ++j; ++matches;
}
}
return HASHSIG_SCALE * (matches * 2) / (a->size + b->size);
}
int git_hashsig_compare(const git_hashsig *a, const git_hashsig *b)
{
/* if we have no elements in either file then each file is either
* empty or blank. if we're ignoring whitespace then the files are
* similar, otherwise they're dissimilar.
*/
if (a->mins.size == 0 && b->mins.size == 0) {
if ((!a->lines && !b->lines) ||
(a->opt & GIT_HASHSIG_IGNORE_WHITESPACE))
return HASHSIG_SCALE;
else
return 0;
}
/* if we have fewer than the maximum number of elements, then just use
* one array since the two arrays will be the same
*/
if (a->mins.size < HASHSIG_HEAP_SIZE) {
return hashsig_heap_compare(&a->mins, &b->mins);
} else {
int mins, maxs;
if ((mins = hashsig_heap_compare(&a->mins, &b->mins)) < 0)
return mins;
if ((maxs = hashsig_heap_compare(&a->maxs, &b->maxs)) < 0)
return maxs;
return (mins + maxs) / 2;
}
}
|
0 |
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2
|
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2/src/diff_print.c
|
/*
* Copyright (C) the libgit2 contributors. All rights reserved.
*
* This file is part of libgit2, distributed under the GNU GPL v2 with
* a Linking Exception. For full terms see the included COPYING file.
*/
#include "common.h"
#include "diff.h"
#include "diff_file.h"
#include "patch_generate.h"
#include "futils.h"
#include "zstream.h"
#include "blob.h"
#include "delta.h"
#include "git2/sys/diff.h"
typedef struct {
git_diff_format_t format;
git_diff_line_cb print_cb;
void *payload;
git_buf *buf;
git_diff_line line;
const char *old_prefix;
const char *new_prefix;
uint32_t flags;
int id_strlen;
int (*strcomp)(const char *, const char *);
} diff_print_info;
static int diff_print_info_init__common(
diff_print_info *pi,
git_buf *out,
git_repository *repo,
git_diff_format_t format,
git_diff_line_cb cb,
void *payload)
{
pi->format = format;
pi->print_cb = cb;
pi->payload = payload;
pi->buf = out;
if (!pi->id_strlen) {
if (!repo)
pi->id_strlen = GIT_ABBREV_DEFAULT;
else if (git_repository__configmap_lookup(&pi->id_strlen, repo, GIT_CONFIGMAP_ABBREV) < 0)
return -1;
}
if (pi->id_strlen > GIT_OID_HEXSZ)
pi->id_strlen = GIT_OID_HEXSZ;
memset(&pi->line, 0, sizeof(pi->line));
pi->line.old_lineno = -1;
pi->line.new_lineno = -1;
pi->line.num_lines = 1;
return 0;
}
static int diff_print_info_init_fromdiff(
diff_print_info *pi,
git_buf *out,
git_diff *diff,
git_diff_format_t format,
git_diff_line_cb cb,
void *payload)
{
git_repository *repo = diff ? diff->repo : NULL;
memset(pi, 0, sizeof(diff_print_info));
if (diff) {
pi->flags = diff->opts.flags;
pi->id_strlen = diff->opts.id_abbrev;
pi->old_prefix = diff->opts.old_prefix;
pi->new_prefix = diff->opts.new_prefix;
pi->strcomp = diff->strcomp;
}
return diff_print_info_init__common(pi, out, repo, format, cb, payload);
}
static int diff_print_info_init_frompatch(
diff_print_info *pi,
git_buf *out,
git_patch *patch,
git_diff_format_t format,
git_diff_line_cb cb,
void *payload)
{
GIT_ASSERT_ARG(patch);
memset(pi, 0, sizeof(diff_print_info));
pi->flags = patch->diff_opts.flags;
pi->id_strlen = patch->diff_opts.id_abbrev;
pi->old_prefix = patch->diff_opts.old_prefix;
pi->new_prefix = patch->diff_opts.new_prefix;
return diff_print_info_init__common(pi, out, patch->repo, format, cb, payload);
}
static char diff_pick_suffix(int mode)
{
if (S_ISDIR(mode))
return '/';
else if (GIT_PERMS_IS_EXEC(mode)) /* -V536 */
/* in git, modes are very regular, so we must have 0100755 mode */
return '*';
else
return ' ';
}
char git_diff_status_char(git_delta_t status)
{
char code;
switch (status) {
case GIT_DELTA_ADDED: code = 'A'; break;
case GIT_DELTA_DELETED: code = 'D'; break;
case GIT_DELTA_MODIFIED: code = 'M'; break;
case GIT_DELTA_RENAMED: code = 'R'; break;
case GIT_DELTA_COPIED: code = 'C'; break;
case GIT_DELTA_IGNORED: code = 'I'; break;
case GIT_DELTA_UNTRACKED: code = '?'; break;
case GIT_DELTA_TYPECHANGE: code = 'T'; break;
case GIT_DELTA_UNREADABLE: code = 'X'; break;
default: code = ' '; break;
}
return code;
}
static int diff_print_one_name_only(
const git_diff_delta *delta, float progress, void *data)
{
diff_print_info *pi = data;
git_buf *out = pi->buf;
GIT_UNUSED(progress);
if ((pi->flags & GIT_DIFF_SHOW_UNMODIFIED) == 0 &&
delta->status == GIT_DELTA_UNMODIFIED)
return 0;
git_buf_clear(out);
git_buf_puts(out, delta->new_file.path);
git_buf_putc(out, '\n');
if (git_buf_oom(out))
return -1;
pi->line.origin = GIT_DIFF_LINE_FILE_HDR;
pi->line.content = git_buf_cstr(out);
pi->line.content_len = git_buf_len(out);
return pi->print_cb(delta, NULL, &pi->line, pi->payload);
}
static int diff_print_one_name_status(
const git_diff_delta *delta, float progress, void *data)
{
diff_print_info *pi = data;
git_buf *out = pi->buf;
char old_suffix, new_suffix, code = git_diff_status_char(delta->status);
int(*strcomp)(const char *, const char *) = pi->strcomp ?
pi->strcomp : git__strcmp;
GIT_UNUSED(progress);
if ((pi->flags & GIT_DIFF_SHOW_UNMODIFIED) == 0 && code == ' ')
return 0;
old_suffix = diff_pick_suffix(delta->old_file.mode);
new_suffix = diff_pick_suffix(delta->new_file.mode);
git_buf_clear(out);
if (delta->old_file.path != delta->new_file.path &&
strcomp(delta->old_file.path,delta->new_file.path) != 0)
git_buf_printf(out, "%c\t%s%c %s%c\n", code,
delta->old_file.path, old_suffix, delta->new_file.path, new_suffix);
else if (delta->old_file.mode != delta->new_file.mode &&
delta->old_file.mode != 0 && delta->new_file.mode != 0)
git_buf_printf(out, "%c\t%s%c %s%c\n", code,
delta->old_file.path, old_suffix, delta->new_file.path, new_suffix);
else if (old_suffix != ' ')
git_buf_printf(out, "%c\t%s%c\n", code, delta->old_file.path, old_suffix);
else
git_buf_printf(out, "%c\t%s\n", code, delta->old_file.path);
if (git_buf_oom(out))
return -1;
pi->line.origin = GIT_DIFF_LINE_FILE_HDR;
pi->line.content = git_buf_cstr(out);
pi->line.content_len = git_buf_len(out);
return pi->print_cb(delta, NULL, &pi->line, pi->payload);
}
static int diff_print_one_raw(
const git_diff_delta *delta, float progress, void *data)
{
diff_print_info *pi = data;
git_buf *out = pi->buf;
int id_abbrev;
char code = git_diff_status_char(delta->status);
char start_oid[GIT_OID_HEXSZ+1], end_oid[GIT_OID_HEXSZ+1];
GIT_UNUSED(progress);
if ((pi->flags & GIT_DIFF_SHOW_UNMODIFIED) == 0 && code == ' ')
return 0;
git_buf_clear(out);
id_abbrev = delta->old_file.mode ? delta->old_file.id_abbrev :
delta->new_file.id_abbrev;
if (pi->id_strlen > id_abbrev) {
git_error_set(GIT_ERROR_PATCH,
"the patch input contains %d id characters (cannot print %d)",
id_abbrev, pi->id_strlen);
return -1;
}
git_oid_tostr(start_oid, pi->id_strlen + 1, &delta->old_file.id);
git_oid_tostr(end_oid, pi->id_strlen + 1, &delta->new_file.id);
git_buf_printf(
out, (pi->id_strlen <= GIT_OID_HEXSZ) ?
":%06o %06o %s... %s... %c" : ":%06o %06o %s %s %c",
delta->old_file.mode, delta->new_file.mode, start_oid, end_oid, code);
if (delta->similarity > 0)
git_buf_printf(out, "%03u", delta->similarity);
if (delta->old_file.path != delta->new_file.path)
git_buf_printf(
out, "\t%s %s\n", delta->old_file.path, delta->new_file.path);
else
git_buf_printf(
out, "\t%s\n", delta->old_file.path ?
delta->old_file.path : delta->new_file.path);
if (git_buf_oom(out))
return -1;
pi->line.origin = GIT_DIFF_LINE_FILE_HDR;
pi->line.content = git_buf_cstr(out);
pi->line.content_len = git_buf_len(out);
return pi->print_cb(delta, NULL, &pi->line, pi->payload);
}
static int diff_print_modes(
git_buf *out, const git_diff_delta *delta)
{
git_buf_printf(out, "old mode %o\n", delta->old_file.mode);
git_buf_printf(out, "new mode %o\n", delta->new_file.mode);
return git_buf_oom(out) ? -1 : 0;
}
static int diff_print_oid_range(
git_buf *out, const git_diff_delta *delta, int id_strlen,
bool print_index)
{
char start_oid[GIT_OID_HEXSZ+1], end_oid[GIT_OID_HEXSZ+1];
if (delta->old_file.mode &&
id_strlen > delta->old_file.id_abbrev) {
git_error_set(GIT_ERROR_PATCH,
"the patch input contains %d id characters (cannot print %d)",
delta->old_file.id_abbrev, id_strlen);
return -1;
}
if ((delta->new_file.mode &&
id_strlen > delta->new_file.id_abbrev)) {
git_error_set(GIT_ERROR_PATCH,
"the patch input contains %d id characters (cannot print %d)",
delta->new_file.id_abbrev, id_strlen);
return -1;
}
git_oid_tostr(start_oid, id_strlen + 1, &delta->old_file.id);
git_oid_tostr(end_oid, id_strlen + 1, &delta->new_file.id);
if (delta->old_file.mode == delta->new_file.mode) {
if (print_index)
git_buf_printf(out, "index %s..%s %o\n",
start_oid, end_oid, delta->old_file.mode);
} else {
if (delta->old_file.mode == 0)
git_buf_printf(out, "new file mode %o\n", delta->new_file.mode);
else if (delta->new_file.mode == 0)
git_buf_printf(out, "deleted file mode %o\n", delta->old_file.mode);
else
diff_print_modes(out, delta);
if (print_index)
git_buf_printf(out, "index %s..%s\n", start_oid, end_oid);
}
return git_buf_oom(out) ? -1 : 0;
}
static int diff_delta_format_path(
git_buf *out, const char *prefix, const char *filename)
{
if (git_buf_joinpath(out, prefix, filename) < 0)
return -1;
return git_buf_quote(out);
}
static int diff_delta_format_with_paths(
git_buf *out,
const git_diff_delta *delta,
const char *template,
const char *oldpath,
const char *newpath)
{
if (git_oid_is_zero(&delta->old_file.id))
oldpath = "/dev/null";
if (git_oid_is_zero(&delta->new_file.id))
newpath = "/dev/null";
return git_buf_printf(out, template, oldpath, newpath);
}
static int diff_delta_format_similarity_header(
git_buf *out,
const git_diff_delta *delta)
{
git_buf old_path = GIT_BUF_INIT, new_path = GIT_BUF_INIT;
const char *type;
int error = 0;
if (delta->similarity > 100) {
git_error_set(GIT_ERROR_PATCH, "invalid similarity %d", delta->similarity);
error = -1;
goto done;
}
GIT_ASSERT(delta->status == GIT_DELTA_RENAMED || delta->status == GIT_DELTA_COPIED);
if (delta->status == GIT_DELTA_RENAMED)
type = "rename";
else
type = "copy";
if ((error = git_buf_puts(&old_path, delta->old_file.path)) < 0 ||
(error = git_buf_puts(&new_path, delta->new_file.path)) < 0 ||
(error = git_buf_quote(&old_path)) < 0 ||
(error = git_buf_quote(&new_path)) < 0)
goto done;
git_buf_printf(out,
"similarity index %d%%\n"
"%s from %s\n"
"%s to %s\n",
delta->similarity,
type, old_path.ptr,
type, new_path.ptr);
if (git_buf_oom(out))
error = -1;
done:
git_buf_dispose(&old_path);
git_buf_dispose(&new_path);
return error;
}
static bool delta_is_unchanged(const git_diff_delta *delta)
{
if (git_oid_is_zero(&delta->old_file.id) &&
git_oid_is_zero(&delta->new_file.id))
return true;
if (delta->old_file.mode == GIT_FILEMODE_COMMIT ||
delta->new_file.mode == GIT_FILEMODE_COMMIT)
return false;
if (git_oid_equal(&delta->old_file.id, &delta->new_file.id))
return true;
return false;
}
int git_diff_delta__format_file_header(
git_buf *out,
const git_diff_delta *delta,
const char *oldpfx,
const char *newpfx,
int id_strlen,
bool print_index)
{
git_buf old_path = GIT_BUF_INIT, new_path = GIT_BUF_INIT;
bool unchanged = delta_is_unchanged(delta);
int error = 0;
if (!oldpfx)
oldpfx = DIFF_OLD_PREFIX_DEFAULT;
if (!newpfx)
newpfx = DIFF_NEW_PREFIX_DEFAULT;
if (!id_strlen)
id_strlen = GIT_ABBREV_DEFAULT;
if ((error = diff_delta_format_path(
&old_path, oldpfx, delta->old_file.path)) < 0 ||
(error = diff_delta_format_path(
&new_path, newpfx, delta->new_file.path)) < 0)
goto done;
git_buf_clear(out);
git_buf_printf(out, "diff --git %s %s\n",
old_path.ptr, new_path.ptr);
if (unchanged && delta->old_file.mode != delta->new_file.mode)
diff_print_modes(out, delta);
if (delta->status == GIT_DELTA_RENAMED ||
(delta->status == GIT_DELTA_COPIED && unchanged)) {
if ((error = diff_delta_format_similarity_header(out, delta)) < 0)
goto done;
}
if (!unchanged) {
if ((error = diff_print_oid_range(out, delta,
id_strlen, print_index)) < 0)
goto done;
if ((delta->flags & GIT_DIFF_FLAG_BINARY) == 0)
diff_delta_format_with_paths(out, delta,
"--- %s\n+++ %s\n", old_path.ptr, new_path.ptr);
}
if (git_buf_oom(out))
error = -1;
done:
git_buf_dispose(&old_path);
git_buf_dispose(&new_path);
return error;
}
static int format_binary(
diff_print_info *pi,
git_diff_binary_t type,
const char *data,
size_t datalen,
size_t inflatedlen)
{
const char *typename = type == GIT_DIFF_BINARY_DELTA ?
"delta" : "literal";
const char *scan, *end;
git_buf_printf(pi->buf, "%s %" PRIuZ "\n", typename, inflatedlen);
pi->line.num_lines++;
for (scan = data, end = data + datalen; scan < end; ) {
size_t chunk_len = end - scan;
if (chunk_len > 52)
chunk_len = 52;
if (chunk_len <= 26)
git_buf_putc(pi->buf, (char)chunk_len + 'A' - 1);
else
git_buf_putc(pi->buf, (char)chunk_len - 26 + 'a' - 1);
git_buf_encode_base85(pi->buf, scan, chunk_len);
git_buf_putc(pi->buf, '\n');
if (git_buf_oom(pi->buf))
return -1;
scan += chunk_len;
pi->line.num_lines++;
}
git_buf_putc(pi->buf, '\n');
if (git_buf_oom(pi->buf))
return -1;
return 0;
}
static int diff_print_patch_file_binary_noshow(
diff_print_info *pi, git_diff_delta *delta,
const char *old_pfx, const char *new_pfx)
{
git_buf old_path = GIT_BUF_INIT, new_path = GIT_BUF_INIT;
int error;
if ((error = diff_delta_format_path(&old_path, old_pfx, delta->old_file.path)) < 0 ||
(error = diff_delta_format_path(&new_path, new_pfx, delta->new_file.path)) < 0 ||
(error = diff_delta_format_with_paths(pi->buf, delta, "Binary files %s and %s differ\n",
old_path.ptr, new_path.ptr)) < 0)
goto done;
pi->line.num_lines = 1;
done:
git_buf_dispose(&old_path);
git_buf_dispose(&new_path);
return error;
}
static int diff_print_patch_file_binary(
diff_print_info *pi, git_diff_delta *delta,
const char *old_pfx, const char *new_pfx,
const git_diff_binary *binary)
{
size_t pre_binary_size;
int error;
if (delta->status == GIT_DELTA_UNMODIFIED)
return 0;
if ((pi->flags & GIT_DIFF_SHOW_BINARY) == 0 || !binary->contains_data)
return diff_print_patch_file_binary_noshow(
pi, delta, old_pfx, new_pfx);
pre_binary_size = pi->buf->size;
git_buf_printf(pi->buf, "GIT binary patch\n");
pi->line.num_lines++;
if ((error = format_binary(pi, binary->new_file.type, binary->new_file.data,
binary->new_file.datalen, binary->new_file.inflatedlen)) < 0 ||
(error = format_binary(pi, binary->old_file.type, binary->old_file.data,
binary->old_file.datalen, binary->old_file.inflatedlen)) < 0) {
if (error == GIT_EBUFS) {
git_error_clear();
git_buf_truncate(pi->buf, pre_binary_size);
return diff_print_patch_file_binary_noshow(
pi, delta, old_pfx, new_pfx);
}
}
pi->line.num_lines++;
return error;
}
static int diff_print_patch_file(
const git_diff_delta *delta, float progress, void *data)
{
int error;
diff_print_info *pi = data;
const char *oldpfx =
pi->old_prefix ? pi->old_prefix : DIFF_OLD_PREFIX_DEFAULT;
const char *newpfx =
pi->new_prefix ? pi->new_prefix : DIFF_NEW_PREFIX_DEFAULT;
bool binary = (delta->flags & GIT_DIFF_FLAG_BINARY) ||
(pi->flags & GIT_DIFF_FORCE_BINARY);
bool show_binary = !!(pi->flags & GIT_DIFF_SHOW_BINARY);
int id_strlen = pi->id_strlen;
bool print_index = (pi->format != GIT_DIFF_FORMAT_PATCH_ID);
if (binary && show_binary)
id_strlen = delta->old_file.id_abbrev ? delta->old_file.id_abbrev :
delta->new_file.id_abbrev;
GIT_UNUSED(progress);
if (S_ISDIR(delta->new_file.mode) ||
delta->status == GIT_DELTA_UNMODIFIED ||
delta->status == GIT_DELTA_IGNORED ||
delta->status == GIT_DELTA_UNREADABLE ||
(delta->status == GIT_DELTA_UNTRACKED &&
(pi->flags & GIT_DIFF_SHOW_UNTRACKED_CONTENT) == 0))
return 0;
if ((error = git_diff_delta__format_file_header(pi->buf, delta, oldpfx, newpfx,
id_strlen, print_index)) < 0)
return error;
pi->line.origin = GIT_DIFF_LINE_FILE_HDR;
pi->line.content = git_buf_cstr(pi->buf);
pi->line.content_len = git_buf_len(pi->buf);
return pi->print_cb(delta, NULL, &pi->line, pi->payload);
}
static int diff_print_patch_binary(
const git_diff_delta *delta,
const git_diff_binary *binary,
void *data)
{
diff_print_info *pi = data;
const char *old_pfx =
pi->old_prefix ? pi->old_prefix : DIFF_OLD_PREFIX_DEFAULT;
const char *new_pfx =
pi->new_prefix ? pi->new_prefix : DIFF_NEW_PREFIX_DEFAULT;
int error;
git_buf_clear(pi->buf);
if ((error = diff_print_patch_file_binary(
pi, (git_diff_delta *)delta, old_pfx, new_pfx, binary)) < 0)
return error;
pi->line.origin = GIT_DIFF_LINE_BINARY;
pi->line.content = git_buf_cstr(pi->buf);
pi->line.content_len = git_buf_len(pi->buf);
return pi->print_cb(delta, NULL, &pi->line, pi->payload);
}
static int diff_print_patch_hunk(
const git_diff_delta *d,
const git_diff_hunk *h,
void *data)
{
diff_print_info *pi = data;
if (S_ISDIR(d->new_file.mode))
return 0;
pi->line.origin = GIT_DIFF_LINE_HUNK_HDR;
pi->line.content = h->header;
pi->line.content_len = h->header_len;
return pi->print_cb(d, h, &pi->line, pi->payload);
}
static int diff_print_patch_line(
const git_diff_delta *delta,
const git_diff_hunk *hunk,
const git_diff_line *line,
void *data)
{
diff_print_info *pi = data;
if (S_ISDIR(delta->new_file.mode))
return 0;
return pi->print_cb(delta, hunk, line, pi->payload);
}
/* print a git_diff to an output callback */
int git_diff_print(
git_diff *diff,
git_diff_format_t format,
git_diff_line_cb print_cb,
void *payload)
{
int error;
git_buf buf = GIT_BUF_INIT;
diff_print_info pi;
git_diff_file_cb print_file = NULL;
git_diff_binary_cb print_binary = NULL;
git_diff_hunk_cb print_hunk = NULL;
git_diff_line_cb print_line = NULL;
switch (format) {
case GIT_DIFF_FORMAT_PATCH:
print_file = diff_print_patch_file;
print_binary = diff_print_patch_binary;
print_hunk = diff_print_patch_hunk;
print_line = diff_print_patch_line;
break;
case GIT_DIFF_FORMAT_PATCH_ID:
print_file = diff_print_patch_file;
print_binary = diff_print_patch_binary;
print_line = diff_print_patch_line;
break;
case GIT_DIFF_FORMAT_PATCH_HEADER:
print_file = diff_print_patch_file;
break;
case GIT_DIFF_FORMAT_RAW:
print_file = diff_print_one_raw;
break;
case GIT_DIFF_FORMAT_NAME_ONLY:
print_file = diff_print_one_name_only;
break;
case GIT_DIFF_FORMAT_NAME_STATUS:
print_file = diff_print_one_name_status;
break;
default:
git_error_set(GIT_ERROR_INVALID, "unknown diff output format (%d)", format);
return -1;
}
if ((error = diff_print_info_init_fromdiff(&pi, &buf, diff, format, print_cb, payload)) < 0)
goto out;
if ((error = git_diff_foreach(diff, print_file, print_binary, print_hunk, print_line, &pi)) != 0) {
git_error_set_after_callback_function(error, "git_diff_print");
goto out;
}
out:
git_buf_dispose(&buf);
return error;
}
int git_diff_print_callback__to_buf(
const git_diff_delta *delta,
const git_diff_hunk *hunk,
const git_diff_line *line,
void *payload)
{
git_buf *output = payload;
GIT_UNUSED(delta); GIT_UNUSED(hunk);
if (!output) {
git_error_set(GIT_ERROR_INVALID, "buffer pointer must be provided");
return -1;
}
if (line->origin == GIT_DIFF_LINE_ADDITION ||
line->origin == GIT_DIFF_LINE_DELETION ||
line->origin == GIT_DIFF_LINE_CONTEXT)
git_buf_putc(output, line->origin);
return git_buf_put(output, line->content, line->content_len);
}
int git_diff_print_callback__to_file_handle(
const git_diff_delta *delta,
const git_diff_hunk *hunk,
const git_diff_line *line,
void *payload)
{
FILE *fp = payload ? payload : stdout;
int error;
GIT_UNUSED(delta);
GIT_UNUSED(hunk);
if (line->origin == GIT_DIFF_LINE_CONTEXT ||
line->origin == GIT_DIFF_LINE_ADDITION ||
line->origin == GIT_DIFF_LINE_DELETION) {
while ((error = fputc(line->origin, fp)) == EINTR)
continue;
if (error) {
git_error_set(GIT_ERROR_OS, "could not write status");
return -1;
}
}
if (fwrite(line->content, line->content_len, 1, fp) != 1) {
git_error_set(GIT_ERROR_OS, "could not write line");
return -1;
}
return 0;
}
/* print a git_diff to a git_buf */
int git_diff_to_buf(git_buf *out, git_diff *diff, git_diff_format_t format)
{
int error;
GIT_ASSERT_ARG(out);
GIT_ASSERT_ARG(diff);
if ((error = git_buf_sanitize(out)) < 0)
return error;
return git_diff_print(diff, format, git_diff_print_callback__to_buf, out);
}
/* print a git_patch to an output callback */
int git_patch_print(
git_patch *patch,
git_diff_line_cb print_cb,
void *payload)
{
git_buf temp = GIT_BUF_INIT;
diff_print_info pi;
int error;
GIT_ASSERT_ARG(patch);
GIT_ASSERT_ARG(print_cb);
if ((error = diff_print_info_init_frompatch(&pi, &temp, patch,
GIT_DIFF_FORMAT_PATCH, print_cb, payload)) < 0)
goto out;
if ((error = git_patch__invoke_callbacks(patch, diff_print_patch_file, diff_print_patch_binary,
diff_print_patch_hunk, diff_print_patch_line, &pi)) < 0) {
git_error_set_after_callback_function(error, "git_patch_print");
goto out;
}
out:
git_buf_dispose(&temp);
return error;
}
/* print a git_patch to a git_buf */
int git_patch_to_buf(git_buf *out, git_patch *patch)
{
int error;
GIT_ASSERT_ARG(out);
GIT_ASSERT_ARG(patch);
if ((error = git_buf_sanitize(out)) < 0)
return error;
return git_patch_print(patch, git_diff_print_callback__to_buf, out);
}
|
0 |
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2
|
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2/src/net.c
|
/*
* Copyright (C) the libgit2 contributors. All rights reserved.
*
* This file is part of libgit2, distributed under the GNU GPL v2 with
* a Linking Exception. For full terms see the included COPYING file.
*/
#include "net.h"
#include "netops.h"
#include <ctype.h>
#include "git2/errors.h"
#include "posix.h"
#include "buffer.h"
#include "http_parser.h"
#include "runtime.h"
#define DEFAULT_PORT_HTTP "80"
#define DEFAULT_PORT_HTTPS "443"
#define DEFAULT_PORT_GIT "9418"
#define DEFAULT_PORT_SSH "22"
static const char *default_port_for_scheme(const char *scheme)
{
if (strcmp(scheme, "http") == 0)
return DEFAULT_PORT_HTTP;
else if (strcmp(scheme, "https") == 0)
return DEFAULT_PORT_HTTPS;
else if (strcmp(scheme, "git") == 0)
return DEFAULT_PORT_GIT;
else if (strcmp(scheme, "ssh") == 0)
return DEFAULT_PORT_SSH;
return NULL;
}
int git_net_url_dup(git_net_url *out, git_net_url *in)
{
if (in->scheme) {
out->scheme = git__strdup(in->scheme);
GIT_ERROR_CHECK_ALLOC(out->scheme);
}
if (in->host) {
out->host = git__strdup(in->host);
GIT_ERROR_CHECK_ALLOC(out->host);
}
if (in->port) {
out->port = git__strdup(in->port);
GIT_ERROR_CHECK_ALLOC(out->port);
}
if (in->path) {
out->path = git__strdup(in->path);
GIT_ERROR_CHECK_ALLOC(out->path);
}
if (in->query) {
out->query = git__strdup(in->query);
GIT_ERROR_CHECK_ALLOC(out->query);
}
if (in->username) {
out->username = git__strdup(in->username);
GIT_ERROR_CHECK_ALLOC(out->username);
}
if (in->password) {
out->password = git__strdup(in->password);
GIT_ERROR_CHECK_ALLOC(out->password);
}
return 0;
}
int git_net_url_parse(git_net_url *url, const char *given)
{
struct http_parser_url u = {0};
bool has_scheme, has_host, has_port, has_path, has_query, has_userinfo;
git_buf scheme = GIT_BUF_INIT,
host = GIT_BUF_INIT,
port = GIT_BUF_INIT,
path = GIT_BUF_INIT,
username = GIT_BUF_INIT,
password = GIT_BUF_INIT,
query = GIT_BUF_INIT;
int error = GIT_EINVALIDSPEC;
if (http_parser_parse_url(given, strlen(given), false, &u)) {
git_error_set(GIT_ERROR_NET, "malformed URL '%s'", given);
goto done;
}
has_scheme = !!(u.field_set & (1 << UF_SCHEMA));
has_host = !!(u.field_set & (1 << UF_HOST));
has_port = !!(u.field_set & (1 << UF_PORT));
has_path = !!(u.field_set & (1 << UF_PATH));
has_query = !!(u.field_set & (1 << UF_QUERY));
has_userinfo = !!(u.field_set & (1 << UF_USERINFO));
if (has_scheme) {
const char *url_scheme = given + u.field_data[UF_SCHEMA].off;
size_t url_scheme_len = u.field_data[UF_SCHEMA].len;
git_buf_put(&scheme, url_scheme, url_scheme_len);
git__strntolower(scheme.ptr, scheme.size);
} else {
git_error_set(GIT_ERROR_NET, "malformed URL '%s'", given);
goto done;
}
if (has_host) {
const char *url_host = given + u.field_data[UF_HOST].off;
size_t url_host_len = u.field_data[UF_HOST].len;
git_buf_decode_percent(&host, url_host, url_host_len);
}
if (has_port) {
const char *url_port = given + u.field_data[UF_PORT].off;
size_t url_port_len = u.field_data[UF_PORT].len;
git_buf_put(&port, url_port, url_port_len);
} else {
const char *default_port = default_port_for_scheme(scheme.ptr);
if (default_port == NULL) {
git_error_set(GIT_ERROR_NET, "unknown scheme for URL '%s'", given);
goto done;
}
git_buf_puts(&port, default_port);
}
if (has_path) {
const char *url_path = given + u.field_data[UF_PATH].off;
size_t url_path_len = u.field_data[UF_PATH].len;
git_buf_put(&path, url_path, url_path_len);
} else {
git_buf_puts(&path, "/");
}
if (has_query) {
const char *url_query = given + u.field_data[UF_QUERY].off;
size_t url_query_len = u.field_data[UF_QUERY].len;
git_buf_decode_percent(&query, url_query, url_query_len);
}
if (has_userinfo) {
const char *url_userinfo = given + u.field_data[UF_USERINFO].off;
size_t url_userinfo_len = u.field_data[UF_USERINFO].len;
const char *colon = memchr(url_userinfo, ':', url_userinfo_len);
if (colon) {
const char *url_username = url_userinfo;
size_t url_username_len = colon - url_userinfo;
const char *url_password = colon + 1;
size_t url_password_len = url_userinfo_len - (url_username_len + 1);
git_buf_decode_percent(&username, url_username, url_username_len);
git_buf_decode_percent(&password, url_password, url_password_len);
} else {
git_buf_decode_percent(&username, url_userinfo, url_userinfo_len);
}
}
if (git_buf_oom(&scheme) ||
git_buf_oom(&host) ||
git_buf_oom(&port) ||
git_buf_oom(&path) ||
git_buf_oom(&query) ||
git_buf_oom(&username) ||
git_buf_oom(&password))
return -1;
url->scheme = git_buf_detach(&scheme);
url->host = git_buf_detach(&host);
url->port = git_buf_detach(&port);
url->path = git_buf_detach(&path);
url->query = git_buf_detach(&query);
url->username = git_buf_detach(&username);
url->password = git_buf_detach(&password);
error = 0;
done:
git_buf_dispose(&scheme);
git_buf_dispose(&host);
git_buf_dispose(&port);
git_buf_dispose(&path);
git_buf_dispose(&query);
git_buf_dispose(&username);
git_buf_dispose(&password);
return error;
}
int git_net_url_joinpath(
git_net_url *out,
git_net_url *one,
const char *two)
{
git_buf path = GIT_BUF_INIT;
const char *query;
size_t one_len, two_len;
git_net_url_dispose(out);
if ((query = strchr(two, '?')) != NULL) {
two_len = query - two;
if (*(++query) != '\0') {
out->query = git__strdup(query);
GIT_ERROR_CHECK_ALLOC(out->query);
}
} else {
two_len = strlen(two);
}
/* Strip all trailing `/`s from the first path */
one_len = one->path ? strlen(one->path) : 0;
while (one_len && one->path[one_len - 1] == '/')
one_len--;
/* Strip all leading `/`s from the second path */
while (*two == '/') {
two++;
two_len--;
}
git_buf_put(&path, one->path, one_len);
git_buf_putc(&path, '/');
git_buf_put(&path, two, two_len);
if (git_buf_oom(&path))
return -1;
out->path = git_buf_detach(&path);
if (one->scheme) {
out->scheme = git__strdup(one->scheme);
GIT_ERROR_CHECK_ALLOC(out->scheme);
}
if (one->host) {
out->host = git__strdup(one->host);
GIT_ERROR_CHECK_ALLOC(out->host);
}
if (one->port) {
out->port = git__strdup(one->port);
GIT_ERROR_CHECK_ALLOC(out->port);
}
if (one->username) {
out->username = git__strdup(one->username);
GIT_ERROR_CHECK_ALLOC(out->username);
}
if (one->password) {
out->password = git__strdup(one->password);
GIT_ERROR_CHECK_ALLOC(out->password);
}
return 0;
}
/*
* Some servers strip the query parameters from the Location header
* when sending a redirect. Others leave it in place.
* Check for both, starting with the stripped case first,
* since it appears to be more common.
*/
static void remove_service_suffix(
git_net_url *url,
const char *service_suffix)
{
const char *service_query = strchr(service_suffix, '?');
size_t full_suffix_len = strlen(service_suffix);
size_t suffix_len = service_query ?
(size_t)(service_query - service_suffix) : full_suffix_len;
size_t path_len = strlen(url->path);
ssize_t truncate = -1;
/*
* Check for a redirect without query parameters,
* like "/newloc/info/refs"'
*/
if (suffix_len && path_len >= suffix_len) {
size_t suffix_offset = path_len - suffix_len;
if (git__strncmp(url->path + suffix_offset, service_suffix, suffix_len) == 0 &&
(!service_query || git__strcmp(url->query, service_query + 1) == 0)) {
truncate = suffix_offset;
}
}
/*
* If we haven't already found where to truncate to remove the
* suffix, check for a redirect with query parameters, like
* "/newloc/info/refs?service=git-upload-pack"
*/
if (truncate < 0 && git__suffixcmp(url->path, service_suffix) == 0)
truncate = path_len - full_suffix_len;
/* Ensure we leave a minimum of '/' as the path */
if (truncate == 0)
truncate++;
if (truncate > 0) {
url->path[truncate] = '\0';
git__free(url->query);
url->query = NULL;
}
}
int git_net_url_apply_redirect(
git_net_url *url,
const char *redirect_location,
const char *service_suffix)
{
git_net_url tmp = GIT_NET_URL_INIT;
int error = 0;
GIT_ASSERT(url);
GIT_ASSERT(redirect_location);
if (redirect_location[0] == '/') {
git__free(url->path);
if ((url->path = git__strdup(redirect_location)) == NULL) {
error = -1;
goto done;
}
} else {
git_net_url *original = url;
if ((error = git_net_url_parse(&tmp, redirect_location)) < 0)
goto done;
/* Validate that this is a legal redirection */
if (original->scheme &&
strcmp(original->scheme, tmp.scheme) != 0 &&
strcmp(tmp.scheme, "https") != 0) {
git_error_set(GIT_ERROR_NET, "cannot redirect from '%s' to '%s'",
original->scheme, tmp.scheme);
error = -1;
goto done;
}
if (original->host &&
git__strcasecmp(original->host, tmp.host) != 0) {
git_error_set(GIT_ERROR_NET, "cannot redirect from '%s' to '%s'",
original->host, tmp.host);
error = -1;
goto done;
}
git_net_url_swap(url, &tmp);
}
/* Remove the service suffix if it was given to us */
if (service_suffix)
remove_service_suffix(url, service_suffix);
done:
git_net_url_dispose(&tmp);
return error;
}
bool git_net_url_valid(git_net_url *url)
{
return (url->host && url->port && url->path);
}
bool git_net_url_is_default_port(git_net_url *url)
{
const char *default_port;
if ((default_port = default_port_for_scheme(url->scheme)) != NULL)
return (strcmp(url->port, default_port) == 0);
else
return false;
}
bool git_net_url_is_ipv6(git_net_url *url)
{
return (strchr(url->host, ':') != NULL);
}
void git_net_url_swap(git_net_url *a, git_net_url *b)
{
git_net_url tmp = GIT_NET_URL_INIT;
memcpy(&tmp, a, sizeof(git_net_url));
memcpy(a, b, sizeof(git_net_url));
memcpy(b, &tmp, sizeof(git_net_url));
}
int git_net_url_fmt(git_buf *buf, git_net_url *url)
{
GIT_ASSERT_ARG(url);
GIT_ASSERT_ARG(url->scheme);
GIT_ASSERT_ARG(url->host);
git_buf_puts(buf, url->scheme);
git_buf_puts(buf, "://");
if (url->username) {
git_buf_puts(buf, url->username);
if (url->password) {
git_buf_puts(buf, ":");
git_buf_puts(buf, url->password);
}
git_buf_putc(buf, '@');
}
git_buf_puts(buf, url->host);
if (url->port && !git_net_url_is_default_port(url)) {
git_buf_putc(buf, ':');
git_buf_puts(buf, url->port);
}
git_buf_puts(buf, url->path ? url->path : "/");
if (url->query) {
git_buf_putc(buf, '?');
git_buf_puts(buf, url->query);
}
return git_buf_oom(buf) ? -1 : 0;
}
int git_net_url_fmt_path(git_buf *buf, git_net_url *url)
{
git_buf_puts(buf, url->path ? url->path : "/");
if (url->query) {
git_buf_putc(buf, '?');
git_buf_puts(buf, url->query);
}
return git_buf_oom(buf) ? -1 : 0;
}
static bool matches_pattern(
git_net_url *url,
const char *pattern,
size_t pattern_len)
{
const char *domain, *port = NULL, *colon;
size_t host_len, domain_len, port_len = 0, wildcard = 0;
GIT_UNUSED(url);
GIT_UNUSED(pattern);
if (!pattern_len)
return false;
else if (pattern_len == 1 && pattern[0] == '*')
return true;
else if (pattern_len > 1 && pattern[0] == '*' && pattern[1] == '.')
wildcard = 2;
else if (pattern[0] == '.')
wildcard = 1;
domain = pattern + wildcard;
domain_len = pattern_len - wildcard;
if ((colon = memchr(domain, ':', domain_len)) != NULL) {
domain_len = colon - domain;
port = colon + 1;
port_len = pattern_len - wildcard - domain_len - 1;
}
/* A pattern's port *must* match if it's specified */
if (port_len && git__strlcmp(url->port, port, port_len) != 0)
return false;
/* No wildcard? Host must match exactly. */
if (!wildcard)
return !git__strlcmp(url->host, domain, domain_len);
/* Wildcard: ensure there's (at least) a suffix match */
if ((host_len = strlen(url->host)) < domain_len ||
memcmp(url->host + (host_len - domain_len), domain, domain_len))
return false;
/* The pattern is *.domain and the host is simply domain */
if (host_len == domain_len)
return true;
/* The pattern is *.domain and the host is foo.domain */
return (url->host[host_len - domain_len - 1] == '.');
}
bool git_net_url_matches_pattern(git_net_url *url, const char *pattern)
{
return matches_pattern(url, pattern, strlen(pattern));
}
bool git_net_url_matches_pattern_list(
git_net_url *url,
const char *pattern_list)
{
const char *pattern, *pattern_end, *sep;
for (pattern = pattern_list;
pattern && *pattern;
pattern = sep ? sep + 1 : NULL) {
sep = strchr(pattern, ',');
pattern_end = sep ? sep : strchr(pattern, '\0');
if (matches_pattern(url, pattern, (pattern_end - pattern)))
return true;
}
return false;
}
void git_net_url_dispose(git_net_url *url)
{
if (url->username)
git__memzero(url->username, strlen(url->username));
if (url->password)
git__memzero(url->password, strlen(url->password));
git__free(url->scheme); url->scheme = NULL;
git__free(url->host); url->host = NULL;
git__free(url->port); url->port = NULL;
git__free(url->path); url->path = NULL;
git__free(url->query); url->query = NULL;
git__free(url->username); url->username = NULL;
git__free(url->password); url->password = NULL;
}
|
0 |
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2
|
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2/src/diff_generate.h
|
/*
* Copyright (C) the libgit2 contributors. All rights reserved.
*
* This file is part of libgit2, distributed under the GNU GPL v2 with
* a Linking Exception. For full terms see the included COPYING file.
*/
#ifndef INCLUDE_diff_generate_h__
#define INCLUDE_diff_generate_h__
#include "common.h"
#include "diff.h"
#include "pool.h"
#include "index.h"
enum {
GIT_DIFFCAPS_HAS_SYMLINKS = (1 << 0), /* symlinks on platform? */
GIT_DIFFCAPS_IGNORE_STAT = (1 << 1), /* use stat? */
GIT_DIFFCAPS_TRUST_MODE_BITS = (1 << 2), /* use st_mode? */
GIT_DIFFCAPS_TRUST_CTIME = (1 << 3), /* use st_ctime? */
GIT_DIFFCAPS_USE_DEV = (1 << 4), /* use st_dev? */
};
#define DIFF_FLAGS_KNOWN_BINARY (GIT_DIFF_FLAG_BINARY|GIT_DIFF_FLAG_NOT_BINARY)
#define DIFF_FLAGS_NOT_BINARY (GIT_DIFF_FLAG_NOT_BINARY|GIT_DIFF_FLAG__NO_DATA)
enum {
GIT_DIFF_FLAG__FREE_PATH = (1 << 7), /* `path` is allocated memory */
GIT_DIFF_FLAG__FREE_DATA = (1 << 8), /* internal file data is allocated */
GIT_DIFF_FLAG__UNMAP_DATA = (1 << 9), /* internal file data is mmap'ed */
GIT_DIFF_FLAG__NO_DATA = (1 << 10), /* file data should not be loaded */
GIT_DIFF_FLAG__FREE_BLOB = (1 << 11), /* release the blob when done */
GIT_DIFF_FLAG__LOADED = (1 << 12), /* file data has been loaded */
GIT_DIFF_FLAG__TO_DELETE = (1 << 16), /* delete entry during rename det. */
GIT_DIFF_FLAG__TO_SPLIT = (1 << 17), /* split entry during rename det. */
GIT_DIFF_FLAG__IS_RENAME_TARGET = (1 << 18),
GIT_DIFF_FLAG__IS_RENAME_SOURCE = (1 << 19),
GIT_DIFF_FLAG__HAS_SELF_SIMILARITY = (1 << 20),
};
#define GIT_DIFF_FLAG__CLEAR_INTERNAL(F) (F) = ((F) & 0x00FFFF)
#define GIT_DIFF__VERBOSE (1 << 30)
extern void git_diff_addref(git_diff *diff);
extern bool git_diff_delta__should_skip(
const git_diff_options *opts, const git_diff_delta *delta);
extern int git_diff__from_iterators(
git_diff **diff_ptr,
git_repository *repo,
git_iterator *old_iter,
git_iterator *new_iter,
const git_diff_options *opts);
extern int git_diff__commit(
git_diff **diff, git_repository *repo, const git_commit *commit, const git_diff_options *opts);
extern int git_diff__paired_foreach(
git_diff *idx2head,
git_diff *wd2idx,
int (*cb)(git_diff_delta *i2h, git_diff_delta *w2i, void *payload),
void *payload);
/* Merge two `git_diff`s according to the callback given by `cb`. */
typedef git_diff_delta *(*git_diff__merge_cb)(
const git_diff_delta *left,
const git_diff_delta *right,
git_pool *pool);
extern int git_diff__merge(
git_diff *onto, const git_diff *from, git_diff__merge_cb cb);
extern git_diff_delta *git_diff__merge_like_cgit(
const git_diff_delta *a,
const git_diff_delta *b,
git_pool *pool);
/* Duplicate a `git_diff_delta` out of the `git_pool` */
extern git_diff_delta *git_diff__delta_dup(
const git_diff_delta *d, git_pool *pool);
extern int git_diff__oid_for_file(
git_oid *out,
git_diff *diff,
const char *path,
uint16_t mode,
git_object_size_t size);
extern int git_diff__oid_for_entry(
git_oid *out,
git_diff *diff,
const git_index_entry *src,
uint16_t mode,
const git_oid *update_match);
/*
* Sometimes a git_diff_file will have a zero size; this attempts to
* fill in the size without loading the blob if possible. If that is
* not possible, then it will return the git_odb_object that had to be
* loaded and the caller can use it or dispose of it as needed.
*/
GIT_INLINE(int) git_diff_file__resolve_zero_size(
git_diff_file *file, git_odb_object **odb_obj, git_repository *repo)
{
int error;
git_odb *odb;
size_t len;
git_object_t type;
if ((error = git_repository_odb(&odb, repo)) < 0)
return error;
error = git_odb__read_header_or_object(
odb_obj, &len, &type, odb, &file->id);
git_odb_free(odb);
if (!error)
file->size = (git_object_size_t)len;
return error;
}
#endif
|
0 |
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2
|
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2/src/apply.c
|
/*
* Copyright (C) the libgit2 contributors. All rights reserved.
*
* This file is part of libgit2, distributed under the GNU GPL v2 with
* a Linking Exception. For full terms see the included COPYING file.
*/
#include "git2/apply.h"
#include "git2/patch.h"
#include "git2/filter.h"
#include "git2/blob.h"
#include "git2/index.h"
#include "git2/checkout.h"
#include "git2/repository.h"
#include "array.h"
#include "patch.h"
#include "futils.h"
#include "delta.h"
#include "zstream.h"
#include "reader.h"
#include "index.h"
#include "apply.h"
typedef struct {
/* The lines that we allocate ourself are allocated out of the pool.
* (Lines may have been allocated out of the diff.)
*/
git_pool pool;
git_vector lines;
} patch_image;
static int apply_err(const char *fmt, ...) GIT_FORMAT_PRINTF(1, 2);
static int apply_err(const char *fmt, ...)
{
va_list ap;
va_start(ap, fmt);
git_error_vset(GIT_ERROR_PATCH, fmt, ap);
va_end(ap);
return GIT_EAPPLYFAIL;
}
static void patch_line_init(
git_diff_line *out,
const char *in,
size_t in_len,
size_t in_offset)
{
out->content = in;
out->content_len = in_len;
out->content_offset = in_offset;
}
#define PATCH_IMAGE_INIT { GIT_POOL_INIT, GIT_VECTOR_INIT }
static int patch_image_init_fromstr(
patch_image *out, const char *in, size_t in_len)
{
git_diff_line *line;
const char *start, *end;
memset(out, 0x0, sizeof(patch_image));
if (git_pool_init(&out->pool, sizeof(git_diff_line)) < 0)
return -1;
if (!in_len)
return 0;
for (start = in; start < in + in_len; start = end) {
end = memchr(start, '\n', in_len - (start - in));
if (end == NULL)
end = in + in_len;
else if (end < in + in_len)
end++;
line = git_pool_mallocz(&out->pool, 1);
GIT_ERROR_CHECK_ALLOC(line);
if (git_vector_insert(&out->lines, line) < 0)
return -1;
patch_line_init(line, start, (end - start), (start - in));
}
return 0;
}
static void patch_image_free(patch_image *image)
{
if (image == NULL)
return;
git_pool_clear(&image->pool);
git_vector_free(&image->lines);
}
static bool match_hunk(
patch_image *image,
patch_image *preimage,
size_t linenum)
{
bool match = 0;
size_t i;
/* Ensure this hunk is within the image boundaries. */
if (git_vector_length(&preimage->lines) + linenum >
git_vector_length(&image->lines))
return 0;
match = 1;
/* Check exact match. */
for (i = 0; i < git_vector_length(&preimage->lines); i++) {
git_diff_line *preimage_line = git_vector_get(&preimage->lines, i);
git_diff_line *image_line = git_vector_get(&image->lines, linenum + i);
if (preimage_line->content_len != image_line->content_len ||
memcmp(preimage_line->content, image_line->content, image_line->content_len) != 0) {
match = 0;
break;
}
}
return match;
}
static bool find_hunk_linenum(
size_t *out,
patch_image *image,
patch_image *preimage,
size_t linenum)
{
size_t max = git_vector_length(&image->lines);
bool match;
if (linenum > max)
linenum = max;
match = match_hunk(image, preimage, linenum);
*out = linenum;
return match;
}
static int update_hunk(
patch_image *image,
size_t linenum,
patch_image *preimage,
patch_image *postimage)
{
size_t postlen = git_vector_length(&postimage->lines);
size_t prelen = git_vector_length(&preimage->lines);
size_t i;
int error = 0;
if (postlen > prelen)
error = git_vector_insert_null(
&image->lines, linenum, (postlen - prelen));
else if (prelen > postlen)
error = git_vector_remove_range(
&image->lines, linenum, (prelen - postlen));
if (error) {
git_error_set_oom();
return -1;
}
for (i = 0; i < git_vector_length(&postimage->lines); i++) {
image->lines.contents[linenum + i] =
git_vector_get(&postimage->lines, i);
}
return 0;
}
typedef struct {
git_apply_options opts;
size_t skipped_new_lines;
size_t skipped_old_lines;
} apply_hunks_ctx;
static int apply_hunk(
patch_image *image,
git_patch *patch,
git_patch_hunk *hunk,
apply_hunks_ctx *ctx)
{
patch_image preimage = PATCH_IMAGE_INIT, postimage = PATCH_IMAGE_INIT;
size_t line_num, i;
int error = 0;
if (ctx->opts.hunk_cb) {
error = ctx->opts.hunk_cb(&hunk->hunk, ctx->opts.payload);
if (error) {
if (error > 0) {
ctx->skipped_new_lines += hunk->hunk.new_lines;
ctx->skipped_old_lines += hunk->hunk.old_lines;
error = 0;
}
goto done;
}
}
for (i = 0; i < hunk->line_count; i++) {
size_t linenum = hunk->line_start + i;
git_diff_line *line = git_array_get(patch->lines, linenum), *prev;
if (!line) {
error = apply_err("preimage does not contain line %"PRIuZ, linenum);
goto done;
}
switch (line->origin) {
case GIT_DIFF_LINE_CONTEXT_EOFNL:
case GIT_DIFF_LINE_DEL_EOFNL:
case GIT_DIFF_LINE_ADD_EOFNL:
prev = i ? git_array_get(patch->lines, linenum - 1) : NULL;
if (prev && prev->content[prev->content_len - 1] == '\n')
prev->content_len -= 1;
break;
case GIT_DIFF_LINE_CONTEXT:
if ((error = git_vector_insert(&preimage.lines, line)) < 0 ||
(error = git_vector_insert(&postimage.lines, line)) < 0)
goto done;
break;
case GIT_DIFF_LINE_DELETION:
if ((error = git_vector_insert(&preimage.lines, line)) < 0)
goto done;
break;
case GIT_DIFF_LINE_ADDITION:
if ((error = git_vector_insert(&postimage.lines, line)) < 0)
goto done;
break;
}
}
if (hunk->hunk.new_start) {
line_num = hunk->hunk.new_start -
ctx->skipped_new_lines +
ctx->skipped_old_lines -
1;
} else {
line_num = 0;
}
if (!find_hunk_linenum(&line_num, image, &preimage, line_num)) {
error = apply_err("hunk at line %d did not apply",
hunk->hunk.new_start);
goto done;
}
error = update_hunk(image, line_num, &preimage, &postimage);
done:
patch_image_free(&preimage);
patch_image_free(&postimage);
return error;
}
static int apply_hunks(
git_buf *out,
const char *source,
size_t source_len,
git_patch *patch,
apply_hunks_ctx *ctx)
{
git_patch_hunk *hunk;
git_diff_line *line;
patch_image image;
size_t i;
int error = 0;
if ((error = patch_image_init_fromstr(&image, source, source_len)) < 0)
goto done;
git_array_foreach(patch->hunks, i, hunk) {
if ((error = apply_hunk(&image, patch, hunk, ctx)) < 0)
goto done;
}
git_vector_foreach(&image.lines, i, line)
git_buf_put(out, line->content, line->content_len);
done:
patch_image_free(&image);
return error;
}
static int apply_binary_delta(
git_buf *out,
const char *source,
size_t source_len,
git_diff_binary_file *binary_file)
{
git_buf inflated = GIT_BUF_INIT;
int error = 0;
/* no diff means identical contents */
if (binary_file->datalen == 0)
return git_buf_put(out, source, source_len);
error = git_zstream_inflatebuf(&inflated,
binary_file->data, binary_file->datalen);
if (!error && inflated.size != binary_file->inflatedlen) {
error = apply_err("inflated delta does not match expected length");
git_buf_dispose(out);
}
if (error < 0)
goto done;
if (binary_file->type == GIT_DIFF_BINARY_DELTA) {
void *data;
size_t data_len;
error = git_delta_apply(&data, &data_len, (void *)source, source_len,
(void *)inflated.ptr, inflated.size);
out->ptr = data;
out->size = data_len;
out->asize = data_len;
}
else if (binary_file->type == GIT_DIFF_BINARY_LITERAL) {
git_buf_swap(out, &inflated);
}
else {
error = apply_err("unknown binary delta type");
goto done;
}
done:
git_buf_dispose(&inflated);
return error;
}
static int apply_binary(
git_buf *out,
const char *source,
size_t source_len,
git_patch *patch)
{
git_buf reverse = GIT_BUF_INIT;
int error = 0;
if (!patch->binary.contains_data) {
error = apply_err("patch does not contain binary data");
goto done;
}
if (!patch->binary.old_file.datalen && !patch->binary.new_file.datalen)
goto done;
/* first, apply the new_file delta to the given source */
if ((error = apply_binary_delta(out, source, source_len,
&patch->binary.new_file)) < 0)
goto done;
/* second, apply the old_file delta to sanity check the result */
if ((error = apply_binary_delta(&reverse, out->ptr, out->size,
&patch->binary.old_file)) < 0)
goto done;
/* Verify that the resulting file with the reverse patch applied matches the source file */
if (source_len != reverse.size ||
(source_len && memcmp(source, reverse.ptr, source_len) != 0)) {
error = apply_err("binary patch did not apply cleanly");
goto done;
}
done:
if (error < 0)
git_buf_dispose(out);
git_buf_dispose(&reverse);
return error;
}
int git_apply__patch(
git_buf *contents_out,
char **filename_out,
unsigned int *mode_out,
const char *source,
size_t source_len,
git_patch *patch,
const git_apply_options *given_opts)
{
apply_hunks_ctx ctx = { GIT_APPLY_OPTIONS_INIT };
char *filename = NULL;
unsigned int mode = 0;
int error = 0;
GIT_ASSERT_ARG(contents_out);
GIT_ASSERT_ARG(filename_out);
GIT_ASSERT_ARG(mode_out);
GIT_ASSERT_ARG(source || !source_len);
GIT_ASSERT_ARG(patch);
if (given_opts)
memcpy(&ctx.opts, given_opts, sizeof(git_apply_options));
*filename_out = NULL;
*mode_out = 0;
if (patch->delta->status != GIT_DELTA_DELETED) {
const git_diff_file *newfile = &patch->delta->new_file;
filename = git__strdup(newfile->path);
mode = newfile->mode ?
newfile->mode : GIT_FILEMODE_BLOB;
}
if (patch->delta->flags & GIT_DIFF_FLAG_BINARY)
error = apply_binary(contents_out, source, source_len, patch);
else if (patch->hunks.size)
error = apply_hunks(contents_out, source, source_len, patch, &ctx);
else
error = git_buf_put(contents_out, source, source_len);
if (error)
goto done;
if (patch->delta->status == GIT_DELTA_DELETED &&
git_buf_len(contents_out) > 0) {
error = apply_err("removal patch leaves file contents");
goto done;
}
*filename_out = filename;
*mode_out = mode;
done:
if (error < 0)
git__free(filename);
return error;
}
static int apply_one(
git_repository *repo,
git_reader *preimage_reader,
git_index *preimage,
git_reader *postimage_reader,
git_index *postimage,
git_diff *diff,
git_strmap *removed_paths,
size_t i,
const git_apply_options *opts)
{
git_patch *patch = NULL;
git_buf pre_contents = GIT_BUF_INIT, post_contents = GIT_BUF_INIT;
const git_diff_delta *delta;
char *filename = NULL;
unsigned int mode;
git_oid pre_id, post_id;
git_filemode_t pre_filemode;
git_index_entry pre_entry, post_entry;
bool skip_preimage = false;
int error;
if ((error = git_patch_from_diff(&patch, diff, i)) < 0)
goto done;
delta = git_patch_get_delta(patch);
if (opts->delta_cb) {
error = opts->delta_cb(delta, opts->payload);
if (error) {
if (error > 0)
error = 0;
goto done;
}
}
/*
* Ensure that the file has not been deleted or renamed if we're
* applying a modification delta.
*/
if (delta->status != GIT_DELTA_RENAMED &&
delta->status != GIT_DELTA_ADDED) {
if (git_strmap_exists(removed_paths, delta->old_file.path)) {
error = apply_err("path '%s' has been renamed or deleted", delta->old_file.path);
goto done;
}
}
/*
* We may be applying a second delta to an already seen file. If so,
* use the already modified data in the postimage instead of the
* content from the index or working directory. (Don't do this in
* the case of a rename, which must be specified before additional
* deltas since we apply deltas to the target filename.)
*/
if (delta->status != GIT_DELTA_RENAMED) {
if ((error = git_reader_read(&pre_contents, &pre_id, &pre_filemode,
postimage_reader, delta->old_file.path)) == 0) {
skip_preimage = true;
} else if (error == GIT_ENOTFOUND) {
git_error_clear();
error = 0;
} else {
goto done;
}
}
if (!skip_preimage && delta->status != GIT_DELTA_ADDED) {
error = git_reader_read(&pre_contents, &pre_id, &pre_filemode,
preimage_reader, delta->old_file.path);
/* ENOTFOUND means the preimage was not found; apply failed. */
if (error == GIT_ENOTFOUND)
error = GIT_EAPPLYFAIL;
/* When applying to BOTH, the index did not match the workdir. */
if (error == GIT_READER_MISMATCH)
error = apply_err("%s: does not match index", delta->old_file.path);
if (error < 0)
goto done;
/*
* We need to populate the preimage data structure with the
* contents that we are using as the preimage for this file.
* This allows us to apply patches to files that have been
* modified in the working directory. During checkout,
* we will use this expected preimage as the baseline, and
* limit checkout to only the paths affected by patch
* application. (Without this, we would fail to write the
* postimage contents to any file that had been modified
* from HEAD on-disk, even if the patch application succeeded.)
* Use the contents from the delta where available - some
* fields may not be available, like the old file mode (eg in
* an exact rename situation) so trust the patch parsing to
* validate and use the preimage data in that case.
*/
if (preimage) {
memset(&pre_entry, 0, sizeof(git_index_entry));
pre_entry.path = delta->old_file.path;
pre_entry.mode = delta->old_file.mode ? delta->old_file.mode : pre_filemode;
git_oid_cpy(&pre_entry.id, &pre_id);
if ((error = git_index_add(preimage, &pre_entry)) < 0)
goto done;
}
}
if (delta->status != GIT_DELTA_DELETED) {
if ((error = git_apply__patch(&post_contents, &filename, &mode,
pre_contents.ptr, pre_contents.size, patch, opts)) < 0 ||
(error = git_blob_create_from_buffer(&post_id, repo,
post_contents.ptr, post_contents.size)) < 0)
goto done;
memset(&post_entry, 0, sizeof(git_index_entry));
post_entry.path = filename;
post_entry.mode = mode;
git_oid_cpy(&post_entry.id, &post_id);
if ((error = git_index_add(postimage, &post_entry)) < 0)
goto done;
}
if (delta->status == GIT_DELTA_RENAMED ||
delta->status == GIT_DELTA_DELETED)
error = git_strmap_set(removed_paths, delta->old_file.path, (char *) delta->old_file.path);
if (delta->status == GIT_DELTA_RENAMED ||
delta->status == GIT_DELTA_ADDED)
git_strmap_delete(removed_paths, delta->new_file.path);
done:
git_buf_dispose(&pre_contents);
git_buf_dispose(&post_contents);
git__free(filename);
git_patch_free(patch);
return error;
}
static int apply_deltas(
git_repository *repo,
git_reader *pre_reader,
git_index *preimage,
git_reader *post_reader,
git_index *postimage,
git_diff *diff,
const git_apply_options *opts)
{
git_strmap *removed_paths;
size_t i;
int error = 0;
if (git_strmap_new(&removed_paths) < 0)
return -1;
for (i = 0; i < git_diff_num_deltas(diff); i++) {
if ((error = apply_one(repo, pre_reader, preimage, post_reader, postimage, diff, removed_paths, i, opts)) < 0)
goto done;
}
done:
git_strmap_free(removed_paths);
return error;
}
int git_apply_to_tree(
git_index **out,
git_repository *repo,
git_tree *preimage,
git_diff *diff,
const git_apply_options *given_opts)
{
git_index *postimage = NULL;
git_reader *pre_reader = NULL, *post_reader = NULL;
git_apply_options opts = GIT_APPLY_OPTIONS_INIT;
const git_diff_delta *delta;
size_t i;
int error = 0;
GIT_ASSERT_ARG(out);
GIT_ASSERT_ARG(repo);
GIT_ASSERT_ARG(preimage);
GIT_ASSERT_ARG(diff);
*out = NULL;
if (given_opts)
memcpy(&opts, given_opts, sizeof(git_apply_options));
if ((error = git_reader_for_tree(&pre_reader, preimage)) < 0)
goto done;
/*
* put the current tree into the postimage as-is - the diff will
* replace any entries contained therein
*/
if ((error = git_index_new(&postimage)) < 0 ||
(error = git_index_read_tree(postimage, preimage)) < 0 ||
(error = git_reader_for_index(&post_reader, repo, postimage)) < 0)
goto done;
/*
* Remove the old paths from the index before applying diffs -
* we need to do a full pass to remove them before adding deltas,
* in order to handle rename situations.
*/
for (i = 0; i < git_diff_num_deltas(diff); i++) {
delta = git_diff_get_delta(diff, i);
if (delta->status == GIT_DELTA_DELETED ||
delta->status == GIT_DELTA_RENAMED) {
if ((error = git_index_remove(postimage,
delta->old_file.path, 0)) < 0)
goto done;
}
}
if ((error = apply_deltas(repo, pre_reader, NULL, post_reader, postimage, diff, &opts)) < 0)
goto done;
*out = postimage;
done:
if (error < 0)
git_index_free(postimage);
git_reader_free(pre_reader);
git_reader_free(post_reader);
return error;
}
static int git_apply__to_workdir(
git_repository *repo,
git_diff *diff,
git_index *preimage,
git_index *postimage,
git_apply_location_t location,
git_apply_options *opts)
{
git_vector paths = GIT_VECTOR_INIT;
git_checkout_options checkout_opts = GIT_CHECKOUT_OPTIONS_INIT;
const git_diff_delta *delta;
size_t i;
int error;
GIT_UNUSED(opts);
/*
* Limit checkout to the paths affected by the diff; this ensures
* that other modifications in the working directory are unaffected.
*/
if ((error = git_vector_init(&paths, git_diff_num_deltas(diff), NULL)) < 0)
goto done;
for (i = 0; i < git_diff_num_deltas(diff); i++) {
delta = git_diff_get_delta(diff, i);
if ((error = git_vector_insert(&paths, (void *)delta->old_file.path)) < 0)
goto done;
if (strcmp(delta->old_file.path, delta->new_file.path) &&
(error = git_vector_insert(&paths, (void *)delta->new_file.path)) < 0)
goto done;
}
checkout_opts.checkout_strategy |= GIT_CHECKOUT_SAFE;
checkout_opts.checkout_strategy |= GIT_CHECKOUT_DISABLE_PATHSPEC_MATCH;
checkout_opts.checkout_strategy |= GIT_CHECKOUT_DONT_WRITE_INDEX;
if (location == GIT_APPLY_LOCATION_WORKDIR)
checkout_opts.checkout_strategy |= GIT_CHECKOUT_DONT_UPDATE_INDEX;
checkout_opts.paths.strings = (char **)paths.contents;
checkout_opts.paths.count = paths.length;
checkout_opts.baseline_index = preimage;
error = git_checkout_index(repo, postimage, &checkout_opts);
done:
git_vector_free(&paths);
return error;
}
static int git_apply__to_index(
git_repository *repo,
git_diff *diff,
git_index *preimage,
git_index *postimage,
git_apply_options *opts)
{
git_index *index = NULL;
const git_diff_delta *delta;
const git_index_entry *entry;
size_t i;
int error;
GIT_UNUSED(preimage);
GIT_UNUSED(opts);
if ((error = git_repository_index(&index, repo)) < 0)
goto done;
/* Remove deleted (or renamed) paths from the index. */
for (i = 0; i < git_diff_num_deltas(diff); i++) {
delta = git_diff_get_delta(diff, i);
if (delta->status == GIT_DELTA_DELETED ||
delta->status == GIT_DELTA_RENAMED) {
if ((error = git_index_remove(index, delta->old_file.path, 0)) < 0)
goto done;
}
}
/* Then add the changes back to the index. */
for (i = 0; i < git_index_entrycount(postimage); i++) {
entry = git_index_get_byindex(postimage, i);
if ((error = git_index_add(index, entry)) < 0)
goto done;
}
done:
git_index_free(index);
return error;
}
int git_apply_options_init(git_apply_options *opts, unsigned int version)
{
GIT_ASSERT_ARG(opts);
GIT_INIT_STRUCTURE_FROM_TEMPLATE(
opts, version, git_apply_options, GIT_APPLY_OPTIONS_INIT);
return 0;
}
/*
* Handle the three application options ("locations"):
*
* GIT_APPLY_LOCATION_WORKDIR: the default, emulates `git apply`.
* Applies the diff only to the workdir items and ignores the index
* entirely.
*
* GIT_APPLY_LOCATION_INDEX: emulates `git apply --cached`.
* Applies the diff only to the index items and ignores the workdir
* completely.
*
* GIT_APPLY_LOCATION_BOTH: emulates `git apply --index`.
* Applies the diff to both the index items and the working directory
* items.
*/
int git_apply(
git_repository *repo,
git_diff *diff,
git_apply_location_t location,
const git_apply_options *given_opts)
{
git_indexwriter indexwriter = GIT_INDEXWRITER_INIT;
git_index *index = NULL, *preimage = NULL, *postimage = NULL;
git_reader *pre_reader = NULL, *post_reader = NULL;
git_apply_options opts = GIT_APPLY_OPTIONS_INIT;
int error = GIT_EINVALID;
GIT_ASSERT_ARG(repo);
GIT_ASSERT_ARG(diff);
GIT_ERROR_CHECK_VERSION(
given_opts, GIT_APPLY_OPTIONS_VERSION, "git_apply_options");
if (given_opts)
memcpy(&opts, given_opts, sizeof(git_apply_options));
/*
* by default, we apply a patch directly to the working directory;
* in `--cached` or `--index` mode, we apply to the contents already
* in the index.
*/
switch (location) {
case GIT_APPLY_LOCATION_BOTH:
error = git_reader_for_workdir(&pre_reader, repo, true);
break;
case GIT_APPLY_LOCATION_INDEX:
error = git_reader_for_index(&pre_reader, repo, NULL);
break;
case GIT_APPLY_LOCATION_WORKDIR:
error = git_reader_for_workdir(&pre_reader, repo, false);
break;
default:
GIT_ASSERT(false);
}
if (error < 0)
goto done;
/*
* Build the preimage and postimage (differences). Note that
* this is not the complete preimage or postimage, it only
* contains the files affected by the patch. We want to avoid
* having the full repo index, so we will limit our checkout
* to only write these files that were affected by the diff.
*/
if ((error = git_index_new(&preimage)) < 0 ||
(error = git_index_new(&postimage)) < 0 ||
(error = git_reader_for_index(&post_reader, repo, postimage)) < 0)
goto done;
if (!(opts.flags & GIT_APPLY_CHECK))
if ((error = git_repository_index(&index, repo)) < 0 ||
(error = git_indexwriter_init(&indexwriter, index)) < 0)
goto done;
if ((error = apply_deltas(repo, pre_reader, preimage, post_reader, postimage, diff, &opts)) < 0)
goto done;
if ((opts.flags & GIT_APPLY_CHECK))
goto done;
switch (location) {
case GIT_APPLY_LOCATION_BOTH:
error = git_apply__to_workdir(repo, diff, preimage, postimage, location, &opts);
break;
case GIT_APPLY_LOCATION_INDEX:
error = git_apply__to_index(repo, diff, preimage, postimage, &opts);
break;
case GIT_APPLY_LOCATION_WORKDIR:
error = git_apply__to_workdir(repo, diff, preimage, postimage, location, &opts);
break;
default:
GIT_ASSERT(false);
}
if (error < 0)
goto done;
error = git_indexwriter_commit(&indexwriter);
done:
git_indexwriter_cleanup(&indexwriter);
git_index_free(postimage);
git_index_free(preimage);
git_index_free(index);
git_reader_free(pre_reader);
git_reader_free(post_reader);
return error;
}
|
0 |
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2
|
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2/src/patch_generate.c
|
/*
* Copyright (C) the libgit2 contributors. All rights reserved.
*
* This file is part of libgit2, distributed under the GNU GPL v2 with
* a Linking Exception. For full terms see the included COPYING file.
*/
#include "patch_generate.h"
#include "git2/blob.h"
#include "diff.h"
#include "diff_generate.h"
#include "diff_file.h"
#include "diff_driver.h"
#include "diff_xdiff.h"
#include "delta.h"
#include "zstream.h"
#include "futils.h"
static void diff_output_init(
git_patch_generated_output *, const git_diff_options *, git_diff_file_cb,
git_diff_binary_cb, git_diff_hunk_cb, git_diff_line_cb, void*);
static void diff_output_to_patch(
git_patch_generated_output *, git_patch_generated *);
static void patch_generated_free(git_patch *p)
{
git_patch_generated *patch = (git_patch_generated *)p;
git_array_clear(patch->base.lines);
git_array_clear(patch->base.hunks);
git__free((char *)patch->base.binary.old_file.data);
git__free((char *)patch->base.binary.new_file.data);
git_diff_file_content__clear(&patch->ofile);
git_diff_file_content__clear(&patch->nfile);
git_diff_free(patch->diff); /* decrements refcount */
patch->diff = NULL;
git_pool_clear(&patch->flattened);
git__free((char *)patch->base.diff_opts.old_prefix);
git__free((char *)patch->base.diff_opts.new_prefix);
if (patch->flags & GIT_PATCH_GENERATED_ALLOCATED)
git__free(patch);
}
static void patch_generated_update_binary(git_patch_generated *patch)
{
if ((patch->base.delta->flags & DIFF_FLAGS_KNOWN_BINARY) != 0)
return;
if ((patch->ofile.file->flags & GIT_DIFF_FLAG_BINARY) != 0 ||
(patch->nfile.file->flags & GIT_DIFF_FLAG_BINARY) != 0)
patch->base.delta->flags |= GIT_DIFF_FLAG_BINARY;
else if (patch->ofile.file->size > GIT_XDIFF_MAX_SIZE ||
patch->nfile.file->size > GIT_XDIFF_MAX_SIZE)
patch->base.delta->flags |= GIT_DIFF_FLAG_BINARY;
else if ((patch->ofile.file->flags & DIFF_FLAGS_NOT_BINARY) != 0 &&
(patch->nfile.file->flags & DIFF_FLAGS_NOT_BINARY) != 0)
patch->base.delta->flags |= GIT_DIFF_FLAG_NOT_BINARY;
}
static void patch_generated_init_common(git_patch_generated *patch)
{
patch->base.free_fn = patch_generated_free;
patch_generated_update_binary(patch);
patch->flags |= GIT_PATCH_GENERATED_INITIALIZED;
if (patch->diff)
git_diff_addref(patch->diff);
}
static int patch_generated_normalize_options(
git_diff_options *out,
const git_diff_options *opts)
{
if (opts) {
GIT_ERROR_CHECK_VERSION(opts, GIT_DIFF_OPTIONS_VERSION, "git_diff_options");
memcpy(out, opts, sizeof(git_diff_options));
} else {
git_diff_options default_opts = GIT_DIFF_OPTIONS_INIT;
memcpy(out, &default_opts, sizeof(git_diff_options));
}
out->old_prefix = opts && opts->old_prefix ?
git__strdup(opts->old_prefix) :
git__strdup(DIFF_OLD_PREFIX_DEFAULT);
out->new_prefix = opts && opts->new_prefix ?
git__strdup(opts->new_prefix) :
git__strdup(DIFF_NEW_PREFIX_DEFAULT);
GIT_ERROR_CHECK_ALLOC(out->old_prefix);
GIT_ERROR_CHECK_ALLOC(out->new_prefix);
return 0;
}
static int patch_generated_init(
git_patch_generated *patch, git_diff *diff, size_t delta_index)
{
int error = 0;
memset(patch, 0, sizeof(*patch));
patch->diff = diff;
patch->base.repo = diff->repo;
patch->base.delta = git_vector_get(&diff->deltas, delta_index);
patch->delta_index = delta_index;
if ((error = patch_generated_normalize_options(
&patch->base.diff_opts, &diff->opts)) < 0 ||
(error = git_diff_file_content__init_from_diff(
&patch->ofile, diff, patch->base.delta, true)) < 0 ||
(error = git_diff_file_content__init_from_diff(
&patch->nfile, diff, patch->base.delta, false)) < 0)
return error;
patch_generated_init_common(patch);
return 0;
}
static int patch_generated_alloc_from_diff(
git_patch_generated **out, git_diff *diff, size_t delta_index)
{
int error;
git_patch_generated *patch = git__calloc(1, sizeof(git_patch_generated));
GIT_ERROR_CHECK_ALLOC(patch);
if (!(error = patch_generated_init(patch, diff, delta_index))) {
patch->flags |= GIT_PATCH_GENERATED_ALLOCATED;
GIT_REFCOUNT_INC(&patch->base);
} else {
git__free(patch);
patch = NULL;
}
*out = patch;
return error;
}
GIT_INLINE(bool) should_skip_binary(git_patch_generated *patch, git_diff_file *file)
{
if ((patch->base.diff_opts.flags & GIT_DIFF_SHOW_BINARY) != 0)
return false;
return (file->flags & GIT_DIFF_FLAG_BINARY) != 0;
}
static bool patch_generated_diffable(git_patch_generated *patch)
{
size_t olen, nlen;
if (patch->base.delta->status == GIT_DELTA_UNMODIFIED)
return false;
/* if we've determined this to be binary (and we are not showing binary
* data) then we have skipped loading the map data. instead, query the
* file data itself.
*/
if ((patch->base.delta->flags & GIT_DIFF_FLAG_BINARY) != 0 &&
(patch->base.diff_opts.flags & GIT_DIFF_SHOW_BINARY) == 0) {
olen = (size_t)patch->ofile.file->size;
nlen = (size_t)patch->nfile.file->size;
} else {
olen = patch->ofile.map.len;
nlen = patch->nfile.map.len;
}
/* if both sides are empty, files are identical */
if (!olen && !nlen)
return false;
/* otherwise, check the file sizes and the oid */
return (olen != nlen ||
!git_oid_equal(&patch->ofile.file->id, &patch->nfile.file->id));
}
static int patch_generated_load(git_patch_generated *patch, git_patch_generated_output *output)
{
int error = 0;
bool incomplete_data;
if ((patch->flags & GIT_PATCH_GENERATED_LOADED) != 0)
return 0;
/* if no hunk and data callbacks and user doesn't care if data looks
* binary, then there is no need to actually load the data
*/
if ((patch->ofile.opts_flags & GIT_DIFF_SKIP_BINARY_CHECK) != 0 &&
output && !output->binary_cb && !output->hunk_cb && !output->data_cb)
return 0;
incomplete_data =
(((patch->ofile.flags & GIT_DIFF_FLAG__NO_DATA) != 0 ||
(patch->ofile.file->flags & GIT_DIFF_FLAG_VALID_ID) != 0) &&
((patch->nfile.flags & GIT_DIFF_FLAG__NO_DATA) != 0 ||
(patch->nfile.file->flags & GIT_DIFF_FLAG_VALID_ID) != 0));
if ((error = git_diff_file_content__load(
&patch->ofile, &patch->base.diff_opts)) < 0 ||
(error = git_diff_file_content__load(
&patch->nfile, &patch->base.diff_opts)) < 0 ||
should_skip_binary(patch, patch->nfile.file))
goto cleanup;
/* if previously missing an oid, and now that we have it the two sides
* are the same (and not submodules), update MODIFIED -> UNMODIFIED
*/
if (incomplete_data &&
patch->ofile.file->mode == patch->nfile.file->mode &&
patch->ofile.file->mode != GIT_FILEMODE_COMMIT &&
git_oid_equal(&patch->ofile.file->id, &patch->nfile.file->id) &&
patch->base.delta->status == GIT_DELTA_MODIFIED) /* not RENAMED/COPIED! */
patch->base.delta->status = GIT_DELTA_UNMODIFIED;
cleanup:
patch_generated_update_binary(patch);
if (!error) {
if (patch_generated_diffable(patch))
patch->flags |= GIT_PATCH_GENERATED_DIFFABLE;
patch->flags |= GIT_PATCH_GENERATED_LOADED;
}
return error;
}
static int patch_generated_invoke_file_callback(
git_patch_generated *patch, git_patch_generated_output *output)
{
float progress = patch->diff ?
((float)patch->delta_index / patch->diff->deltas.length) : 1.0f;
if (!output->file_cb)
return 0;
return git_error_set_after_callback_function(
output->file_cb(patch->base.delta, progress, output->payload),
"git_patch");
}
static int create_binary(
git_diff_binary_t *out_type,
char **out_data,
size_t *out_datalen,
size_t *out_inflatedlen,
const char *a_data,
size_t a_datalen,
const char *b_data,
size_t b_datalen)
{
git_buf deflate = GIT_BUF_INIT, delta = GIT_BUF_INIT;
size_t delta_data_len = 0;
int error;
/* The git_delta function accepts unsigned long only */
if (!git__is_ulong(a_datalen) || !git__is_ulong(b_datalen))
return GIT_EBUFS;
if ((error = git_zstream_deflatebuf(&deflate, b_data, b_datalen)) < 0)
goto done;
/* The git_delta function accepts unsigned long only */
if (!git__is_ulong(deflate.size)) {
error = GIT_EBUFS;
goto done;
}
if (a_datalen && b_datalen) {
void *delta_data;
error = git_delta(&delta_data, &delta_data_len,
a_data, a_datalen,
b_data, b_datalen,
deflate.size);
if (error == 0) {
error = git_zstream_deflatebuf(
&delta, delta_data, delta_data_len);
git__free(delta_data);
} else if (error == GIT_EBUFS) {
error = 0;
}
if (error < 0)
goto done;
}
if (delta.size && delta.size < deflate.size) {
*out_type = GIT_DIFF_BINARY_DELTA;
*out_datalen = delta.size;
*out_data = git_buf_detach(&delta);
*out_inflatedlen = delta_data_len;
} else {
*out_type = GIT_DIFF_BINARY_LITERAL;
*out_datalen = deflate.size;
*out_data = git_buf_detach(&deflate);
*out_inflatedlen = b_datalen;
}
done:
git_buf_dispose(&deflate);
git_buf_dispose(&delta);
return error;
}
static int diff_binary(git_patch_generated_output *output, git_patch_generated *patch)
{
git_diff_binary binary = {0};
const char *old_data = patch->ofile.map.data;
const char *new_data = patch->nfile.map.data;
size_t old_len = patch->ofile.map.len,
new_len = patch->nfile.map.len;
int error;
/* Only load contents if the user actually wants to diff
* binary files. */
if (patch->base.diff_opts.flags & GIT_DIFF_SHOW_BINARY) {
binary.contains_data = 1;
/* Create the old->new delta (as the "new" side of the patch),
* and the new->old delta (as the "old" side)
*/
if ((error = create_binary(&binary.old_file.type,
(char **)&binary.old_file.data,
&binary.old_file.datalen,
&binary.old_file.inflatedlen,
new_data, new_len, old_data, old_len)) < 0 ||
(error = create_binary(&binary.new_file.type,
(char **)&binary.new_file.data,
&binary.new_file.datalen,
&binary.new_file.inflatedlen,
old_data, old_len, new_data, new_len)) < 0)
return error;
}
error = git_error_set_after_callback_function(
output->binary_cb(patch->base.delta, &binary, output->payload),
"git_patch");
git__free((char *) binary.old_file.data);
git__free((char *) binary.new_file.data);
return error;
}
static int patch_generated_create(
git_patch_generated *patch,
git_patch_generated_output *output)
{
int error = 0;
if ((patch->flags & GIT_PATCH_GENERATED_DIFFED) != 0)
return 0;
/* if we are not looking at the binary or text data, don't do the diff */
if (!output->binary_cb && !output->hunk_cb && !output->data_cb)
return 0;
if ((patch->flags & GIT_PATCH_GENERATED_LOADED) == 0 &&
(error = patch_generated_load(patch, output)) < 0)
return error;
if ((patch->flags & GIT_PATCH_GENERATED_DIFFABLE) == 0)
return 0;
if ((patch->base.delta->flags & GIT_DIFF_FLAG_BINARY) != 0) {
if (output->binary_cb)
error = diff_binary(output, patch);
}
else {
if (output->diff_cb)
error = output->diff_cb(output, patch);
}
patch->flags |= GIT_PATCH_GENERATED_DIFFED;
return error;
}
static int diff_required(git_diff *diff, const char *action)
{
if (diff)
return 0;
git_error_set(GIT_ERROR_INVALID, "must provide valid diff to %s", action);
return -1;
}
typedef struct {
git_patch_generated patch;
git_diff_delta delta;
char paths[GIT_FLEX_ARRAY];
} patch_generated_with_delta;
static int diff_single_generate(patch_generated_with_delta *pd, git_xdiff_output *xo)
{
int error = 0;
git_patch_generated *patch = &pd->patch;
bool has_old = ((patch->ofile.flags & GIT_DIFF_FLAG__NO_DATA) == 0);
bool has_new = ((patch->nfile.flags & GIT_DIFF_FLAG__NO_DATA) == 0);
pd->delta.status = has_new ?
(has_old ? GIT_DELTA_MODIFIED : GIT_DELTA_ADDED) :
(has_old ? GIT_DELTA_DELETED : GIT_DELTA_UNTRACKED);
if (git_oid_equal(&patch->nfile.file->id, &patch->ofile.file->id))
pd->delta.status = GIT_DELTA_UNMODIFIED;
patch->base.delta = &pd->delta;
patch_generated_init_common(patch);
if (pd->delta.status == GIT_DELTA_UNMODIFIED &&
!(patch->ofile.opts_flags & GIT_DIFF_INCLUDE_UNMODIFIED)) {
/* Even empty patches are flagged as binary, and even though
* there's no difference, we flag this as "containing data"
* (the data is known to be empty, as opposed to wholly unknown).
*/
if (patch->base.diff_opts.flags & GIT_DIFF_SHOW_BINARY)
patch->base.binary.contains_data = 1;
return error;
}
error = patch_generated_invoke_file_callback(patch, (git_patch_generated_output *)xo);
if (!error)
error = patch_generated_create(patch, (git_patch_generated_output *)xo);
return error;
}
static int patch_generated_from_sources(
patch_generated_with_delta *pd,
git_xdiff_output *xo,
git_diff_file_content_src *oldsrc,
git_diff_file_content_src *newsrc,
const git_diff_options *opts)
{
int error = 0;
git_repository *repo =
oldsrc->blob ? git_blob_owner(oldsrc->blob) :
newsrc->blob ? git_blob_owner(newsrc->blob) : NULL;
git_diff_file *lfile = &pd->delta.old_file, *rfile = &pd->delta.new_file;
git_diff_file_content *ldata = &pd->patch.ofile, *rdata = &pd->patch.nfile;
if ((error = patch_generated_normalize_options(&pd->patch.base.diff_opts, opts)) < 0)
return error;
if (opts && (opts->flags & GIT_DIFF_REVERSE) != 0) {
void *tmp = lfile; lfile = rfile; rfile = tmp;
tmp = ldata; ldata = rdata; rdata = tmp;
}
pd->patch.base.delta = &pd->delta;
if (!oldsrc->as_path) {
if (newsrc->as_path)
oldsrc->as_path = newsrc->as_path;
else
oldsrc->as_path = newsrc->as_path = "file";
}
else if (!newsrc->as_path)
newsrc->as_path = oldsrc->as_path;
lfile->path = oldsrc->as_path;
rfile->path = newsrc->as_path;
if ((error = git_diff_file_content__init_from_src(
ldata, repo, opts, oldsrc, lfile)) < 0 ||
(error = git_diff_file_content__init_from_src(
rdata, repo, opts, newsrc, rfile)) < 0)
return error;
return diff_single_generate(pd, xo);
}
static int patch_generated_with_delta_alloc(
patch_generated_with_delta **out,
const char **old_path,
const char **new_path)
{
patch_generated_with_delta *pd;
size_t old_len = *old_path ? strlen(*old_path) : 0;
size_t new_len = *new_path ? strlen(*new_path) : 0;
size_t alloc_len;
GIT_ERROR_CHECK_ALLOC_ADD(&alloc_len, sizeof(*pd), old_len);
GIT_ERROR_CHECK_ALLOC_ADD(&alloc_len, alloc_len, new_len);
GIT_ERROR_CHECK_ALLOC_ADD(&alloc_len, alloc_len, 2);
*out = pd = git__calloc(1, alloc_len);
GIT_ERROR_CHECK_ALLOC(pd);
pd->patch.flags = GIT_PATCH_GENERATED_ALLOCATED;
if (*old_path) {
memcpy(&pd->paths[0], *old_path, old_len);
*old_path = &pd->paths[0];
} else if (*new_path)
*old_path = &pd->paths[old_len + 1];
if (*new_path) {
memcpy(&pd->paths[old_len + 1], *new_path, new_len);
*new_path = &pd->paths[old_len + 1];
} else if (*old_path)
*new_path = &pd->paths[0];
return 0;
}
static int diff_from_sources(
git_diff_file_content_src *oldsrc,
git_diff_file_content_src *newsrc,
const git_diff_options *opts,
git_diff_file_cb file_cb,
git_diff_binary_cb binary_cb,
git_diff_hunk_cb hunk_cb,
git_diff_line_cb data_cb,
void *payload)
{
int error = 0;
patch_generated_with_delta pd;
git_xdiff_output xo;
memset(&xo, 0, sizeof(xo));
diff_output_init(
&xo.output, opts, file_cb, binary_cb, hunk_cb, data_cb, payload);
git_xdiff_init(&xo, opts);
memset(&pd, 0, sizeof(pd));
error = patch_generated_from_sources(&pd, &xo, oldsrc, newsrc, opts);
git_patch_free(&pd.patch.base);
return error;
}
static int patch_from_sources(
git_patch **out,
git_diff_file_content_src *oldsrc,
git_diff_file_content_src *newsrc,
const git_diff_options *opts)
{
int error = 0;
patch_generated_with_delta *pd;
git_xdiff_output xo;
GIT_ASSERT_ARG(out);
*out = NULL;
if ((error = patch_generated_with_delta_alloc(
&pd, &oldsrc->as_path, &newsrc->as_path)) < 0)
return error;
memset(&xo, 0, sizeof(xo));
diff_output_to_patch(&xo.output, &pd->patch);
git_xdiff_init(&xo, opts);
if (!(error = patch_generated_from_sources(pd, &xo, oldsrc, newsrc, opts)))
*out = (git_patch *)pd;
else
git_patch_free((git_patch *)pd);
return error;
}
int git_diff_blobs(
const git_blob *old_blob,
const char *old_path,
const git_blob *new_blob,
const char *new_path,
const git_diff_options *opts,
git_diff_file_cb file_cb,
git_diff_binary_cb binary_cb,
git_diff_hunk_cb hunk_cb,
git_diff_line_cb data_cb,
void *payload)
{
git_diff_file_content_src osrc =
GIT_DIFF_FILE_CONTENT_SRC__BLOB(old_blob, old_path);
git_diff_file_content_src nsrc =
GIT_DIFF_FILE_CONTENT_SRC__BLOB(new_blob, new_path);
return diff_from_sources(
&osrc, &nsrc, opts, file_cb, binary_cb, hunk_cb, data_cb, payload);
}
int git_patch_from_blobs(
git_patch **out,
const git_blob *old_blob,
const char *old_path,
const git_blob *new_blob,
const char *new_path,
const git_diff_options *opts)
{
git_diff_file_content_src osrc =
GIT_DIFF_FILE_CONTENT_SRC__BLOB(old_blob, old_path);
git_diff_file_content_src nsrc =
GIT_DIFF_FILE_CONTENT_SRC__BLOB(new_blob, new_path);
return patch_from_sources(out, &osrc, &nsrc, opts);
}
int git_diff_blob_to_buffer(
const git_blob *old_blob,
const char *old_path,
const char *buf,
size_t buflen,
const char *buf_path,
const git_diff_options *opts,
git_diff_file_cb file_cb,
git_diff_binary_cb binary_cb,
git_diff_hunk_cb hunk_cb,
git_diff_line_cb data_cb,
void *payload)
{
git_diff_file_content_src osrc =
GIT_DIFF_FILE_CONTENT_SRC__BLOB(old_blob, old_path);
git_diff_file_content_src nsrc =
GIT_DIFF_FILE_CONTENT_SRC__BUF(buf, buflen, buf_path);
return diff_from_sources(
&osrc, &nsrc, opts, file_cb, binary_cb, hunk_cb, data_cb, payload);
}
int git_patch_from_blob_and_buffer(
git_patch **out,
const git_blob *old_blob,
const char *old_path,
const void *buf,
size_t buflen,
const char *buf_path,
const git_diff_options *opts)
{
git_diff_file_content_src osrc =
GIT_DIFF_FILE_CONTENT_SRC__BLOB(old_blob, old_path);
git_diff_file_content_src nsrc =
GIT_DIFF_FILE_CONTENT_SRC__BUF(buf, buflen, buf_path);
return patch_from_sources(out, &osrc, &nsrc, opts);
}
int git_diff_buffers(
const void *old_buf,
size_t old_len,
const char *old_path,
const void *new_buf,
size_t new_len,
const char *new_path,
const git_diff_options *opts,
git_diff_file_cb file_cb,
git_diff_binary_cb binary_cb,
git_diff_hunk_cb hunk_cb,
git_diff_line_cb data_cb,
void *payload)
{
git_diff_file_content_src osrc =
GIT_DIFF_FILE_CONTENT_SRC__BUF(old_buf, old_len, old_path);
git_diff_file_content_src nsrc =
GIT_DIFF_FILE_CONTENT_SRC__BUF(new_buf, new_len, new_path);
return diff_from_sources(
&osrc, &nsrc, opts, file_cb, binary_cb, hunk_cb, data_cb, payload);
}
int git_patch_from_buffers(
git_patch **out,
const void *old_buf,
size_t old_len,
const char *old_path,
const void *new_buf,
size_t new_len,
const char *new_path,
const git_diff_options *opts)
{
git_diff_file_content_src osrc =
GIT_DIFF_FILE_CONTENT_SRC__BUF(old_buf, old_len, old_path);
git_diff_file_content_src nsrc =
GIT_DIFF_FILE_CONTENT_SRC__BUF(new_buf, new_len, new_path);
return patch_from_sources(out, &osrc, &nsrc, opts);
}
int git_patch_generated_from_diff(
git_patch **patch_ptr, git_diff *diff, size_t idx)
{
int error = 0;
git_xdiff_output xo;
git_diff_delta *delta = NULL;
git_patch_generated *patch = NULL;
if (patch_ptr) *patch_ptr = NULL;
if (diff_required(diff, "git_patch_from_diff") < 0)
return -1;
delta = git_vector_get(&diff->deltas, idx);
if (!delta) {
git_error_set(GIT_ERROR_INVALID, "index out of range for delta in diff");
return GIT_ENOTFOUND;
}
if (git_diff_delta__should_skip(&diff->opts, delta))
return 0;
/* don't load the patch data unless we need it for binary check */
if (!patch_ptr &&
((delta->flags & DIFF_FLAGS_KNOWN_BINARY) != 0 ||
(diff->opts.flags & GIT_DIFF_SKIP_BINARY_CHECK) != 0))
return 0;
if ((error = patch_generated_alloc_from_diff(&patch, diff, idx)) < 0)
return error;
memset(&xo, 0, sizeof(xo));
diff_output_to_patch(&xo.output, patch);
git_xdiff_init(&xo, &diff->opts);
error = patch_generated_invoke_file_callback(patch, &xo.output);
if (!error)
error = patch_generated_create(patch, &xo.output);
if (!error) {
/* TODO: if cumulative diff size is < 0.5 total size, flatten patch */
/* TODO: and unload the file content */
}
if (error || !patch_ptr)
git_patch_free(&patch->base);
else
*patch_ptr = &patch->base;
return error;
}
git_diff_driver *git_patch_generated_driver(git_patch_generated *patch)
{
/* ofile driver is representative for whole patch */
return patch->ofile.driver;
}
void git_patch_generated_old_data(
char **ptr, size_t *len, git_patch_generated *patch)
{
*ptr = patch->ofile.map.data;
*len = patch->ofile.map.len;
}
void git_patch_generated_new_data(
char **ptr, size_t *len, git_patch_generated *patch)
{
*ptr = patch->nfile.map.data;
*len = patch->nfile.map.len;
}
static int patch_generated_file_cb(
const git_diff_delta *delta,
float progress,
void *payload)
{
GIT_UNUSED(delta); GIT_UNUSED(progress); GIT_UNUSED(payload);
return 0;
}
static int patch_generated_binary_cb(
const git_diff_delta *delta,
const git_diff_binary *binary,
void *payload)
{
git_patch *patch = payload;
GIT_UNUSED(delta);
memcpy(&patch->binary, binary, sizeof(git_diff_binary));
if (binary->old_file.data) {
patch->binary.old_file.data = git__malloc(binary->old_file.datalen);
GIT_ERROR_CHECK_ALLOC(patch->binary.old_file.data);
memcpy((char *)patch->binary.old_file.data,
binary->old_file.data, binary->old_file.datalen);
}
if (binary->new_file.data) {
patch->binary.new_file.data = git__malloc(binary->new_file.datalen);
GIT_ERROR_CHECK_ALLOC(patch->binary.new_file.data);
memcpy((char *)patch->binary.new_file.data,
binary->new_file.data, binary->new_file.datalen);
}
return 0;
}
static int git_patch_hunk_cb(
const git_diff_delta *delta,
const git_diff_hunk *hunk_,
void *payload)
{
git_patch_generated *patch = payload;
git_patch_hunk *hunk;
GIT_UNUSED(delta);
hunk = git_array_alloc(patch->base.hunks);
GIT_ERROR_CHECK_ALLOC(hunk);
memcpy(&hunk->hunk, hunk_, sizeof(hunk->hunk));
patch->base.header_size += hunk_->header_len;
hunk->line_start = git_array_size(patch->base.lines);
hunk->line_count = 0;
return 0;
}
static int patch_generated_line_cb(
const git_diff_delta *delta,
const git_diff_hunk *hunk_,
const git_diff_line *line_,
void *payload)
{
git_patch_generated *patch = payload;
git_patch_hunk *hunk;
git_diff_line *line;
GIT_UNUSED(delta);
GIT_UNUSED(hunk_);
hunk = git_array_last(patch->base.hunks);
GIT_ASSERT(hunk); /* programmer error if no hunk is available */
line = git_array_alloc(patch->base.lines);
GIT_ERROR_CHECK_ALLOC(line);
memcpy(line, line_, sizeof(*line));
/* do some bookkeeping so we can provide old/new line numbers */
patch->base.content_size += line->content_len;
if (line->origin == GIT_DIFF_LINE_ADDITION ||
line->origin == GIT_DIFF_LINE_DELETION)
patch->base.content_size += 1;
else if (line->origin == GIT_DIFF_LINE_CONTEXT) {
patch->base.content_size += 1;
patch->base.context_size += line->content_len + 1;
} else if (line->origin == GIT_DIFF_LINE_CONTEXT_EOFNL)
patch->base.context_size += line->content_len;
hunk->line_count++;
return 0;
}
static void diff_output_init(
git_patch_generated_output *out,
const git_diff_options *opts,
git_diff_file_cb file_cb,
git_diff_binary_cb binary_cb,
git_diff_hunk_cb hunk_cb,
git_diff_line_cb data_cb,
void *payload)
{
GIT_UNUSED(opts);
memset(out, 0, sizeof(*out));
out->file_cb = file_cb;
out->binary_cb = binary_cb;
out->hunk_cb = hunk_cb;
out->data_cb = data_cb;
out->payload = payload;
}
static void diff_output_to_patch(
git_patch_generated_output *out, git_patch_generated *patch)
{
diff_output_init(
out,
NULL,
patch_generated_file_cb,
patch_generated_binary_cb,
git_patch_hunk_cb,
patch_generated_line_cb,
patch);
}
|
0 |
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2
|
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2/src/reader.c
|
/*
* Copyright (C) the libgit2 contributors. All rights reserved.
*
* This file is part of libgit2, distributed under the GNU GPL v2 with
* a Linking Exception. For full terms see the included COPYING file.
*/
#include "reader.h"
#include "futils.h"
#include "blob.h"
#include "git2/tree.h"
#include "git2/blob.h"
#include "git2/index.h"
#include "git2/repository.h"
/* tree reader */
typedef struct {
git_reader reader;
git_tree *tree;
} tree_reader;
static int tree_reader_read(
git_buf *out,
git_oid *out_id,
git_filemode_t *out_filemode,
git_reader *_reader,
const char *filename)
{
tree_reader *reader = (tree_reader *)_reader;
git_tree_entry *tree_entry = NULL;
git_blob *blob = NULL;
git_object_size_t blobsize;
int error;
if ((error = git_tree_entry_bypath(&tree_entry, reader->tree, filename)) < 0 ||
(error = git_blob_lookup(&blob, git_tree_owner(reader->tree), git_tree_entry_id(tree_entry))) < 0)
goto done;
blobsize = git_blob_rawsize(blob);
GIT_ERROR_CHECK_BLOBSIZE(blobsize);
if ((error = git_buf_set(out, git_blob_rawcontent(blob), (size_t)blobsize)) < 0)
goto done;
if (out_id)
git_oid_cpy(out_id, git_tree_entry_id(tree_entry));
if (out_filemode)
*out_filemode = git_tree_entry_filemode(tree_entry);
done:
git_blob_free(blob);
git_tree_entry_free(tree_entry);
return error;
}
int git_reader_for_tree(git_reader **out, git_tree *tree)
{
tree_reader *reader;
GIT_ASSERT_ARG(out);
GIT_ASSERT_ARG(tree);
reader = git__calloc(1, sizeof(tree_reader));
GIT_ERROR_CHECK_ALLOC(reader);
reader->reader.read = tree_reader_read;
reader->tree = tree;
*out = (git_reader *)reader;
return 0;
}
/* workdir reader */
typedef struct {
git_reader reader;
git_repository *repo;
git_index *index;
} workdir_reader;
static int workdir_reader_read(
git_buf *out,
git_oid *out_id,
git_filemode_t *out_filemode,
git_reader *_reader,
const char *filename)
{
workdir_reader *reader = (workdir_reader *)_reader;
git_buf path = GIT_BUF_INIT;
struct stat st;
git_filemode_t filemode;
git_filter_list *filters = NULL;
const git_index_entry *idx_entry;
git_oid id;
int error;
if ((error = git_repository_workdir_path(&path, reader->repo, filename)) < 0)
goto done;
if ((error = p_lstat(path.ptr, &st)) < 0) {
if (error == -1 && errno == ENOENT)
error = GIT_ENOTFOUND;
git_error_set(GIT_ERROR_OS, "could not stat '%s'", path.ptr);
goto done;
}
filemode = git_futils_canonical_mode(st.st_mode);
/*
* Patch application - for example - uses the filtered version of
* the working directory data to match git. So we will run the
* workdir -> ODB filter on the contents in this workdir reader.
*/
if ((error = git_filter_list_load(&filters, reader->repo, NULL, filename,
GIT_FILTER_TO_ODB, GIT_FILTER_DEFAULT)) < 0)
goto done;
if ((error = git_filter_list_apply_to_file(out,
filters, reader->repo, path.ptr)) < 0)
goto done;
if (out_id || reader->index) {
if ((error = git_odb_hash(&id, out->ptr, out->size, GIT_OBJECT_BLOB)) < 0)
goto done;
}
if (reader->index) {
if (!(idx_entry = git_index_get_bypath(reader->index, filename, 0)) ||
filemode != idx_entry->mode ||
!git_oid_equal(&id, &idx_entry->id)) {
error = GIT_READER_MISMATCH;
goto done;
}
}
if (out_id)
git_oid_cpy(out_id, &id);
if (out_filemode)
*out_filemode = filemode;
done:
git_filter_list_free(filters);
git_buf_dispose(&path);
return error;
}
int git_reader_for_workdir(
git_reader **out,
git_repository *repo,
bool validate_index)
{
workdir_reader *reader;
int error;
GIT_ASSERT_ARG(out);
GIT_ASSERT_ARG(repo);
reader = git__calloc(1, sizeof(workdir_reader));
GIT_ERROR_CHECK_ALLOC(reader);
reader->reader.read = workdir_reader_read;
reader->repo = repo;
if (validate_index &&
(error = git_repository_index__weakptr(&reader->index, repo)) < 0) {
git__free(reader);
return error;
}
*out = (git_reader *)reader;
return 0;
}
/* index reader */
typedef struct {
git_reader reader;
git_repository *repo;
git_index *index;
} index_reader;
static int index_reader_read(
git_buf *out,
git_oid *out_id,
git_filemode_t *out_filemode,
git_reader *_reader,
const char *filename)
{
index_reader *reader = (index_reader *)_reader;
const git_index_entry *entry;
git_blob *blob;
int error;
if ((entry = git_index_get_bypath(reader->index, filename, 0)) == NULL)
return GIT_ENOTFOUND;
if ((error = git_blob_lookup(&blob, reader->repo, &entry->id)) < 0)
goto done;
if (out_id)
git_oid_cpy(out_id, &entry->id);
if (out_filemode)
*out_filemode = entry->mode;
error = git_blob__getbuf(out, blob);
done:
git_blob_free(blob);
return error;
}
int git_reader_for_index(
git_reader **out,
git_repository *repo,
git_index *index)
{
index_reader *reader;
int error;
GIT_ASSERT_ARG(out);
GIT_ASSERT_ARG(repo);
reader = git__calloc(1, sizeof(index_reader));
GIT_ERROR_CHECK_ALLOC(reader);
reader->reader.read = index_reader_read;
reader->repo = repo;
if (index) {
reader->index = index;
} else if ((error = git_repository_index__weakptr(&reader->index, repo)) < 0) {
git__free(reader);
return error;
}
*out = (git_reader *)reader;
return 0;
}
/* generic */
int git_reader_read(
git_buf *out,
git_oid *out_id,
git_filemode_t *out_filemode,
git_reader *reader,
const char *filename)
{
GIT_ASSERT_ARG(out);
GIT_ASSERT_ARG(reader);
GIT_ASSERT_ARG(filename);
return reader->read(out, out_id, out_filemode, reader, filename);
}
void git_reader_free(git_reader *reader)
{
if (!reader)
return;
git__free(reader);
}
|
0 |
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2
|
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2/src/commit_graph.h
|
/*
* Copyright (C) the libgit2 contributors. All rights reserved.
*
* This file is part of libgit2, distributed under the GNU GPL v2 with
* a Linking Exception. For full terms see the included COPYING file.
*/
#ifndef INCLUDE_commit_graph_h__
#define INCLUDE_commit_graph_h__
#include "common.h"
#include "git2/types.h"
#include "git2/sys/commit_graph.h"
#include "map.h"
#include "vector.h"
/**
* A commit-graph file.
*
* This file contains metadata about commits, particularly the generation
* number for each one. This can help speed up graph operations without
* requiring a full graph traversal.
*
* Support for this feature was added in git 2.19.
*/
typedef struct git_commit_graph_file {
git_map graph_map;
/* The OID Fanout table. */
const uint32_t *oid_fanout;
/* The total number of commits in the graph. */
uint32_t num_commits;
/* The OID Lookup table. */
git_oid *oid_lookup;
/*
* The Commit Data table. Each entry contains the OID of the commit followed
* by two 8-byte fields in network byte order:
* - The indices of the first two parents (32 bits each).
* - The generation number (first 30 bits) and commit time in seconds since
* UNIX epoch (34 bits).
*/
const unsigned char *commit_data;
/*
* The Extra Edge List table. Each 4-byte entry is a network byte order index
* of one of the i-th (i > 0) parents of commits in the `commit_data` table,
* when the commit has more than 2 parents.
*/
const unsigned char *extra_edge_list;
/* The number of entries in the Extra Edge List table. Each entry is 4 bytes wide. */
size_t num_extra_edge_list;
/* The trailer of the file. Contains the SHA1-checksum of the whole file. */
git_oid checksum;
} git_commit_graph_file;
/**
* An entry in the commit-graph file. Provides a subset of the information that
* can be obtained from the commit header.
*/
typedef struct git_commit_graph_entry {
/* The generation number of the commit within the graph */
size_t generation;
/* Time in seconds from UNIX epoch. */
git_time_t commit_time;
/* The number of parents of the commit. */
size_t parent_count;
/*
* The indices of the parent commits within the Commit Data table. The value
* of `GIT_COMMIT_GRAPH_MISSING_PARENT` indicates that no parent is in that
* position.
*/
size_t parent_indices[2];
/* The index within the Extra Edge List of any parent after the first two. */
size_t extra_parents_index;
/* The SHA-1 hash of the root tree of the commit. */
git_oid tree_oid;
/* The SHA-1 hash of the requested commit. */
git_oid sha1;
} git_commit_graph_entry;
/* A wrapper for git_commit_graph_file to enable lazy loading in the ODB. */
struct git_commit_graph {
/* The path to the commit-graph file. Something like ".git/objects/info/commit-graph". */
git_buf filename;
/* The underlying commit-graph file. */
git_commit_graph_file *file;
/* Whether the commit-graph file was already checked for validity. */
bool checked;
};
/** Create a new commit-graph, optionally opening the underlying file. */
int git_commit_graph_new(git_commit_graph **cgraph_out, const char *objects_dir, bool open_file);
/** Open and validate a commit-graph file. */
int git_commit_graph_file_open(git_commit_graph_file **file_out, const char *path);
/*
* Attempt to get the git_commit_graph's commit-graph file. This object is
* still owned by the git_commit_graph. If the repository does not contain a commit graph,
* it will return GIT_ENOTFOUND.
*
* This function is not thread-safe.
*/
int git_commit_graph_get_file(git_commit_graph_file **file_out, git_commit_graph *cgraph);
/* Marks the commit-graph file as needing a refresh. */
void git_commit_graph_refresh(git_commit_graph *cgraph);
/*
* A writer for `commit-graph` files.
*/
struct git_commit_graph_writer {
/*
* The path of the `objects/info` directory where the `commit-graph` will be
* stored.
*/
git_buf objects_info_dir;
/* The list of packed commits. */
git_vector commits;
};
/*
* Returns whether the git_commit_graph_file needs to be reloaded since the
* contents of the commit-graph file have changed on disk.
*/
bool git_commit_graph_file_needs_refresh(
const git_commit_graph_file *file, const char *path);
int git_commit_graph_entry_find(
git_commit_graph_entry *e,
const git_commit_graph_file *file,
const git_oid *short_oid,
size_t len);
int git_commit_graph_entry_parent(
git_commit_graph_entry *parent,
const git_commit_graph_file *file,
const git_commit_graph_entry *entry,
size_t n);
int git_commit_graph_file_close(git_commit_graph_file *cgraph);
void git_commit_graph_file_free(git_commit_graph_file *cgraph);
/* This is exposed for use in the fuzzers. */
int git_commit_graph_file_parse(
git_commit_graph_file *file,
const unsigned char *data,
size_t size);
#endif
|
0 |
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2
|
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2/src/delta.h
|
/*
* diff-delta code taken from git.git. See diff-delta.c for details.
*
*/
#ifndef INCLUDE_git_delta_h__
#define INCLUDE_git_delta_h__
#include "common.h"
#include "pack.h"
typedef struct git_delta_index git_delta_index;
/*
* git_delta_index_init: compute index data from given buffer
*
* This returns a pointer to a struct delta_index that should be passed to
* subsequent create_delta() calls, or to free_delta_index(). A NULL pointer
* is returned on failure. The given buffer must not be freed nor altered
* before free_delta_index() is called. The returned pointer must be freed
* using free_delta_index().
*/
extern int git_delta_index_init(
git_delta_index **out, const void *buf, size_t bufsize);
/*
* Free the index created by git_delta_index_init()
*/
extern void git_delta_index_free(git_delta_index *index);
/*
* Returns memory usage of delta index.
*/
extern size_t git_delta_index_size(git_delta_index *index);
/*
* create_delta: create a delta from given index for the given buffer
*
* This function may be called multiple times with different buffers using
* the same delta_index pointer. If max_delta_size is non-zero and the
* resulting delta is to be larger than max_delta_size then NULL is returned.
* On success, a non-NULL pointer to the buffer with the delta data is
* returned and *delta_size is updated with its size. The returned buffer
* must be freed by the caller.
*/
extern int git_delta_create_from_index(
void **out,
size_t *out_size,
const struct git_delta_index *index,
const void *buf,
size_t bufsize,
size_t max_delta_size);
/*
* diff_delta: create a delta from source buffer to target buffer
*
* If max_delta_size is non-zero and the resulting delta is to be larger
* than max_delta_size then GIT_EBUFS is returned. On success, a non-NULL
* pointer to the buffer with the delta data is returned and *delta_size is
* updated with its size. The returned buffer must be freed by the caller.
*/
GIT_INLINE(int) git_delta(
void **out, size_t *out_len,
const void *src_buf, size_t src_bufsize,
const void *trg_buf, size_t trg_bufsize,
size_t max_delta_size)
{
git_delta_index *index;
int error = 0;
*out = NULL;
*out_len = 0;
if ((error = git_delta_index_init(&index, src_buf, src_bufsize)) < 0)
return error;
if (index) {
error = git_delta_create_from_index(out, out_len,
index, trg_buf, trg_bufsize, max_delta_size);
git_delta_index_free(index);
}
return error;
}
/* the smallest possible delta size is 4 bytes */
#define GIT_DELTA_SIZE_MIN 4
/**
* Apply a git binary delta to recover the original content.
* The caller is responsible for freeing the returned buffer.
*
* @param out the output buffer
* @param out_len the length of the output buffer
* @param base the base to copy from during copy instructions.
* @param base_len number of bytes available at base.
* @param delta the delta to execute copy/insert instructions from.
* @param delta_len total number of bytes in the delta.
* @return 0 on success or an error code
*/
extern int git_delta_apply(
void **out,
size_t *out_len,
const unsigned char *base,
size_t base_len,
const unsigned char *delta,
size_t delta_len);
/**
* Read the header of a git binary delta.
*
* @param base_out pointer to store the base size field.
* @param result_out pointer to store the result size field.
* @param delta the delta to execute copy/insert instructions from.
* @param delta_len total number of bytes in the delta.
* @return 0 on success or an error code
*/
extern int git_delta_read_header(
size_t *base_out,
size_t *result_out,
const unsigned char *delta,
size_t delta_len);
/**
* Read the header of a git binary delta
*
* This variant reads just enough from the packfile stream to read the
* delta header.
*/
extern int git_delta_read_header_fromstream(
size_t *base_out,
size_t *result_out,
git_packfile_stream *stream);
#endif
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.