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/oidmap.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 "oidmap.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(oid, const git_oid *, void *)
GIT_INLINE(khint_t) git_oidmap_hash(const git_oid *oid)
{
khint_t h;
memcpy(&h, oid, sizeof(khint_t));
return h;
}
__KHASH_IMPL(oid, static kh_inline, const git_oid *, void *, 1, git_oidmap_hash, git_oid_equal)
int git_oidmap_new(git_oidmap **out)
{
*out = kh_init(oid);
GIT_ERROR_CHECK_ALLOC(*out);
return 0;
}
void git_oidmap_free(git_oidmap *map)
{
kh_destroy(oid, map);
}
void git_oidmap_clear(git_oidmap *map)
{
kh_clear(oid, map);
}
size_t git_oidmap_size(git_oidmap *map)
{
return kh_size(map);
}
void *git_oidmap_get(git_oidmap *map, const git_oid *key)
{
size_t idx = kh_get(oid, map, key);
if (idx == kh_end(map) || !kh_exist(map, idx))
return NULL;
return kh_val(map, idx);
}
int git_oidmap_set(git_oidmap *map, const git_oid *key, void *value)
{
size_t idx;
int rval;
idx = kh_put(oid, 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_oidmap_delete(git_oidmap *map, const git_oid *key)
{
khiter_t idx = kh_get(oid, map, key);
if (idx == kh_end(map))
return GIT_ENOTFOUND;
kh_del(oid, map, idx);
return 0;
}
int git_oidmap_exists(git_oidmap *map, const git_oid *key)
{
return kh_get(oid, map, key) != kh_end(map);
}
int git_oidmap_iterate(void **value, git_oidmap *map, size_t *iter, const git_oid **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_value(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/common.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_common_h__
#define INCLUDE_common_h__
#ifndef LIBGIT2_NO_FEATURES_H
# include "git2/sys/features.h"
#endif
#include "git2/common.h"
#include "cc-compat.h"
/** Declare a function as always inlined. */
#if defined(_MSC_VER)
# define GIT_INLINE(type) static __inline type
#elif defined(__GNUC__)
# define GIT_INLINE(type) static __inline__ type
#elif defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L)
# define GIT_INLINE(type) static inline type
#else
# define GIT_INLINE(type) static type
#endif
/** Support for gcc/clang __has_builtin intrinsic */
#ifndef __has_builtin
# define __has_builtin(x) 0
#endif
/**
* Declare that a function's return value must be used.
*
* Used mostly to guard against potential silent bugs at runtime. This is
* recommended to be added to functions that:
*
* - Allocate / reallocate memory. This prevents memory leaks or errors where
* buffers are expected to have grown to a certain size, but could not be
* resized.
* - Acquire locks. When a lock cannot be acquired, that will almost certainly
* cause a data race / undefined behavior.
*/
#if defined(__GNUC__)
# define GIT_WARN_UNUSED_RESULT __attribute__((warn_unused_result))
#else
# define GIT_WARN_UNUSED_RESULT
#endif
#include <assert.h>
#include <errno.h>
#include <limits.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#ifdef GIT_WIN32
# include <io.h>
# include <direct.h>
# include <winsock2.h>
# include <windows.h>
# include <ws2tcpip.h>
# include "win32/msvc-compat.h"
# include "win32/mingw-compat.h"
# include "win32/w32_common.h"
# include "win32/win32-compat.h"
# include "win32/error.h"
# include "win32/version.h"
# ifdef GIT_THREADS
# include "win32/thread.h"
# endif
#else
# include <unistd.h>
# include <strings.h>
# ifdef GIT_THREADS
# include <pthread.h>
# include <sched.h>
# endif
#define GIT_LIBGIT2_CALL
#define GIT_SYSTEM_CALL
#ifdef GIT_USE_STAT_ATIMESPEC
# define st_atim st_atimespec
# define st_ctim st_ctimespec
# define st_mtim st_mtimespec
#endif
# include <arpa/inet.h>
#endif
#include "git2/types.h"
#include "git2/errors.h"
#include "errors.h"
#include "thread.h"
#include "integer.h"
#include "assert_safe.h"
#include "utf8.h"
/*
* Include the declarations for deprecated functions; this ensures
* that they're decorated with the proper extern/visibility attributes.
*/
#include "git2/deprecated.h"
#include "posix.h"
#define DEFAULT_BUFSIZE 65536
#define FILEIO_BUFSIZE DEFAULT_BUFSIZE
#define FILTERIO_BUFSIZE DEFAULT_BUFSIZE
#define NETIO_BUFSIZE DEFAULT_BUFSIZE
/**
* Check a pointer allocation result, returning -1 if it failed.
*/
#define GIT_ERROR_CHECK_ALLOC(ptr) if (ptr == NULL) { return -1; }
/**
* Check a buffer allocation result, returning -1 if it failed.
*/
#define GIT_ERROR_CHECK_ALLOC_BUF(buf) if ((void *)(buf) == NULL || git_buf_oom(buf)) { return -1; }
/**
* Check a return value and propagate result if non-zero.
*/
#define GIT_ERROR_CHECK_ERROR(code) \
do { int _err = (code); if (_err) return _err; } while (0)
/**
* Check a versioned structure for validity
*/
GIT_INLINE(int) git_error__check_version(const void *structure, unsigned int expected_max, const char *name)
{
unsigned int actual;
if (!structure)
return 0;
actual = *(const unsigned int*)structure;
if (actual > 0 && actual <= expected_max)
return 0;
git_error_set(GIT_ERROR_INVALID, "invalid version %d on %s", actual, name);
return -1;
}
#define GIT_ERROR_CHECK_VERSION(S,V,N) if (git_error__check_version(S,V,N) < 0) return -1
/**
* Initialize a structure with a version.
*/
GIT_INLINE(void) git__init_structure(void *structure, size_t len, unsigned int version)
{
memset(structure, 0, len);
*((int*)structure) = version;
}
#define GIT_INIT_STRUCTURE(S,V) git__init_structure(S, sizeof(*S), V)
#define GIT_INIT_STRUCTURE_FROM_TEMPLATE(PTR,VERSION,TYPE,TPL) do { \
TYPE _tmpl = TPL; \
GIT_ERROR_CHECK_VERSION(&(VERSION), _tmpl.version, #TYPE); \
memcpy((PTR), &_tmpl, sizeof(_tmpl)); } while (0)
/** Check for additive overflow, setting an error if would occur. */
#define GIT_ADD_SIZET_OVERFLOW(out, one, two) \
(git__add_sizet_overflow(out, one, two) ? (git_error_set_oom(), 1) : 0)
/** Check for additive overflow, setting an error if would occur. */
#define GIT_MULTIPLY_SIZET_OVERFLOW(out, nelem, elsize) \
(git__multiply_sizet_overflow(out, nelem, elsize) ? (git_error_set_oom(), 1) : 0)
/** Check for additive overflow, failing if it would occur. */
#define GIT_ERROR_CHECK_ALLOC_ADD(out, one, two) \
if (GIT_ADD_SIZET_OVERFLOW(out, one, two)) { return -1; }
#define GIT_ERROR_CHECK_ALLOC_ADD3(out, one, two, three) \
if (GIT_ADD_SIZET_OVERFLOW(out, one, two) || \
GIT_ADD_SIZET_OVERFLOW(out, *(out), three)) { return -1; }
#define GIT_ERROR_CHECK_ALLOC_ADD4(out, one, two, three, four) \
if (GIT_ADD_SIZET_OVERFLOW(out, one, two) || \
GIT_ADD_SIZET_OVERFLOW(out, *(out), three) || \
GIT_ADD_SIZET_OVERFLOW(out, *(out), four)) { return -1; }
#define GIT_ERROR_CHECK_ALLOC_ADD5(out, one, two, three, four, five) \
if (GIT_ADD_SIZET_OVERFLOW(out, one, two) || \
GIT_ADD_SIZET_OVERFLOW(out, *(out), three) || \
GIT_ADD_SIZET_OVERFLOW(out, *(out), four) || \
GIT_ADD_SIZET_OVERFLOW(out, *(out), five)) { return -1; }
/** Check for multiplicative overflow, failing if it would occur. */
#define GIT_ERROR_CHECK_ALLOC_MULTIPLY(out, nelem, elsize) \
if (GIT_MULTIPLY_SIZET_OVERFLOW(out, nelem, elsize)) { return -1; }
/* NOTE: other git_error functions are in the public errors.h header file */
#include "util.h"
#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/CMakeLists.txt
|
add_library(git2internal OBJECT)
set_target_properties(git2internal PROPERTIES C_STANDARD 90)
IF(DEBUG_POOL)
SET(GIT_DEBUG_POOL 1)
ENDIF()
ADD_FEATURE_INFO(debugpool GIT_DEBUG_POOL "debug pool allocator")
IF(DEBUG_STRICT_ALLOC)
SET(GIT_DEBUG_STRICT_ALLOC 1)
ENDIF()
ADD_FEATURE_INFO(debugalloc GIT_DEBUG_STRICT_ALLOC "debug strict allocators")
IF(DEBUG_STRICT_OPEN)
SET(GIT_DEBUG_STRICT_OPEN 1)
ENDIF()
ADD_FEATURE_INFO(debugopen GIT_DEBUG_STRICT_OPEN "path validation in open")
INCLUDE(PkgBuildConfig)
INCLUDE(SanitizeBool)
# This variable will contain the libraries we need to put into
# libgit2.pc's Requires.private. That is, what we're linking to or
# what someone who's statically linking us needs to link to.
SET(LIBGIT2_PC_REQUIRES "")
# This will be set later if we use the system's http-parser library or
# use iconv (OSX) and will be written to the Libs.private field in the
# pc file.
SET(LIBGIT2_PC_LIBS "")
SET(LIBGIT2_INCLUDES
"${CMAKE_CURRENT_BINARY_DIR}"
"${libgit2_SOURCE_DIR}/src"
"${libgit2_SOURCE_DIR}/include")
SET(LIBGIT2_SYSTEM_INCLUDES "")
SET(LIBGIT2_LIBS "")
enable_warnings(missing-declarations)
# Enable tracing
IF(ENABLE_TRACE)
SET(GIT_TRACE 1)
ENDIF()
ADD_FEATURE_INFO(tracing GIT_TRACE "tracing support")
IF (HAVE_FUTIMENS)
SET(GIT_USE_FUTIMENS 1)
ENDIF ()
ADD_FEATURE_INFO(futimens GIT_USE_FUTIMENS "futimens support")
CHECK_PROTOTYPE_DEFINITION(qsort_r
"void qsort_r(void *base, size_t nmemb, size_t size, void *thunk, int (*compar)(void *, const void *, const void *))"
"" "stdlib.h" HAVE_QSORT_R_BSD)
IF (HAVE_QSORT_R_BSD)
target_compile_definitions(git2internal PRIVATE HAVE_QSORT_R_BSD)
ENDIF()
CHECK_PROTOTYPE_DEFINITION(qsort_r
"void qsort_r(void *base, size_t nmemb, size_t size, int (*compar)(const void *, const void *, void *), void *arg)"
"" "stdlib.h" HAVE_QSORT_R_GNU)
IF (HAVE_QSORT_R_GNU)
target_compile_definitions(git2internal PRIVATE HAVE_QSORT_R_GNU)
ENDIF()
CHECK_FUNCTION_EXISTS(qsort_s HAVE_QSORT_S)
IF (HAVE_QSORT_S)
target_compile_definitions(git2internal PRIVATE HAVE_QSORT_S)
ENDIF ()
# Find required dependencies
IF(WIN32)
LIST(APPEND LIBGIT2_LIBS ws2_32)
ELSEIF(CMAKE_SYSTEM_NAME MATCHES "(Solaris|SunOS)")
LIST(APPEND LIBGIT2_LIBS socket nsl)
LIST(APPEND LIBGIT2_PC_LIBS "-lsocket" "-lnsl")
ELSEIF(CMAKE_SYSTEM_NAME MATCHES "Haiku")
LIST(APPEND LIBGIT2_LIBS network)
LIST(APPEND LIBGIT2_PC_LIBS "-lnetwork")
ENDIF()
CHECK_LIBRARY_EXISTS(rt clock_gettime "time.h" NEED_LIBRT)
IF(NEED_LIBRT)
LIST(APPEND LIBGIT2_LIBS rt)
LIST(APPEND LIBGIT2_PC_LIBS "-lrt")
ENDIF()
IF(THREADSAFE)
LIST(APPEND LIBGIT2_LIBS ${CMAKE_THREAD_LIBS_INIT})
LIST(APPEND LIBGIT2_PC_LIBS ${CMAKE_THREAD_LIBS_INIT})
ENDIF()
ADD_FEATURE_INFO(threadsafe THREADSAFE "threadsafe support")
if(WIN32 AND EMBED_SSH_PATH)
file(GLOB SRC_SSH "${EMBED_SSH_PATH}/src/*.c")
list(SORT SRC_SSH)
target_sources(git2internal PRIVATE ${SRC_SSH})
list(APPEND LIBGIT2_SYSTEM_INCLUDES "${EMBED_SSH_PATH}/include")
file(WRITE "${EMBED_SSH_PATH}/src/libssh2_config.h" "#define HAVE_WINCNG\n#define LIBSSH2_WINCNG\n#include \"../win32/libssh2_config.h\"")
set(GIT_SSH 1)
endif()
IF (WIN32 AND WINHTTP)
SET(GIT_WINHTTP 1)
# Since MinGW does not come with headers or an import library for winhttp,
# we have to include a private header and generate our own import library
IF (MINGW)
ADD_SUBDIRECTORY("${libgit2_SOURCE_DIR}/deps/winhttp" "${libgit2_BINARY_DIR}/deps/winhttp")
LIST(APPEND LIBGIT2_LIBS winhttp)
LIST(APPEND LIBGIT2_INCLUDES "${libgit2_SOURCE_DIR}/deps/winhttp")
ELSE()
LIST(APPEND LIBGIT2_LIBS "winhttp")
LIST(APPEND LIBGIT2_PC_LIBS "-lwinhttp")
ENDIF ()
LIST(APPEND LIBGIT2_LIBS "rpcrt4" "crypt32" "ole32")
LIST(APPEND LIBGIT2_PC_LIBS "-lrpcrt4" "-lcrypt32" "-lole32")
ENDIF()
include(SelectHTTPSBackend)
include(SelectHashes)
target_sources(git2internal PRIVATE ${SRC_SHA1})
# Specify regular expression implementation
FIND_PACKAGE(PCRE)
IF(REGEX_BACKEND STREQUAL "")
CHECK_SYMBOL_EXISTS(regcomp_l "regex.h;xlocale.h" HAVE_REGCOMP_L)
IF(HAVE_REGCOMP_L)
SET(REGEX_BACKEND "regcomp_l")
ELSEIF(PCRE_FOUND)
SET(REGEX_BACKEND "pcre")
ELSE()
SET(REGEX_BACKEND "builtin")
ENDIF()
ENDIF()
IF(REGEX_BACKEND STREQUAL "regcomp_l")
ADD_FEATURE_INFO(regex ON "using system regcomp_l")
SET(GIT_REGEX_REGCOMP_L 1)
ELSEIF(REGEX_BACKEND STREQUAL "pcre2")
FIND_PACKAGE(PCRE2)
IF(NOT PCRE2_FOUND)
MESSAGE(FATAL_ERROR "PCRE2 support was requested but not found")
ENDIF()
ADD_FEATURE_INFO(regex ON "using system PCRE2")
SET(GIT_REGEX_PCRE2 1)
LIST(APPEND LIBGIT2_SYSTEM_INCLUDES ${PCRE2_INCLUDE_DIRS})
LIST(APPEND LIBGIT2_LIBS ${PCRE2_LIBRARIES})
LIST(APPEND LIBGIT2_PC_REQUIRES "libpcre2-8")
ELSEIF(REGEX_BACKEND STREQUAL "pcre")
ADD_FEATURE_INFO(regex ON "using system PCRE")
SET(GIT_REGEX_PCRE 1)
LIST(APPEND LIBGIT2_SYSTEM_INCLUDES ${PCRE_INCLUDE_DIRS})
LIST(APPEND LIBGIT2_LIBS ${PCRE_LIBRARIES})
LIST(APPEND LIBGIT2_PC_REQUIRES "libpcre")
ELSEIF(REGEX_BACKEND STREQUAL "regcomp")
ADD_FEATURE_INFO(regex ON "using system regcomp")
SET(GIT_REGEX_REGCOMP 1)
ELSEIF(REGEX_BACKEND STREQUAL "builtin")
ADD_FEATURE_INFO(regex ON "using bundled PCRE")
SET(GIT_REGEX_BUILTIN 1)
ADD_SUBDIRECTORY("${libgit2_SOURCE_DIR}/deps/pcre" "${libgit2_BINARY_DIR}/deps/pcre")
LIST(APPEND LIBGIT2_INCLUDES "${libgit2_SOURCE_DIR}/deps/pcre")
LIST(APPEND LIBGIT2_OBJECTS $<TARGET_OBJECTS:pcre>)
ELSE()
MESSAGE(FATAL_ERROR "The REGEX_BACKEND option provided is not supported")
ENDIF()
# Optional external dependency: http-parser
IF(USE_HTTP_PARSER STREQUAL "system")
FIND_PACKAGE(HTTP_Parser)
IF (HTTP_PARSER_FOUND AND HTTP_PARSER_VERSION_MAJOR EQUAL 2)
LIST(APPEND LIBGIT2_SYSTEM_INCLUDES ${HTTP_PARSER_INCLUDE_DIRS})
LIST(APPEND LIBGIT2_LIBS ${HTTP_PARSER_LIBRARIES})
LIST(APPEND LIBGIT2_PC_LIBS "-lhttp_parser")
ADD_FEATURE_INFO(http-parser ON "http-parser support (system)")
ELSE()
MESSAGE(FATAL_ERROR "http-parser support was requested but not found")
ENDIF()
ELSE()
MESSAGE(STATUS "http-parser version 2 was not found or disabled; using bundled 3rd-party sources.")
ADD_SUBDIRECTORY("${libgit2_SOURCE_DIR}/deps/http-parser" "${libgit2_BINARY_DIR}/deps/http-parser")
LIST(APPEND LIBGIT2_INCLUDES "${libgit2_SOURCE_DIR}/deps/http-parser")
LIST(APPEND LIBGIT2_OBJECTS "$<TARGET_OBJECTS:http-parser>")
ADD_FEATURE_INFO(http-parser ON "http-parser support (bundled)")
ENDIF()
# Optional external dependency: zlib
SanitizeBool(USE_BUNDLED_ZLIB)
IF(USE_BUNDLED_ZLIB STREQUAL ON)
SET(USE_BUNDLED_ZLIB "Bundled")
ENDIF()
IF(USE_BUNDLED_ZLIB STREQUAL "OFF")
FIND_PACKAGE(ZLIB)
IF(ZLIB_FOUND)
LIST(APPEND LIBGIT2_SYSTEM_INCLUDES ${ZLIB_INCLUDE_DIRS})
LIST(APPEND LIBGIT2_LIBS ${ZLIB_LIBRARIES})
IF(APPLE OR CMAKE_SYSTEM_NAME MATCHES "FreeBSD")
LIST(APPEND LIBGIT2_PC_LIBS "-lz")
ELSE()
LIST(APPEND LIBGIT2_PC_REQUIRES "zlib")
ENDIF()
ADD_FEATURE_INFO(zlib ON "using system zlib")
ELSE()
MESSAGE(STATUS "zlib was not found; using bundled 3rd-party sources." )
ENDIF()
ENDIF()
IF(USE_BUNDLED_ZLIB STREQUAL "Chromium")
ADD_SUBDIRECTORY("${libgit2_SOURCE_DIR}/deps/chromium-zlib" "${libgit2_BINARY_DIR}/deps/chromium-zlib")
LIST(APPEND LIBGIT2_INCLUDES "${libgit2_SOURCE_DIR}/deps/chromium-zlib")
LIST(APPEND LIBGIT2_OBJECTS $<TARGET_OBJECTS:chromium_zlib>)
ADD_FEATURE_INFO(zlib ON "using (Chromium) bundled zlib")
ELSEIF(USE_BUNDLED_ZLIB OR NOT ZLIB_FOUND)
ADD_SUBDIRECTORY("${libgit2_SOURCE_DIR}/deps/zlib" "${libgit2_BINARY_DIR}/deps/zlib")
LIST(APPEND LIBGIT2_INCLUDES "${libgit2_SOURCE_DIR}/deps/zlib")
LIST(APPEND LIBGIT2_OBJECTS $<TARGET_OBJECTS:zlib>)
ADD_FEATURE_INFO(zlib ON "using bundled zlib")
ENDIF()
# Optional external dependency: libssh2
IF (USE_SSH)
FIND_PKGLIBRARIES(LIBSSH2 libssh2)
IF (NOT LIBSSH2_FOUND)
FIND_PACKAGE(LibSSH2)
SET(LIBSSH2_INCLUDE_DIRS ${LIBSSH2_INCLUDE_DIR})
GET_FILENAME_COMPONENT(LIBSSH2_LIBRARY_DIRS "${LIBSSH2_LIBRARY}" DIRECTORY)
SET(LIBSSH2_LIBRARIES ${LIBSSH2_LIBRARY})
SET(LIBSSH2_LDFLAGS "-lssh2")
ENDIF()
ENDIF()
IF (LIBSSH2_FOUND)
SET(GIT_SSH 1)
LIST(APPEND LIBGIT2_SYSTEM_INCLUDES ${LIBSSH2_INCLUDE_DIRS})
LIST(APPEND LIBGIT2_LIBS ${LIBSSH2_LIBRARIES})
LIST(APPEND LIBGIT2_PC_LIBS ${LIBSSH2_LDFLAGS})
CHECK_LIBRARY_EXISTS("${LIBSSH2_LIBRARIES}" libssh2_userauth_publickey_frommemory "${LIBSSH2_LIBRARY_DIRS}" HAVE_LIBSSH2_MEMORY_CREDENTIALS)
IF (HAVE_LIBSSH2_MEMORY_CREDENTIALS)
SET(GIT_SSH_MEMORY_CREDENTIALS 1)
ENDIF()
ELSE()
MESSAGE(STATUS "LIBSSH2 not found. Set CMAKE_PREFIX_PATH if it is installed outside of the default search path.")
ENDIF()
ADD_FEATURE_INFO(SSH GIT_SSH "SSH transport support")
# Optional external dependency: ntlmclient
IF (USE_NTLMCLIENT)
SET(GIT_NTLM 1)
ADD_SUBDIRECTORY("${libgit2_SOURCE_DIR}/deps/ntlmclient" "${libgit2_BINARY_DIR}/deps/ntlmclient")
LIST(APPEND LIBGIT2_INCLUDES "${libgit2_SOURCE_DIR}/deps/ntlmclient")
LIST(APPEND LIBGIT2_OBJECTS "$<TARGET_OBJECTS:ntlmclient>")
ENDIF()
ADD_FEATURE_INFO(ntlmclient GIT_NTLM "NTLM authentication support for Unix")
# Optional external dependency: GSSAPI
INCLUDE(SelectGSSAPI)
# Optional external dependency: iconv
IF (USE_ICONV)
FIND_PACKAGE(Iconv)
ENDIF()
IF (ICONV_FOUND)
SET(GIT_USE_ICONV 1)
LIST(APPEND LIBGIT2_SYSTEM_INCLUDES ${ICONV_INCLUDE_DIR})
LIST(APPEND LIBGIT2_LIBS ${ICONV_LIBRARIES})
LIST(APPEND LIBGIT2_PC_LIBS ${ICONV_LIBRARIES})
ENDIF()
ADD_FEATURE_INFO(iconv GIT_USE_ICONV "iconv encoding conversion support")
IF (THREADSAFE)
IF (NOT WIN32)
FIND_PACKAGE(Threads REQUIRED)
ENDIF()
SET(GIT_THREADS 1)
ENDIF()
IF (USE_NSEC)
SET(GIT_USE_NSEC 1)
ENDIF()
IF (HAVE_STRUCT_STAT_ST_MTIM)
SET(GIT_USE_STAT_MTIM 1)
ELSEIF (HAVE_STRUCT_STAT_ST_MTIMESPEC)
SET(GIT_USE_STAT_MTIMESPEC 1)
ELSEIF (HAVE_STRUCT_STAT_ST_MTIME_NSEC)
SET(GIT_USE_STAT_MTIME_NSEC 1)
ENDIF()
target_compile_definitions(git2internal PRIVATE _FILE_OFFSET_BITS=64)
# Collect sourcefiles
file(GLOB SRC_H
"${libgit2_SOURCE_DIR}/include/git2.h"
"${libgit2_SOURCE_DIR}/include/git2/*.h"
"${libgit2_SOURCE_DIR}/include/git2/sys/*.h")
list(SORT SRC_H)
target_sources(git2internal PRIVATE ${SRC_H})
# On Windows use specific platform sources
if(WIN32 AND NOT CYGWIN)
SET(WIN_RC "win32/git2.rc")
file(GLOB SRC_OS win32/*.c win32/*.h)
list(SORT SRC_OS)
target_sources(git2internal PRIVATE ${SRC_OS})
elseif(AMIGA)
target_compile_definitions(git2internal PRIVATE NO_ADDRINFO NO_READDIR_R NO_MMAP)
else()
file(GLOB SRC_OS unix/*.c unix/*.h)
list(SORT SRC_OS)
target_sources(git2internal PRIVATE ${SRC_OS})
endif()
IF (USE_LEAK_CHECKER STREQUAL "valgrind")
target_compile_definitions(git2internal PRIVATE VALGRIND)
ENDIF()
file(GLOB SRC_GIT2 *.c *.h
allocators/*.c allocators/*.h
streams/*.c streams/*.h
transports/*.c transports/*.h
xdiff/*.c xdiff/*.h)
list(SORT SRC_GIT2)
target_sources(git2internal PRIVATE ${SRC_GIT2})
IF(APPLE)
# The old Secure Transport API has been deprecated in macOS 10.15.
SET_SOURCE_FILES_PROPERTIES(streams/stransport.c PROPERTIES COMPILE_FLAGS -Wno-deprecated)
ENDIF()
# the xdiff dependency is not (yet) warning-free, disable warnings as
# errors for the xdiff sources until we've sorted them out
IF(MSVC)
SET_SOURCE_FILES_PROPERTIES(xdiff/xdiffi.c PROPERTIES COMPILE_FLAGS -WX-)
SET_SOURCE_FILES_PROPERTIES(xdiff/xutils.c PROPERTIES COMPILE_FLAGS -WX-)
ENDIF()
# Determine architecture of the machine
IF (CMAKE_SIZEOF_VOID_P EQUAL 8)
SET(GIT_ARCH_64 1)
ELSEIF (CMAKE_SIZEOF_VOID_P EQUAL 4)
SET(GIT_ARCH_32 1)
ELSEIF (CMAKE_SIZEOF_VOID_P)
MESSAGE(FATAL_ERROR "Unsupported architecture (pointer size is ${CMAKE_SIZEOF_VOID_P} bytes)")
ELSE()
MESSAGE(FATAL_ERROR "Unsupported architecture (CMAKE_SIZEOF_VOID_P is unset)")
ENDIF()
CONFIGURE_FILE(features.h.in git2/sys/features.h)
IDE_SPLIT_SOURCES(git2internal)
LIST(APPEND LIBGIT2_OBJECTS $<TARGET_OBJECTS:git2internal>)
TARGET_INCLUDE_DIRECTORIES(git2internal PRIVATE ${LIBGIT2_INCLUDES} PUBLIC ${libgit2_SOURCE_DIR}/include)
TARGET_INCLUDE_DIRECTORIES(git2internal SYSTEM PRIVATE ${LIBGIT2_SYSTEM_INCLUDES})
SET(LIBGIT2_OBJECTS ${LIBGIT2_OBJECTS} PARENT_SCOPE)
SET(LIBGIT2_INCLUDES ${LIBGIT2_INCLUDES} PARENT_SCOPE)
SET(LIBGIT2_SYSTEM_INCLUDES ${LIBGIT2_SYSTEM_INCLUDES} PARENT_SCOPE)
SET(LIBGIT2_LIBS ${LIBGIT2_LIBS} PARENT_SCOPE)
IF(XCODE_VERSION)
# This is required for Xcode to actually link the libgit2 library
# when using only object libraries.
FILE(WRITE ${CMAKE_CURRENT_BINARY_DIR}/dummy.c "")
LIST(APPEND LIBGIT2_OBJECTS ${CMAKE_CURRENT_BINARY_DIR}/dummy.c)
ENDIF()
# Compile and link libgit2
ADD_LIBRARY(git2 ${WIN_RC} ${LIBGIT2_OBJECTS})
TARGET_LINK_LIBRARIES(git2 ${LIBGIT2_LIBS})
SET_TARGET_PROPERTIES(git2 PROPERTIES C_STANDARD 90)
SET_TARGET_PROPERTIES(git2 PROPERTIES LIBRARY_OUTPUT_DIRECTORY ${libgit2_BINARY_DIR})
SET_TARGET_PROPERTIES(git2 PROPERTIES RUNTIME_OUTPUT_DIRECTORY ${libgit2_BINARY_DIR})
SET_TARGET_PROPERTIES(git2 PROPERTIES ARCHIVE_OUTPUT_DIRECTORY ${libgit2_BINARY_DIR})
# Workaround for Cmake bug #0011240 (see http://public.kitware.com/Bug/view.php?id=11240)
# Win64+MSVC+static libs = linker error
IF(MSVC AND GIT_ARCH_64 AND NOT BUILD_SHARED_LIBS)
SET_TARGET_PROPERTIES(git2 PROPERTIES STATIC_LIBRARY_FLAGS "/MACHINE:x64")
ENDIF()
IDE_SPLIT_SOURCES(git2)
if(SONAME)
set_target_properties(git2 PROPERTIES VERSION ${libgit2_VERSION})
set_target_properties(git2 PROPERTIES SOVERSION "${libgit2_VERSION_MAJOR}.${libgit2_VERSION_MINOR}")
if(LIBGIT2_FILENAME)
target_compile_definitions(git2 PRIVATE LIBGIT2_FILENAME=\"${LIBGIT2_FILENAME}\")
set_target_properties(git2 PROPERTIES OUTPUT_NAME ${LIBGIT2_FILENAME})
elseif(DEFINED LIBGIT2_PREFIX)
set_target_properties(git2 PROPERTIES PREFIX "${LIBGIT2_PREFIX}")
endif()
endif()
PKG_BUILD_CONFIG(NAME libgit2
VERSION ${libgit2_VERSION}
DESCRIPTION "The git library, take 2"
LIBS_SELF git2
PRIVATE_LIBS ${LIBGIT2_PC_LIBS}
REQUIRES ${LIBGIT2_PC_REQUIRES}
)
IF (MSVC_IDE)
# Precompiled headers
SET_TARGET_PROPERTIES(git2 PROPERTIES COMPILE_FLAGS "/Yuprecompiled.h /FIprecompiled.h")
SET_SOURCE_FILES_PROPERTIES(win32/precompiled.c COMPILE_FLAGS "/Ycprecompiled.h")
ENDIF ()
# Install
INSTALL(TARGETS git2
RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR}
LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR}
ARCHIVE DESTINATION ${CMAKE_INSTALL_LIBDIR}
)
INSTALL(DIRECTORY ${libgit2_SOURCE_DIR}/include/git2 DESTINATION ${CMAKE_INSTALL_INCLUDEDIR})
INSTALL(FILES ${libgit2_SOURCE_DIR}/include/git2.h DESTINATION ${CMAKE_INSTALL_INCLUDEDIR})
|
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.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_threadstate_h__
#define INCLUDE_threadstate_h__
#include "common.h"
typedef struct {
git_error *last_error;
git_error error_t;
git_buf error_buf;
char oid_fmt[GIT_OID_HEXSZ+1];
} git_threadstate;
extern int git_threadstate_global_init(void);
extern git_threadstate *git_threadstate_get(void);
#define GIT_THREADSTATE (git_threadstate_get())
#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/path.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 "path.h"
#include "posix.h"
#include "repository.h"
#ifdef GIT_WIN32
#include "win32/posix.h"
#include "win32/w32_buffer.h"
#include "win32/w32_util.h"
#include "win32/version.h"
#include <aclapi.h>
#else
#include <dirent.h>
#endif
#include <stdio.h>
#include <ctype.h>
static int dos_drive_prefix_length(const char *path)
{
int i;
/*
* Does it start with an ASCII letter (i.e. highest bit not set),
* followed by a colon?
*/
if (!(0x80 & (unsigned char)*path))
return *path && path[1] == ':' ? 2 : 0;
/*
* While drive letters must be letters of the English alphabet, it is
* possible to assign virtually _any_ Unicode character via `subst` as
* a drive letter to "virtual drives". Even `1`, or `ä`. Or fun stuff
* like this:
*
* subst ֍: %USERPROFILE%\Desktop
*/
for (i = 1; i < 4 && (0x80 & (unsigned char)path[i]); i++)
; /* skip first UTF-8 character */
return path[i] == ':' ? i + 1 : 0;
}
#ifdef GIT_WIN32
static bool looks_like_network_computer_name(const char *path, int pos)
{
if (pos < 3)
return false;
if (path[0] != '/' || path[1] != '/')
return false;
while (pos-- > 2) {
if (path[pos] == '/')
return false;
}
return true;
}
#endif
/*
* Based on the Android implementation, BSD licensed.
* http://android.git.kernel.org/
*
* Copyright (C) 2008 The Android Open Source Project
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* AS IS AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
* OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
* AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*/
int git_path_basename_r(git_buf *buffer, const char *path)
{
const char *endp, *startp;
int len, result;
/* Empty or NULL string gets treated as "." */
if (path == NULL || *path == '\0') {
startp = ".";
len = 1;
goto Exit;
}
/* Strip trailing slashes */
endp = path + strlen(path) - 1;
while (endp > path && *endp == '/')
endp--;
/* All slashes becomes "/" */
if (endp == path && *endp == '/') {
startp = "/";
len = 1;
goto Exit;
}
/* Find the start of the base */
startp = endp;
while (startp > path && *(startp - 1) != '/')
startp--;
/* Cast is safe because max path < max int */
len = (int)(endp - startp + 1);
Exit:
result = len;
if (buffer != NULL && git_buf_set(buffer, startp, len) < 0)
return -1;
return result;
}
/*
* Determine if the path is a Windows prefix and, if so, returns
* its actual lentgh. If it is not a prefix, returns -1.
*/
static int win32_prefix_length(const char *path, int len)
{
#ifndef GIT_WIN32
GIT_UNUSED(path);
GIT_UNUSED(len);
#else
/*
* Mimic unix behavior where '/.git' returns '/': 'C:/.git'
* will return 'C:/' here
*/
if (dos_drive_prefix_length(path) == len)
return len;
/*
* Similarly checks if we're dealing with a network computer name
* '//computername/.git' will return '//computername/'
*/
if (looks_like_network_computer_name(path, len))
return len;
#endif
return -1;
}
/*
* Based on the Android implementation, BSD licensed.
* Check http://android.git.kernel.org/
*/
int git_path_dirname_r(git_buf *buffer, const char *path)
{
const char *endp;
int is_prefix = 0, len;
/* Empty or NULL string gets treated as "." */
if (path == NULL || *path == '\0') {
path = ".";
len = 1;
goto Exit;
}
/* Strip trailing slashes */
endp = path + strlen(path) - 1;
while (endp > path && *endp == '/')
endp--;
if (endp - path + 1 > INT_MAX) {
git_error_set(GIT_ERROR_INVALID, "path too long");
len = -1;
goto Exit;
}
if ((len = win32_prefix_length(path, (int)(endp - path + 1))) > 0) {
is_prefix = 1;
goto Exit;
}
/* Find the start of the dir */
while (endp > path && *endp != '/')
endp--;
/* Either the dir is "/" or there are no slashes */
if (endp == path) {
path = (*endp == '/') ? "/" : ".";
len = 1;
goto Exit;
}
do {
endp--;
} while (endp > path && *endp == '/');
if (endp - path + 1 > INT_MAX) {
git_error_set(GIT_ERROR_INVALID, "path too long");
len = -1;
goto Exit;
}
if ((len = win32_prefix_length(path, (int)(endp - path + 1))) > 0) {
is_prefix = 1;
goto Exit;
}
/* Cast is safe because max path < max int */
len = (int)(endp - path + 1);
Exit:
if (buffer) {
if (git_buf_set(buffer, path, len) < 0)
return -1;
if (is_prefix && git_buf_putc(buffer, '/') < 0)
return -1;
}
return len;
}
char *git_path_dirname(const char *path)
{
git_buf buf = GIT_BUF_INIT;
char *dirname;
git_path_dirname_r(&buf, path);
dirname = git_buf_detach(&buf);
git_buf_dispose(&buf); /* avoid memleak if error occurs */
return dirname;
}
char *git_path_basename(const char *path)
{
git_buf buf = GIT_BUF_INIT;
char *basename;
git_path_basename_r(&buf, path);
basename = git_buf_detach(&buf);
git_buf_dispose(&buf); /* avoid memleak if error occurs */
return basename;
}
size_t git_path_basename_offset(git_buf *buffer)
{
ssize_t slash;
if (!buffer || buffer->size <= 0)
return 0;
slash = git_buf_rfind_next(buffer, '/');
if (slash >= 0 && buffer->ptr[slash] == '/')
return (size_t)(slash + 1);
return 0;
}
int git_path_root(const char *path)
{
int offset = 0, prefix_len;
/* Does the root of the path look like a windows drive ? */
if ((prefix_len = dos_drive_prefix_length(path)))
offset += prefix_len;
#ifdef GIT_WIN32
/* Are we dealing with a windows network path? */
else if ((path[0] == '/' && path[1] == '/' && path[2] != '/') ||
(path[0] == '\\' && path[1] == '\\' && path[2] != '\\'))
{
offset += 2;
/* Skip the computer name segment */
while (path[offset] && path[offset] != '/' && path[offset] != '\\')
offset++;
}
if (path[offset] == '\\')
return offset;
#endif
if (path[offset] == '/')
return offset;
return -1; /* Not a real error - signals that path is not rooted */
}
static void path_trim_slashes(git_buf *path)
{
int ceiling = git_path_root(path->ptr) + 1;
if (ceiling < 0)
return;
while (path->size > (size_t)ceiling) {
if (path->ptr[path->size-1] != '/')
break;
path->ptr[path->size-1] = '\0';
path->size--;
}
}
int git_path_join_unrooted(
git_buf *path_out, const char *path, const char *base, ssize_t *root_at)
{
ssize_t root;
GIT_ASSERT_ARG(path_out);
GIT_ASSERT_ARG(path);
root = (ssize_t)git_path_root(path);
if (base != NULL && root < 0) {
if (git_buf_joinpath(path_out, base, path) < 0)
return -1;
root = (ssize_t)strlen(base);
} else {
if (git_buf_sets(path_out, path) < 0)
return -1;
if (root < 0)
root = 0;
else if (base)
git_path_equal_or_prefixed(base, path, &root);
}
if (root_at)
*root_at = root;
return 0;
}
void git_path_squash_slashes(git_buf *path)
{
char *p, *q;
if (path->size == 0)
return;
for (p = path->ptr, q = path->ptr; *q; p++, q++) {
*p = *q;
while (*q == '/' && *(q+1) == '/') {
path->size--;
q++;
}
}
*p = '\0';
}
int git_path_prettify(git_buf *path_out, const char *path, const char *base)
{
char buf[GIT_PATH_MAX];
GIT_ASSERT_ARG(path_out);
GIT_ASSERT_ARG(path);
/* construct path if needed */
if (base != NULL && git_path_root(path) < 0) {
if (git_buf_joinpath(path_out, base, path) < 0)
return -1;
path = path_out->ptr;
}
if (p_realpath(path, buf) == NULL) {
/* git_error_set resets the errno when dealing with a GIT_ERROR_OS kind of error */
int error = (errno == ENOENT || errno == ENOTDIR) ? GIT_ENOTFOUND : -1;
git_error_set(GIT_ERROR_OS, "failed to resolve path '%s'", path);
git_buf_clear(path_out);
return error;
}
return git_buf_sets(path_out, buf);
}
int git_path_prettify_dir(git_buf *path_out, const char *path, const char *base)
{
int error = git_path_prettify(path_out, path, base);
return (error < 0) ? error : git_path_to_dir(path_out);
}
int git_path_to_dir(git_buf *path)
{
if (path->asize > 0 &&
git_buf_len(path) > 0 &&
path->ptr[git_buf_len(path) - 1] != '/')
git_buf_putc(path, '/');
return git_buf_oom(path) ? -1 : 0;
}
void git_path_string_to_dir(char *path, size_t size)
{
size_t end = strlen(path);
if (end && path[end - 1] != '/' && end < size) {
path[end] = '/';
path[end + 1] = '\0';
}
}
int git__percent_decode(git_buf *decoded_out, const char *input)
{
int len, hi, lo, i;
GIT_ASSERT_ARG(decoded_out);
GIT_ASSERT_ARG(input);
len = (int)strlen(input);
git_buf_clear(decoded_out);
for(i = 0; i < len; i++)
{
char c = input[i];
if (c != '%')
goto append;
if (i >= len - 2)
goto append;
hi = git__fromhex(input[i + 1]);
lo = git__fromhex(input[i + 2]);
if (hi < 0 || lo < 0)
goto append;
c = (char)(hi << 4 | lo);
i += 2;
append:
if (git_buf_putc(decoded_out, c) < 0)
return -1;
}
return 0;
}
static int error_invalid_local_file_uri(const char *uri)
{
git_error_set(GIT_ERROR_CONFIG, "'%s' is not a valid local file URI", uri);
return -1;
}
static int local_file_url_prefixlen(const char *file_url)
{
int len = -1;
if (git__prefixcmp(file_url, "file://") == 0) {
if (file_url[7] == '/')
len = 8;
else if (git__prefixcmp(file_url + 7, "localhost/") == 0)
len = 17;
}
return len;
}
bool git_path_is_local_file_url(const char *file_url)
{
return (local_file_url_prefixlen(file_url) > 0);
}
int git_path_fromurl(git_buf *local_path_out, const char *file_url)
{
int offset;
GIT_ASSERT_ARG(local_path_out);
GIT_ASSERT_ARG(file_url);
if ((offset = local_file_url_prefixlen(file_url)) < 0 ||
file_url[offset] == '\0' || file_url[offset] == '/')
return error_invalid_local_file_uri(file_url);
#ifndef GIT_WIN32
offset--; /* A *nix absolute path starts with a forward slash */
#endif
git_buf_clear(local_path_out);
return git__percent_decode(local_path_out, file_url + offset);
}
int git_path_walk_up(
git_buf *path,
const char *ceiling,
int (*cb)(void *data, const char *),
void *data)
{
int error = 0;
git_buf iter;
ssize_t stop = 0, scan;
char oldc = '\0';
GIT_ASSERT_ARG(path);
GIT_ASSERT_ARG(cb);
if (ceiling != NULL) {
if (git__prefixcmp(path->ptr, ceiling) == 0)
stop = (ssize_t)strlen(ceiling);
else
stop = git_buf_len(path);
}
scan = git_buf_len(path);
/* empty path: yield only once */
if (!scan) {
error = cb(data, "");
if (error)
git_error_set_after_callback(error);
return error;
}
iter.ptr = path->ptr;
iter.size = git_buf_len(path);
iter.asize = path->asize;
while (scan >= stop) {
error = cb(data, iter.ptr);
iter.ptr[scan] = oldc;
if (error) {
git_error_set_after_callback(error);
break;
}
scan = git_buf_rfind_next(&iter, '/');
if (scan >= 0) {
scan++;
oldc = iter.ptr[scan];
iter.size = scan;
iter.ptr[scan] = '\0';
}
}
if (scan >= 0)
iter.ptr[scan] = oldc;
/* relative path: yield for the last component */
if (!error && stop == 0 && iter.ptr[0] != '/') {
error = cb(data, "");
if (error)
git_error_set_after_callback(error);
}
return error;
}
bool git_path_exists(const char *path)
{
GIT_ASSERT_ARG_WITH_RETVAL(path, false);
return p_access(path, F_OK) == 0;
}
bool git_path_isdir(const char *path)
{
struct stat st;
if (p_stat(path, &st) < 0)
return false;
return S_ISDIR(st.st_mode) != 0;
}
bool git_path_isfile(const char *path)
{
struct stat st;
GIT_ASSERT_ARG_WITH_RETVAL(path, false);
if (p_stat(path, &st) < 0)
return false;
return S_ISREG(st.st_mode) != 0;
}
bool git_path_islink(const char *path)
{
struct stat st;
GIT_ASSERT_ARG_WITH_RETVAL(path, false);
if (p_lstat(path, &st) < 0)
return false;
return S_ISLNK(st.st_mode) != 0;
}
#ifdef GIT_WIN32
bool git_path_is_empty_dir(const char *path)
{
git_win32_path filter_w;
bool empty = false;
if (git_win32__findfirstfile_filter(filter_w, path)) {
WIN32_FIND_DATAW findData;
HANDLE hFind = FindFirstFileW(filter_w, &findData);
/* FindFirstFile will fail if there are no children to the given
* path, which can happen if the given path is a file (and obviously
* has no children) or if the given path is an empty mount point.
* (Most directories have at least directory entries '.' and '..',
* but ridiculously another volume mounted in another drive letter's
* path space do not, and thus have nothing to enumerate.) If
* FindFirstFile fails, check if this is a directory-like thing
* (a mount point).
*/
if (hFind == INVALID_HANDLE_VALUE)
return git_path_isdir(path);
/* If the find handle was created successfully, then it's a directory */
empty = true;
do {
/* Allow the enumeration to return . and .. and still be considered
* empty. In the special case of drive roots (i.e. C:\) where . and
* .. do not occur, we can still consider the path to be an empty
* directory if there's nothing there. */
if (!git_path_is_dot_or_dotdotW(findData.cFileName)) {
empty = false;
break;
}
} while (FindNextFileW(hFind, &findData));
FindClose(hFind);
}
return empty;
}
#else
static int path_found_entry(void *payload, git_buf *path)
{
GIT_UNUSED(payload);
return !git_path_is_dot_or_dotdot(path->ptr);
}
bool git_path_is_empty_dir(const char *path)
{
int error;
git_buf dir = GIT_BUF_INIT;
if (!git_path_isdir(path))
return false;
if ((error = git_buf_sets(&dir, path)) != 0)
git_error_clear();
else
error = git_path_direach(&dir, 0, path_found_entry, NULL);
git_buf_dispose(&dir);
return !error;
}
#endif
int git_path_set_error(int errno_value, const char *path, const char *action)
{
switch (errno_value) {
case ENOENT:
case ENOTDIR:
git_error_set(GIT_ERROR_OS, "could not find '%s' to %s", path, action);
return GIT_ENOTFOUND;
case EINVAL:
case ENAMETOOLONG:
git_error_set(GIT_ERROR_OS, "invalid path for filesystem '%s'", path);
return GIT_EINVALIDSPEC;
case EEXIST:
git_error_set(GIT_ERROR_OS, "failed %s - '%s' already exists", action, path);
return GIT_EEXISTS;
case EACCES:
git_error_set(GIT_ERROR_OS, "failed %s - '%s' is locked", action, path);
return GIT_ELOCKED;
default:
git_error_set(GIT_ERROR_OS, "could not %s '%s'", action, path);
return -1;
}
}
int git_path_lstat(const char *path, struct stat *st)
{
if (p_lstat(path, st) == 0)
return 0;
return git_path_set_error(errno, path, "stat");
}
static bool _check_dir_contents(
git_buf *dir,
const char *sub,
bool (*predicate)(const char *))
{
bool result;
size_t dir_size = git_buf_len(dir);
size_t sub_size = strlen(sub);
size_t alloc_size;
/* leave base valid even if we could not make space for subdir */
if (GIT_ADD_SIZET_OVERFLOW(&alloc_size, dir_size, sub_size) ||
GIT_ADD_SIZET_OVERFLOW(&alloc_size, alloc_size, 2) ||
git_buf_try_grow(dir, alloc_size, false) < 0)
return false;
/* save excursion */
if (git_buf_joinpath(dir, dir->ptr, sub) < 0)
return false;
result = predicate(dir->ptr);
/* restore path */
git_buf_truncate(dir, dir_size);
return result;
}
bool git_path_contains(git_buf *dir, const char *item)
{
return _check_dir_contents(dir, item, &git_path_exists);
}
bool git_path_contains_dir(git_buf *base, const char *subdir)
{
return _check_dir_contents(base, subdir, &git_path_isdir);
}
bool git_path_contains_file(git_buf *base, const char *file)
{
return _check_dir_contents(base, file, &git_path_isfile);
}
int git_path_find_dir(git_buf *dir)
{
int error = 0;
char buf[GIT_PATH_MAX];
if (p_realpath(dir->ptr, buf) != NULL)
error = git_buf_sets(dir, buf);
/* call dirname if this is not a directory */
if (!error) /* && git_path_isdir(dir->ptr) == false) */
error = (git_path_dirname_r(dir, dir->ptr) < 0) ? -1 : 0;
if (!error)
error = git_path_to_dir(dir);
return error;
}
int git_path_resolve_relative(git_buf *path, size_t ceiling)
{
char *base, *to, *from, *next;
size_t len;
GIT_ERROR_CHECK_ALLOC_BUF(path);
if (ceiling > path->size)
ceiling = path->size;
/* recognize drive prefixes, etc. that should not be backed over */
if (ceiling == 0)
ceiling = git_path_root(path->ptr) + 1;
/* recognize URL prefixes that should not be backed over */
if (ceiling == 0) {
for (next = path->ptr; *next && git__isalpha(*next); ++next);
if (next[0] == ':' && next[1] == '/' && next[2] == '/')
ceiling = (next + 3) - path->ptr;
}
base = to = from = path->ptr + ceiling;
while (*from) {
for (next = from; *next && *next != '/'; ++next);
len = next - from;
if (len == 1 && from[0] == '.')
/* do nothing with singleton dot */;
else if (len == 2 && from[0] == '.' && from[1] == '.') {
/* error out if trying to up one from a hard base */
if (to == base && ceiling != 0) {
git_error_set(GIT_ERROR_INVALID,
"cannot strip root component off url");
return -1;
}
/* no more path segments to strip,
* use '../' as a new base path */
if (to == base) {
if (*next == '/')
len++;
if (to != from)
memmove(to, from, len);
to += len;
/* this is now the base, can't back up from a
* relative prefix */
base = to;
} else {
/* back up a path segment */
while (to > base && to[-1] == '/') to--;
while (to > base && to[-1] != '/') to--;
}
} else {
if (*next == '/' && *from != '/')
len++;
if (to != from)
memmove(to, from, len);
to += len;
}
from += len;
while (*from == '/') from++;
}
*to = '\0';
path->size = to - path->ptr;
return 0;
}
int git_path_apply_relative(git_buf *target, const char *relpath)
{
return git_buf_joinpath(target, git_buf_cstr(target), relpath) ||
git_path_resolve_relative(target, 0);
}
int git_path_cmp(
const char *name1, size_t len1, int isdir1,
const char *name2, size_t len2, int isdir2,
int (*compare)(const char *, const char *, size_t))
{
unsigned char c1, c2;
size_t len = len1 < len2 ? len1 : len2;
int cmp;
cmp = compare(name1, name2, len);
if (cmp)
return cmp;
c1 = name1[len];
c2 = name2[len];
if (c1 == '\0' && isdir1)
c1 = '/';
if (c2 == '\0' && isdir2)
c2 = '/';
return (c1 < c2) ? -1 : (c1 > c2) ? 1 : 0;
}
size_t git_path_common_dirlen(const char *one, const char *two)
{
const char *p, *q, *dirsep = NULL;
for (p = one, q = two; *p && *q; p++, q++) {
if (*p == '/' && *q == '/')
dirsep = p;
else if (*p != *q)
break;
}
return dirsep ? (dirsep - one) + 1 : 0;
}
int git_path_make_relative(git_buf *path, const char *parent)
{
const char *p, *q, *p_dirsep, *q_dirsep;
size_t plen = path->size, newlen, alloclen, depth = 1, i, offset;
for (p_dirsep = p = path->ptr, q_dirsep = q = parent; *p && *q; p++, q++) {
if (*p == '/' && *q == '/') {
p_dirsep = p;
q_dirsep = q;
}
else if (*p != *q)
break;
}
/* need at least 1 common path segment */
if ((p_dirsep == path->ptr || q_dirsep == parent) &&
(*p_dirsep != '/' || *q_dirsep != '/')) {
git_error_set(GIT_ERROR_INVALID,
"%s is not a parent of %s", parent, path->ptr);
return GIT_ENOTFOUND;
}
if (*p == '/' && !*q)
p++;
else if (!*p && *q == '/')
q++;
else if (!*p && !*q)
return git_buf_clear(path), 0;
else {
p = p_dirsep + 1;
q = q_dirsep + 1;
}
plen -= (p - path->ptr);
if (!*q)
return git_buf_set(path, p, plen);
for (; (q = strchr(q, '/')) && *(q + 1); q++)
depth++;
GIT_ERROR_CHECK_ALLOC_MULTIPLY(&newlen, depth, 3);
GIT_ERROR_CHECK_ALLOC_ADD(&newlen, newlen, plen);
GIT_ERROR_CHECK_ALLOC_ADD(&alloclen, newlen, 1);
/* save the offset as we might realllocate the pointer */
offset = p - path->ptr;
if (git_buf_try_grow(path, alloclen, 1) < 0)
return -1;
p = path->ptr + offset;
memmove(path->ptr + (depth * 3), p, plen + 1);
for (i = 0; i < depth; i++)
memcpy(path->ptr + (i * 3), "../", 3);
path->size = newlen;
return 0;
}
bool git_path_has_non_ascii(const char *path, size_t pathlen)
{
const uint8_t *scan = (const uint8_t *)path, *end;
for (end = scan + pathlen; scan < end; ++scan)
if (*scan & 0x80)
return true;
return false;
}
#ifdef GIT_USE_ICONV
int git_path_iconv_init_precompose(git_path_iconv_t *ic)
{
git_buf_init(&ic->buf, 0);
ic->map = iconv_open(GIT_PATH_REPO_ENCODING, GIT_PATH_NATIVE_ENCODING);
return 0;
}
void git_path_iconv_clear(git_path_iconv_t *ic)
{
if (ic) {
if (ic->map != (iconv_t)-1)
iconv_close(ic->map);
git_buf_dispose(&ic->buf);
}
}
int git_path_iconv(git_path_iconv_t *ic, const char **in, size_t *inlen)
{
char *nfd = (char*)*in, *nfc;
size_t nfdlen = *inlen, nfclen, wantlen = nfdlen, alloclen, rv;
int retry = 1;
if (!ic || ic->map == (iconv_t)-1 ||
!git_path_has_non_ascii(*in, *inlen))
return 0;
git_buf_clear(&ic->buf);
while (1) {
GIT_ERROR_CHECK_ALLOC_ADD(&alloclen, wantlen, 1);
if (git_buf_grow(&ic->buf, alloclen) < 0)
return -1;
nfc = ic->buf.ptr + ic->buf.size;
nfclen = ic->buf.asize - ic->buf.size;
rv = iconv(ic->map, &nfd, &nfdlen, &nfc, &nfclen);
ic->buf.size = (nfc - ic->buf.ptr);
if (rv != (size_t)-1)
break;
/* if we cannot convert the data (probably because iconv thinks
* it is not valid UTF-8 source data), then use original data
*/
if (errno != E2BIG)
return 0;
/* make space for 2x the remaining data to be converted
* (with per retry overhead to avoid infinite loops)
*/
wantlen = ic->buf.size + max(nfclen, nfdlen) * 2 + (size_t)(retry * 4);
if (retry++ > 4)
goto fail;
}
ic->buf.ptr[ic->buf.size] = '\0';
*in = ic->buf.ptr;
*inlen = ic->buf.size;
return 0;
fail:
git_error_set(GIT_ERROR_OS, "unable to convert unicode path data");
return -1;
}
static const char *nfc_file = "\xC3\x85\x73\x74\x72\xC3\xB6\x6D.XXXXXX";
static const char *nfd_file = "\x41\xCC\x8A\x73\x74\x72\x6F\xCC\x88\x6D.XXXXXX";
/* Check if the platform is decomposing unicode data for us. We will
* emulate core Git and prefer to use precomposed unicode data internally
* on these platforms, composing the decomposed unicode on the fly.
*
* This mainly happens on the Mac where HDFS stores filenames as
* decomposed unicode. Even on VFAT and SAMBA file systems, the Mac will
* return decomposed unicode from readdir() even when the actual
* filesystem is storing precomposed unicode.
*/
bool git_path_does_fs_decompose_unicode(const char *root)
{
git_buf path = GIT_BUF_INIT;
int fd;
bool found_decomposed = false;
char tmp[6];
/* Create a file using a precomposed path and then try to find it
* using the decomposed name. If the lookup fails, then we will mark
* that we should precompose unicode for this repository.
*/
if (git_buf_joinpath(&path, root, nfc_file) < 0 ||
(fd = p_mkstemp(path.ptr)) < 0)
goto done;
p_close(fd);
/* record trailing digits generated by mkstemp */
memcpy(tmp, path.ptr + path.size - sizeof(tmp), sizeof(tmp));
/* try to look up as NFD path */
if (git_buf_joinpath(&path, root, nfd_file) < 0)
goto done;
memcpy(path.ptr + path.size - sizeof(tmp), tmp, sizeof(tmp));
found_decomposed = git_path_exists(path.ptr);
/* remove temporary file (using original precomposed path) */
if (git_buf_joinpath(&path, root, nfc_file) < 0)
goto done;
memcpy(path.ptr + path.size - sizeof(tmp), tmp, sizeof(tmp));
(void)p_unlink(path.ptr);
done:
git_buf_dispose(&path);
return found_decomposed;
}
#else
bool git_path_does_fs_decompose_unicode(const char *root)
{
GIT_UNUSED(root);
return false;
}
#endif
#if defined(__sun) || defined(__GNU__)
typedef char path_dirent_data[sizeof(struct dirent) + FILENAME_MAX + 1];
#else
typedef struct dirent path_dirent_data;
#endif
int git_path_direach(
git_buf *path,
uint32_t flags,
int (*fn)(void *, git_buf *),
void *arg)
{
int error = 0;
ssize_t wd_len;
DIR *dir;
struct dirent *de;
#ifdef GIT_USE_ICONV
git_path_iconv_t ic = GIT_PATH_ICONV_INIT;
#endif
GIT_UNUSED(flags);
if (git_path_to_dir(path) < 0)
return -1;
wd_len = git_buf_len(path);
if ((dir = opendir(path->ptr)) == NULL) {
git_error_set(GIT_ERROR_OS, "failed to open directory '%s'", path->ptr);
if (errno == ENOENT)
return GIT_ENOTFOUND;
return -1;
}
#ifdef GIT_USE_ICONV
if ((flags & GIT_PATH_DIR_PRECOMPOSE_UNICODE) != 0)
(void)git_path_iconv_init_precompose(&ic);
#endif
while ((de = readdir(dir)) != NULL) {
const char *de_path = de->d_name;
size_t de_len = strlen(de_path);
if (git_path_is_dot_or_dotdot(de_path))
continue;
#ifdef GIT_USE_ICONV
if ((error = git_path_iconv(&ic, &de_path, &de_len)) < 0)
break;
#endif
if ((error = git_buf_put(path, de_path, de_len)) < 0)
break;
git_error_clear();
error = fn(arg, path);
git_buf_truncate(path, wd_len); /* restore path */
/* Only set our own error if the callback did not set one already */
if (error != 0) {
if (!git_error_last())
git_error_set_after_callback(error);
break;
}
}
closedir(dir);
#ifdef GIT_USE_ICONV
git_path_iconv_clear(&ic);
#endif
return error;
}
#if defined(GIT_WIN32) && !defined(__MINGW32__)
/* Using _FIND_FIRST_EX_LARGE_FETCH may increase performance in Windows 7
* and better.
*/
#ifndef FIND_FIRST_EX_LARGE_FETCH
# define FIND_FIRST_EX_LARGE_FETCH 2
#endif
int git_path_diriter_init(
git_path_diriter *diriter,
const char *path,
unsigned int flags)
{
git_win32_path path_filter;
static int is_win7_or_later = -1;
if (is_win7_or_later < 0)
is_win7_or_later = git_has_win32_version(6, 1, 0);
GIT_ASSERT_ARG(diriter);
GIT_ASSERT_ARG(path);
memset(diriter, 0, sizeof(git_path_diriter));
diriter->handle = INVALID_HANDLE_VALUE;
if (git_buf_puts(&diriter->path_utf8, path) < 0)
return -1;
path_trim_slashes(&diriter->path_utf8);
if (diriter->path_utf8.size == 0) {
git_error_set(GIT_ERROR_FILESYSTEM, "could not open directory '%s'", path);
return -1;
}
if ((diriter->parent_len = git_win32_path_from_utf8(diriter->path, diriter->path_utf8.ptr)) < 0 ||
!git_win32__findfirstfile_filter(path_filter, diriter->path_utf8.ptr)) {
git_error_set(GIT_ERROR_OS, "could not parse the directory path '%s'", path);
return -1;
}
diriter->handle = FindFirstFileExW(
path_filter,
is_win7_or_later ? FindExInfoBasic : FindExInfoStandard,
&diriter->current,
FindExSearchNameMatch,
NULL,
is_win7_or_later ? FIND_FIRST_EX_LARGE_FETCH : 0);
if (diriter->handle == INVALID_HANDLE_VALUE) {
git_error_set(GIT_ERROR_OS, "could not open directory '%s'", path);
return -1;
}
diriter->parent_utf8_len = diriter->path_utf8.size;
diriter->flags = flags;
return 0;
}
static int diriter_update_paths(git_path_diriter *diriter)
{
size_t filename_len, path_len;
filename_len = wcslen(diriter->current.cFileName);
if (GIT_ADD_SIZET_OVERFLOW(&path_len, diriter->parent_len, filename_len) ||
GIT_ADD_SIZET_OVERFLOW(&path_len, path_len, 2))
return -1;
if (path_len > GIT_WIN_PATH_UTF16) {
git_error_set(GIT_ERROR_FILESYSTEM,
"invalid path '%.*ls\\%ls' (path too long)",
diriter->parent_len, diriter->path, diriter->current.cFileName);
return -1;
}
diriter->path[diriter->parent_len] = L'\\';
memcpy(&diriter->path[diriter->parent_len+1],
diriter->current.cFileName, filename_len * sizeof(wchar_t));
diriter->path[path_len-1] = L'\0';
git_buf_truncate(&diriter->path_utf8, diriter->parent_utf8_len);
if (diriter->parent_utf8_len > 0 &&
diriter->path_utf8.ptr[diriter->parent_utf8_len-1] != '/')
git_buf_putc(&diriter->path_utf8, '/');
git_buf_put_w(&diriter->path_utf8, diriter->current.cFileName, filename_len);
if (git_buf_oom(&diriter->path_utf8))
return -1;
return 0;
}
int git_path_diriter_next(git_path_diriter *diriter)
{
bool skip_dot = !(diriter->flags & GIT_PATH_DIR_INCLUDE_DOT_AND_DOTDOT);
do {
/* Our first time through, we already have the data from
* FindFirstFileW. Use it, otherwise get the next file.
*/
if (!diriter->needs_next)
diriter->needs_next = 1;
else if (!FindNextFileW(diriter->handle, &diriter->current))
return GIT_ITEROVER;
} while (skip_dot && git_path_is_dot_or_dotdotW(diriter->current.cFileName));
if (diriter_update_paths(diriter) < 0)
return -1;
return 0;
}
int git_path_diriter_filename(
const char **out,
size_t *out_len,
git_path_diriter *diriter)
{
GIT_ASSERT_ARG(out);
GIT_ASSERT_ARG(out_len);
GIT_ASSERT_ARG(diriter);
GIT_ASSERT(diriter->path_utf8.size > diriter->parent_utf8_len);
*out = &diriter->path_utf8.ptr[diriter->parent_utf8_len+1];
*out_len = diriter->path_utf8.size - diriter->parent_utf8_len - 1;
return 0;
}
int git_path_diriter_fullpath(
const char **out,
size_t *out_len,
git_path_diriter *diriter)
{
GIT_ASSERT_ARG(out);
GIT_ASSERT_ARG(out_len);
GIT_ASSERT_ARG(diriter);
*out = diriter->path_utf8.ptr;
*out_len = diriter->path_utf8.size;
return 0;
}
int git_path_diriter_stat(struct stat *out, git_path_diriter *diriter)
{
GIT_ASSERT_ARG(out);
GIT_ASSERT_ARG(diriter);
return git_win32__file_attribute_to_stat(out,
(WIN32_FILE_ATTRIBUTE_DATA *)&diriter->current,
diriter->path);
}
void git_path_diriter_free(git_path_diriter *diriter)
{
if (diriter == NULL)
return;
git_buf_dispose(&diriter->path_utf8);
if (diriter->handle != INVALID_HANDLE_VALUE) {
FindClose(diriter->handle);
diriter->handle = INVALID_HANDLE_VALUE;
}
}
#else
int git_path_diriter_init(
git_path_diriter *diriter,
const char *path,
unsigned int flags)
{
GIT_ASSERT_ARG(diriter);
GIT_ASSERT_ARG(path);
memset(diriter, 0, sizeof(git_path_diriter));
if (git_buf_puts(&diriter->path, path) < 0)
return -1;
path_trim_slashes(&diriter->path);
if (diriter->path.size == 0) {
git_error_set(GIT_ERROR_FILESYSTEM, "could not open directory '%s'", path);
return -1;
}
if ((diriter->dir = opendir(diriter->path.ptr)) == NULL) {
git_buf_dispose(&diriter->path);
git_error_set(GIT_ERROR_OS, "failed to open directory '%s'", path);
return -1;
}
#ifdef GIT_USE_ICONV
if ((flags & GIT_PATH_DIR_PRECOMPOSE_UNICODE) != 0)
(void)git_path_iconv_init_precompose(&diriter->ic);
#endif
diriter->parent_len = diriter->path.size;
diriter->flags = flags;
return 0;
}
int git_path_diriter_next(git_path_diriter *diriter)
{
struct dirent *de;
const char *filename;
size_t filename_len;
bool skip_dot = !(diriter->flags & GIT_PATH_DIR_INCLUDE_DOT_AND_DOTDOT);
int error = 0;
GIT_ASSERT_ARG(diriter);
errno = 0;
do {
if ((de = readdir(diriter->dir)) == NULL) {
if (!errno)
return GIT_ITEROVER;
git_error_set(GIT_ERROR_OS,
"could not read directory '%s'", diriter->path.ptr);
return -1;
}
} while (skip_dot && git_path_is_dot_or_dotdot(de->d_name));
filename = de->d_name;
filename_len = strlen(filename);
#ifdef GIT_USE_ICONV
if ((diriter->flags & GIT_PATH_DIR_PRECOMPOSE_UNICODE) != 0 &&
(error = git_path_iconv(&diriter->ic, &filename, &filename_len)) < 0)
return error;
#endif
git_buf_truncate(&diriter->path, diriter->parent_len);
if (diriter->parent_len > 0 &&
diriter->path.ptr[diriter->parent_len-1] != '/')
git_buf_putc(&diriter->path, '/');
git_buf_put(&diriter->path, filename, filename_len);
if (git_buf_oom(&diriter->path))
return -1;
return error;
}
int git_path_diriter_filename(
const char **out,
size_t *out_len,
git_path_diriter *diriter)
{
GIT_ASSERT_ARG(out);
GIT_ASSERT_ARG(out_len);
GIT_ASSERT_ARG(diriter);
GIT_ASSERT(diriter->path.size > diriter->parent_len);
*out = &diriter->path.ptr[diriter->parent_len+1];
*out_len = diriter->path.size - diriter->parent_len - 1;
return 0;
}
int git_path_diriter_fullpath(
const char **out,
size_t *out_len,
git_path_diriter *diriter)
{
GIT_ASSERT_ARG(out);
GIT_ASSERT_ARG(out_len);
GIT_ASSERT_ARG(diriter);
*out = diriter->path.ptr;
*out_len = diriter->path.size;
return 0;
}
int git_path_diriter_stat(struct stat *out, git_path_diriter *diriter)
{
GIT_ASSERT_ARG(out);
GIT_ASSERT_ARG(diriter);
return git_path_lstat(diriter->path.ptr, out);
}
void git_path_diriter_free(git_path_diriter *diriter)
{
if (diriter == NULL)
return;
if (diriter->dir) {
closedir(diriter->dir);
diriter->dir = NULL;
}
#ifdef GIT_USE_ICONV
git_path_iconv_clear(&diriter->ic);
#endif
git_buf_dispose(&diriter->path);
}
#endif
int git_path_dirload(
git_vector *contents,
const char *path,
size_t prefix_len,
uint32_t flags)
{
git_path_diriter iter = GIT_PATH_DIRITER_INIT;
const char *name;
size_t name_len;
char *dup;
int error;
GIT_ASSERT_ARG(contents);
GIT_ASSERT_ARG(path);
if ((error = git_path_diriter_init(&iter, path, flags)) < 0)
return error;
while ((error = git_path_diriter_next(&iter)) == 0) {
if ((error = git_path_diriter_fullpath(&name, &name_len, &iter)) < 0)
break;
GIT_ASSERT(name_len > prefix_len);
dup = git__strndup(name + prefix_len, name_len - prefix_len);
GIT_ERROR_CHECK_ALLOC(dup);
if ((error = git_vector_insert(contents, dup)) < 0)
break;
}
if (error == GIT_ITEROVER)
error = 0;
git_path_diriter_free(&iter);
return error;
}
int git_path_from_url_or_path(git_buf *local_path_out, const char *url_or_path)
{
if (git_path_is_local_file_url(url_or_path))
return git_path_fromurl(local_path_out, url_or_path);
else
return git_buf_sets(local_path_out, url_or_path);
}
/* Reject paths like AUX or COM1, or those versions that end in a dot or
* colon. ("AUX." or "AUX:")
*/
GIT_INLINE(bool) verify_dospath(
const char *component,
size_t len,
const char dospath[3],
bool trailing_num)
{
size_t last = trailing_num ? 4 : 3;
if (len < last || git__strncasecmp(component, dospath, 3) != 0)
return true;
if (trailing_num && (component[3] < '1' || component[3] > '9'))
return true;
return (len > last &&
component[last] != '.' &&
component[last] != ':');
}
static int32_t next_hfs_char(const char **in, size_t *len)
{
while (*len) {
uint32_t codepoint;
int cp_len = git_utf8_iterate(&codepoint, *in, *len);
if (cp_len < 0)
return -1;
(*in) += cp_len;
(*len) -= cp_len;
/* these code points are ignored completely */
switch (codepoint) {
case 0x200c: /* ZERO WIDTH NON-JOINER */
case 0x200d: /* ZERO WIDTH JOINER */
case 0x200e: /* LEFT-TO-RIGHT MARK */
case 0x200f: /* RIGHT-TO-LEFT MARK */
case 0x202a: /* LEFT-TO-RIGHT EMBEDDING */
case 0x202b: /* RIGHT-TO-LEFT EMBEDDING */
case 0x202c: /* POP DIRECTIONAL FORMATTING */
case 0x202d: /* LEFT-TO-RIGHT OVERRIDE */
case 0x202e: /* RIGHT-TO-LEFT OVERRIDE */
case 0x206a: /* INHIBIT SYMMETRIC SWAPPING */
case 0x206b: /* ACTIVATE SYMMETRIC SWAPPING */
case 0x206c: /* INHIBIT ARABIC FORM SHAPING */
case 0x206d: /* ACTIVATE ARABIC FORM SHAPING */
case 0x206e: /* NATIONAL DIGIT SHAPES */
case 0x206f: /* NOMINAL DIGIT SHAPES */
case 0xfeff: /* ZERO WIDTH NO-BREAK SPACE */
continue;
}
/* fold into lowercase -- this will only fold characters in
* the ASCII range, which is perfectly fine, because the
* git folder name can only be composed of ascii characters
*/
return git__tolower((int)codepoint);
}
return 0; /* NULL byte -- end of string */
}
static bool verify_dotgit_hfs_generic(const char *path, size_t len, const char *needle, size_t needle_len)
{
size_t i;
char c;
if (next_hfs_char(&path, &len) != '.')
return true;
for (i = 0; i < needle_len; i++) {
c = next_hfs_char(&path, &len);
if (c != needle[i])
return true;
}
if (next_hfs_char(&path, &len) != '\0')
return true;
return false;
}
static bool verify_dotgit_hfs(const char *path, size_t len)
{
return verify_dotgit_hfs_generic(path, len, "git", CONST_STRLEN("git"));
}
GIT_INLINE(bool) verify_dotgit_ntfs(git_repository *repo, const char *path, size_t len)
{
git_buf *reserved = git_repository__reserved_names_win32;
size_t reserved_len = git_repository__reserved_names_win32_len;
size_t start = 0, i;
if (repo)
git_repository__reserved_names(&reserved, &reserved_len, repo, true);
for (i = 0; i < reserved_len; i++) {
git_buf *r = &reserved[i];
if (len >= r->size &&
strncasecmp(path, r->ptr, r->size) == 0) {
start = r->size;
break;
}
}
if (!start)
return true;
/*
* Reject paths that start with Windows-style directory separators
* (".git\") or NTFS alternate streams (".git:") and could be used
* to write to the ".git" directory on Windows platforms.
*/
if (path[start] == '\\' || path[start] == ':')
return false;
/* Reject paths like '.git ' or '.git.' */
for (i = start; i < len; i++) {
if (path[i] != ' ' && path[i] != '.')
return true;
}
return false;
}
/*
* Windows paths that end with spaces and/or dots are elided to the
* path without them for backward compatibility. That is to say
* that opening file "foo ", "foo." or even "foo . . ." will all
* map to a filename of "foo". This function identifies spaces and
* dots at the end of a filename, whether the proper end of the
* filename (end of string) or a colon (which would indicate a
* Windows alternate data stream.)
*/
GIT_INLINE(bool) ntfs_end_of_filename(const char *path)
{
const char *c = path;
for (;; c++) {
if (*c == '\0' || *c == ':')
return true;
if (*c != ' ' && *c != '.')
return false;
}
return true;
}
GIT_INLINE(bool) verify_dotgit_ntfs_generic(const char *name, size_t len, const char *dotgit_name, size_t dotgit_len, const char *shortname_pfix)
{
int i, saw_tilde;
if (name[0] == '.' && len >= dotgit_len &&
!strncasecmp(name + 1, dotgit_name, dotgit_len)) {
return !ntfs_end_of_filename(name + dotgit_len + 1);
}
/* Detect the basic NTFS shortname with the first six chars */
if (!strncasecmp(name, dotgit_name, 6) && name[6] == '~' &&
name[7] >= '1' && name[7] <= '4')
return !ntfs_end_of_filename(name + 8);
/* Catch fallback names */
for (i = 0, saw_tilde = 0; i < 8; i++) {
if (name[i] == '\0') {
return true;
} else if (saw_tilde) {
if (name[i] < '0' || name[i] > '9')
return true;
} else if (name[i] == '~') {
if (name[i+1] < '1' || name[i+1] > '9')
return true;
saw_tilde = 1;
} else if (i >= 6) {
return true;
} else if ((unsigned char)name[i] > 127) {
return true;
} else if (git__tolower(name[i]) != shortname_pfix[i]) {
return true;
}
}
return !ntfs_end_of_filename(name + i);
}
GIT_INLINE(bool) verify_char(unsigned char c, unsigned int flags)
{
if ((flags & GIT_PATH_REJECT_BACKSLASH) && c == '\\')
return false;
if ((flags & GIT_PATH_REJECT_SLASH) && c == '/')
return false;
if (flags & GIT_PATH_REJECT_NT_CHARS) {
if (c < 32)
return false;
switch (c) {
case '<':
case '>':
case ':':
case '"':
case '|':
case '?':
case '*':
return false;
}
}
return true;
}
/*
* Return the length of the common prefix between str and prefix, comparing them
* case-insensitively (must be ASCII to match).
*/
GIT_INLINE(size_t) common_prefix_icase(const char *str, size_t len, const char *prefix)
{
size_t count = 0;
while (len >0 && tolower(*str) == tolower(*prefix)) {
count++;
str++;
prefix++;
len--;
}
return count;
}
/*
* We fundamentally don't like some paths when dealing with user-inputted
* strings (in checkout or ref names): we don't want dot or dot-dot
* anywhere, we want to avoid writing weird paths on Windows that can't
* be handled by tools that use the non-\\?\ APIs, we don't want slashes
* or double slashes at the end of paths that can make them ambiguous.
*
* For checkout, we don't want to recurse into ".git" either.
*/
static bool verify_component(
git_repository *repo,
const char *component,
size_t len,
uint16_t mode,
unsigned int flags)
{
if (len == 0)
return false;
if ((flags & GIT_PATH_REJECT_TRAVERSAL) &&
len == 1 && component[0] == '.')
return false;
if ((flags & GIT_PATH_REJECT_TRAVERSAL) &&
len == 2 && component[0] == '.' && component[1] == '.')
return false;
if ((flags & GIT_PATH_REJECT_TRAILING_DOT) && component[len-1] == '.')
return false;
if ((flags & GIT_PATH_REJECT_TRAILING_SPACE) && component[len-1] == ' ')
return false;
if ((flags & GIT_PATH_REJECT_TRAILING_COLON) && component[len-1] == ':')
return false;
if (flags & GIT_PATH_REJECT_DOS_PATHS) {
if (!verify_dospath(component, len, "CON", false) ||
!verify_dospath(component, len, "PRN", false) ||
!verify_dospath(component, len, "AUX", false) ||
!verify_dospath(component, len, "NUL", false) ||
!verify_dospath(component, len, "COM", true) ||
!verify_dospath(component, len, "LPT", true))
return false;
}
if (flags & GIT_PATH_REJECT_DOT_GIT_HFS) {
if (!verify_dotgit_hfs(component, len))
return false;
if (S_ISLNK(mode) && git_path_is_gitfile(component, len, GIT_PATH_GITFILE_GITMODULES, GIT_PATH_FS_HFS))
return false;
}
if (flags & GIT_PATH_REJECT_DOT_GIT_NTFS) {
if (!verify_dotgit_ntfs(repo, component, len))
return false;
if (S_ISLNK(mode) && git_path_is_gitfile(component, len, GIT_PATH_GITFILE_GITMODULES, GIT_PATH_FS_NTFS))
return false;
}
/* don't bother rerunning the `.git` test if we ran the HFS or NTFS
* specific tests, they would have already rejected `.git`.
*/
if ((flags & GIT_PATH_REJECT_DOT_GIT_HFS) == 0 &&
(flags & GIT_PATH_REJECT_DOT_GIT_NTFS) == 0 &&
(flags & GIT_PATH_REJECT_DOT_GIT_LITERAL)) {
if (len >= 4 &&
component[0] == '.' &&
(component[1] == 'g' || component[1] == 'G') &&
(component[2] == 'i' || component[2] == 'I') &&
(component[3] == 't' || component[3] == 'T')) {
if (len == 4)
return false;
if (S_ISLNK(mode) && common_prefix_icase(component, len, ".gitmodules") == len)
return false;
}
}
return true;
}
GIT_INLINE(unsigned int) dotgit_flags(
git_repository *repo,
unsigned int flags)
{
int protectHFS = 0, protectNTFS = 1;
int error = 0;
flags |= GIT_PATH_REJECT_DOT_GIT_LITERAL;
#ifdef __APPLE__
protectHFS = 1;
#endif
if (repo && !protectHFS)
error = git_repository__configmap_lookup(&protectHFS, repo, GIT_CONFIGMAP_PROTECTHFS);
if (!error && protectHFS)
flags |= GIT_PATH_REJECT_DOT_GIT_HFS;
if (repo)
error = git_repository__configmap_lookup(&protectNTFS, repo, GIT_CONFIGMAP_PROTECTNTFS);
if (!error && protectNTFS)
flags |= GIT_PATH_REJECT_DOT_GIT_NTFS;
return flags;
}
bool git_path_validate(
git_repository *repo,
const char *path,
uint16_t mode,
unsigned int flags)
{
const char *start, *c;
/* Upgrade the ".git" checks based on platform */
if ((flags & GIT_PATH_REJECT_DOT_GIT))
flags = dotgit_flags(repo, flags);
for (start = c = path; *c; c++) {
if (!verify_char(*c, flags))
return false;
if (*c == '/') {
if (!verify_component(repo, start, (c - start), mode, flags))
return false;
start = c+1;
}
}
return verify_component(repo, start, (c - start), mode, flags);
}
#ifdef GIT_WIN32
GIT_INLINE(bool) should_validate_longpaths(git_repository *repo)
{
int longpaths = 0;
if (repo &&
git_repository__configmap_lookup(&longpaths, repo, GIT_CONFIGMAP_LONGPATHS) < 0)
longpaths = 0;
return (longpaths == 0);
}
#else
GIT_INLINE(bool) should_validate_longpaths(git_repository *repo)
{
GIT_UNUSED(repo);
return false;
}
#endif
int git_path_validate_workdir(git_repository *repo, const char *path)
{
if (should_validate_longpaths(repo))
return git_path_validate_filesystem(path, strlen(path));
return 0;
}
int git_path_validate_workdir_with_len(
git_repository *repo,
const char *path,
size_t path_len)
{
if (should_validate_longpaths(repo))
return git_path_validate_filesystem(path, path_len);
return 0;
}
int git_path_validate_workdir_buf(git_repository *repo, git_buf *path)
{
return git_path_validate_workdir_with_len(repo, path->ptr, path->size);
}
int git_path_normalize_slashes(git_buf *out, const char *path)
{
int error;
char *p;
if ((error = git_buf_puts(out, path)) < 0)
return error;
for (p = out->ptr; *p; p++) {
if (*p == '\\')
*p = '/';
}
return 0;
}
static const struct {
const char *file;
const char *hash;
size_t filelen;
} gitfiles[] = {
{ "gitignore", "gi250a", CONST_STRLEN("gitignore") },
{ "gitmodules", "gi7eba", CONST_STRLEN("gitmodules") },
{ "gitattributes", "gi7d29", CONST_STRLEN("gitattributes") }
};
extern int git_path_is_gitfile(const char *path, size_t pathlen, git_path_gitfile gitfile, git_path_fs fs)
{
const char *file, *hash;
size_t filelen;
if (!(gitfile >= GIT_PATH_GITFILE_GITIGNORE && gitfile < ARRAY_SIZE(gitfiles))) {
git_error_set(GIT_ERROR_OS, "invalid gitfile for path validation");
return -1;
}
file = gitfiles[gitfile].file;
filelen = gitfiles[gitfile].filelen;
hash = gitfiles[gitfile].hash;
switch (fs) {
case GIT_PATH_FS_GENERIC:
return !verify_dotgit_ntfs_generic(path, pathlen, file, filelen, hash) ||
!verify_dotgit_hfs_generic(path, pathlen, file, filelen);
case GIT_PATH_FS_NTFS:
return !verify_dotgit_ntfs_generic(path, pathlen, file, filelen, hash);
case GIT_PATH_FS_HFS:
return !verify_dotgit_hfs_generic(path, pathlen, file, filelen);
default:
git_error_set(GIT_ERROR_OS, "invalid filesystem for path validation");
return -1;
}
}
bool git_path_supports_symlinks(const char *dir)
{
git_buf path = GIT_BUF_INIT;
bool supported = false;
struct stat st;
int fd;
if ((fd = git_futils_mktmp(&path, dir, 0666)) < 0 ||
p_close(fd) < 0 ||
p_unlink(path.ptr) < 0 ||
p_symlink("testing", path.ptr) < 0 ||
p_lstat(path.ptr, &st) < 0)
goto done;
supported = (S_ISLNK(st.st_mode) != 0);
done:
if (path.size)
(void)p_unlink(path.ptr);
git_buf_dispose(&path);
return supported;
}
int git_path_validate_system_file_ownership(const char *path)
{
#ifndef GIT_WIN32
GIT_UNUSED(path);
return GIT_OK;
#else
git_win32_path buf;
PSID owner_sid;
PSECURITY_DESCRIPTOR descriptor = NULL;
HANDLE token;
TOKEN_USER *info = NULL;
DWORD err, len;
int ret;
if (git_win32_path_from_utf8(buf, path) < 0)
return -1;
err = GetNamedSecurityInfoW(buf, SE_FILE_OBJECT,
OWNER_SECURITY_INFORMATION |
DACL_SECURITY_INFORMATION,
&owner_sid, NULL, NULL, NULL, &descriptor);
if (err == ERROR_FILE_NOT_FOUND || err == ERROR_PATH_NOT_FOUND) {
ret = GIT_ENOTFOUND;
goto cleanup;
}
if (err != ERROR_SUCCESS) {
git_error_set(GIT_ERROR_OS, "failed to get security information");
ret = GIT_ERROR;
goto cleanup;
}
if (!IsValidSid(owner_sid)) {
git_error_set(GIT_ERROR_INVALID, "programdata configuration file owner is unknown");
ret = GIT_ERROR;
goto cleanup;
}
if (IsWellKnownSid(owner_sid, WinBuiltinAdministratorsSid) ||
IsWellKnownSid(owner_sid, WinLocalSystemSid)) {
ret = GIT_OK;
goto cleanup;
}
/* Obtain current user's SID */
if (OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &token) &&
!GetTokenInformation(token, TokenUser, NULL, 0, &len)) {
info = git__malloc(len);
GIT_ERROR_CHECK_ALLOC(info);
if (!GetTokenInformation(token, TokenUser, info, len, &len)) {
git__free(info);
info = NULL;
}
}
/*
* If the file is owned by the same account that is running the current
* process, it's okay to read from that file.
*/
if (info && EqualSid(owner_sid, info->User.Sid))
ret = GIT_OK;
else {
git_error_set(GIT_ERROR_INVALID, "programdata configuration file owner is not valid");
ret = GIT_ERROR;
}
git__free(info);
cleanup:
if (descriptor)
LocalFree(descriptor);
return ret;
#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/netops.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_netops_h__
#define INCLUDE_netops_h__
#include "common.h"
#include "posix.h"
#include "stream.h"
#include "net.h"
#ifdef GIT_OPENSSL
# include "streams/openssl.h"
#endif
typedef struct gitno_ssl {
#ifdef GIT_OPENSSL
SSL *ssl;
#else
size_t dummy;
#endif
} gitno_ssl;
/* Represents a socket that may or may not be using SSL */
typedef struct gitno_socket {
GIT_SOCKET socket;
gitno_ssl ssl;
} gitno_socket;
typedef struct gitno_buffer {
char *data;
size_t len;
size_t offset;
int (*recv)(struct gitno_buffer *buffer);
void *cb_data;
} gitno_buffer;
/* Flags to gitno_connect */
enum {
/* Attempt to create an SSL connection. */
GITNO_CONNECT_SSL = 1,
};
/**
* Check if the name in a cert matches the wanted hostname
*
* Check if a pattern from a certificate matches the hostname we
* wanted to connect to according to RFC2818 rules (which specifies
* HTTP over TLS). Mainly, an asterisk matches anything, but is
* limited to a single url component.
*
* Note that this does not set an error message. It expects the user
* to provide the message for the user.
*/
int gitno__match_host(const char *pattern, const char *host);
void gitno_buffer_setup_fromstream(git_stream *st, gitno_buffer *buf, char *data, size_t len);
void gitno_buffer_setup_callback(gitno_buffer *buf, char *data, size_t len, int (*recv)(gitno_buffer *buf), void *cb_data);
int gitno_recv(gitno_buffer *buf);
int gitno_consume(gitno_buffer *buf, const char *ptr);
void gitno_consume_n(gitno_buffer *buf, size_t cons);
#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/pqueue.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_pqueue_h__
#define INCLUDE_pqueue_h__
#include "common.h"
#include "vector.h"
typedef git_vector git_pqueue;
enum {
/* flag meaning: don't grow heap, keep highest values only */
GIT_PQUEUE_FIXED_SIZE = (GIT_VECTOR_FLAG_MAX << 1),
};
/**
* Initialize priority queue
*
* @param pq The priority queue struct to initialize
* @param flags Flags (see above) to control queue behavior
* @param init_size The initial queue size
* @param cmp The entry priority comparison function
* @return 0 on success, <0 on error
*/
extern int git_pqueue_init(
git_pqueue *pq,
uint32_t flags,
size_t init_size,
git_vector_cmp cmp);
#define git_pqueue_free git_vector_free
#define git_pqueue_clear git_vector_clear
#define git_pqueue_size git_vector_length
#define git_pqueue_get git_vector_get
#define git_pqueue_reverse git_vector_reverse
/**
* Insert a new item into the queue
*
* @param pq The priority queue
* @param item Pointer to the item data
* @return 0 on success, <0 on failure
*/
extern int git_pqueue_insert(git_pqueue *pq, void *item);
/**
* Remove the top item in the priority queue
*
* @param pq The priority queue
* @return item from heap on success, NULL if queue is empty
*/
extern void *git_pqueue_pop(git_pqueue *pq);
#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_snapshot.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_backend.h"
#include "config.h"
#include "config_entries.h"
typedef struct {
git_config_backend parent;
git_mutex values_mutex;
git_config_entries *entries;
git_config_backend *source;
} config_snapshot_backend;
static int config_error_readonly(void)
{
git_error_set(GIT_ERROR_CONFIG, "this backend is read-only");
return -1;
}
static int config_snapshot_iterator(
git_config_iterator **iter,
struct git_config_backend *backend)
{
config_snapshot_backend *b = GIT_CONTAINER_OF(backend, config_snapshot_backend, parent);
git_config_entries *entries = NULL;
int error;
if ((error = git_config_entries_dup(&entries, b->entries)) < 0 ||
(error = git_config_entries_iterator_new(iter, entries)) < 0)
goto out;
out:
/* Let iterator delete duplicated entries when it's done */
git_config_entries_free(entries);
return error;
}
/* release the map containing the entry as an equivalent to freeing it */
static void config_snapshot_entry_free(git_config_entry *entry)
{
git_config_entries *entries = (git_config_entries *) entry->payload;
git_config_entries_free(entries);
}
static int config_snapshot_get(git_config_backend *cfg, const char *key, git_config_entry **out)
{
config_snapshot_backend *b = GIT_CONTAINER_OF(cfg, config_snapshot_backend, parent);
git_config_entries *entries = NULL;
git_config_entry *entry;
int error = 0;
if (git_mutex_lock(&b->values_mutex) < 0) {
git_error_set(GIT_ERROR_OS, "failed to lock config backend");
return -1;
}
entries = b->entries;
git_config_entries_incref(entries);
git_mutex_unlock(&b->values_mutex);
if ((error = (git_config_entries_get(&entry, entries, key))) < 0) {
git_config_entries_free(entries);
return error;
}
entry->free = config_snapshot_entry_free;
entry->payload = entries;
*out = entry;
return 0;
}
static int config_snapshot_set(git_config_backend *cfg, const char *name, const char *value)
{
GIT_UNUSED(cfg);
GIT_UNUSED(name);
GIT_UNUSED(value);
return config_error_readonly();
}
static int config_snapshot_set_multivar(
git_config_backend *cfg, const char *name, const char *regexp, const char *value)
{
GIT_UNUSED(cfg);
GIT_UNUSED(name);
GIT_UNUSED(regexp);
GIT_UNUSED(value);
return config_error_readonly();
}
static int config_snapshot_delete_multivar(git_config_backend *cfg, const char *name, const char *regexp)
{
GIT_UNUSED(cfg);
GIT_UNUSED(name);
GIT_UNUSED(regexp);
return config_error_readonly();
}
static int config_snapshot_delete(git_config_backend *cfg, const char *name)
{
GIT_UNUSED(cfg);
GIT_UNUSED(name);
return config_error_readonly();
}
static int config_snapshot_lock(git_config_backend *_cfg)
{
GIT_UNUSED(_cfg);
return config_error_readonly();
}
static int config_snapshot_unlock(git_config_backend *_cfg, int success)
{
GIT_UNUSED(_cfg);
GIT_UNUSED(success);
return config_error_readonly();
}
static void config_snapshot_free(git_config_backend *_backend)
{
config_snapshot_backend *backend = GIT_CONTAINER_OF(_backend, config_snapshot_backend, parent);
if (backend == NULL)
return;
git_config_entries_free(backend->entries);
git_mutex_free(&backend->values_mutex);
git__free(backend);
}
static int config_snapshot_open(git_config_backend *cfg, git_config_level_t level, const git_repository *repo)
{
config_snapshot_backend *b = GIT_CONTAINER_OF(cfg, config_snapshot_backend, parent);
git_config_entries *entries = NULL;
git_config_iterator *it = NULL;
git_config_entry *entry;
int error;
/* We're just copying data, don't care about the level or repo*/
GIT_UNUSED(level);
GIT_UNUSED(repo);
if ((error = git_config_entries_new(&entries)) < 0 ||
(error = b->source->iterator(&it, b->source)) < 0)
goto out;
while ((error = git_config_next(&entry, it)) == 0)
if ((error = git_config_entries_dup_entry(entries, entry)) < 0)
goto out;
if (error < 0) {
if (error != GIT_ITEROVER)
goto out;
error = 0;
}
b->entries = entries;
out:
git_config_iterator_free(it);
if (error)
git_config_entries_free(entries);
return error;
}
int git_config_backend_snapshot(git_config_backend **out, git_config_backend *source)
{
config_snapshot_backend *backend;
backend = git__calloc(1, sizeof(config_snapshot_backend));
GIT_ERROR_CHECK_ALLOC(backend);
backend->parent.version = GIT_CONFIG_BACKEND_VERSION;
git_mutex_init(&backend->values_mutex);
backend->source = source;
backend->parent.readonly = 1;
backend->parent.version = GIT_CONFIG_BACKEND_VERSION;
backend->parent.open = config_snapshot_open;
backend->parent.get = config_snapshot_get;
backend->parent.set = config_snapshot_set;
backend->parent.set_multivar = config_snapshot_set_multivar;
backend->parent.snapshot = git_config_backend_snapshot;
backend->parent.del = config_snapshot_delete;
backend->parent.del_multivar = config_snapshot_delete_multivar;
backend->parent.iterator = config_snapshot_iterator;
backend->parent.lock = config_snapshot_lock;
backend->parent.unlock = config_snapshot_unlock;
backend->parent.free = config_snapshot_free;
*out = &backend->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/filebuf.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 "filebuf.h"
#include "futils.h"
static const size_t WRITE_BUFFER_SIZE = (4096 * 2);
enum buferr_t {
BUFERR_OK = 0,
BUFERR_WRITE,
BUFERR_ZLIB,
BUFERR_MEM
};
#define ENSURE_BUF_OK(buf) if ((buf)->last_error != BUFERR_OK) { return -1; }
static int verify_last_error(git_filebuf *file)
{
switch (file->last_error) {
case BUFERR_WRITE:
git_error_set(GIT_ERROR_OS, "failed to write out file");
return -1;
case BUFERR_MEM:
git_error_set_oom();
return -1;
case BUFERR_ZLIB:
git_error_set(GIT_ERROR_ZLIB,
"Buffer error when writing out ZLib data");
return -1;
default:
return 0;
}
}
static int lock_file(git_filebuf *file, int flags, mode_t mode)
{
if (git_path_exists(file->path_lock) == true) {
git_error_clear(); /* actual OS error code just confuses */
git_error_set(GIT_ERROR_OS,
"failed to lock file '%s' for writing", file->path_lock);
return GIT_ELOCKED;
}
/* create path to the file buffer is required */
if (flags & GIT_FILEBUF_CREATE_LEADING_DIRS) {
/* XXX: Should dirmode here be configurable? Or is 0777 always fine? */
file->fd = git_futils_creat_locked_withpath(file->path_lock, 0777, mode);
} else {
file->fd = git_futils_creat_locked(file->path_lock, mode);
}
if (file->fd < 0)
return file->fd;
file->fd_is_open = true;
if ((flags & GIT_FILEBUF_APPEND) && git_path_exists(file->path_original) == true) {
git_file source;
char buffer[FILEIO_BUFSIZE];
ssize_t read_bytes;
int error = 0;
source = p_open(file->path_original, O_RDONLY);
if (source < 0) {
git_error_set(GIT_ERROR_OS,
"failed to open file '%s' for reading",
file->path_original);
return -1;
}
while ((read_bytes = p_read(source, buffer, sizeof(buffer))) > 0) {
if ((error = p_write(file->fd, buffer, read_bytes)) < 0)
break;
if (file->compute_digest)
git_hash_update(&file->digest, buffer, read_bytes);
}
p_close(source);
if (read_bytes < 0) {
git_error_set(GIT_ERROR_OS, "failed to read file '%s'", file->path_original);
return -1;
} else if (error < 0) {
git_error_set(GIT_ERROR_OS, "failed to write file '%s'", file->path_lock);
return -1;
}
}
return 0;
}
void git_filebuf_cleanup(git_filebuf *file)
{
if (file->fd_is_open && file->fd >= 0)
p_close(file->fd);
if (file->created_lock && !file->did_rename && file->path_lock && git_path_exists(file->path_lock))
p_unlink(file->path_lock);
if (file->compute_digest) {
git_hash_ctx_cleanup(&file->digest);
file->compute_digest = 0;
}
if (file->buffer)
git__free(file->buffer);
/* use the presence of z_buf to decide if we need to deflateEnd */
if (file->z_buf) {
git__free(file->z_buf);
deflateEnd(&file->zs);
}
if (file->path_original)
git__free(file->path_original);
if (file->path_lock)
git__free(file->path_lock);
memset(file, 0x0, sizeof(git_filebuf));
file->fd = -1;
}
GIT_INLINE(int) flush_buffer(git_filebuf *file)
{
int result = file->write(file, file->buffer, file->buf_pos);
file->buf_pos = 0;
return result;
}
int git_filebuf_flush(git_filebuf *file)
{
return flush_buffer(file);
}
static int write_normal(git_filebuf *file, void *source, size_t len)
{
if (len > 0) {
if (p_write(file->fd, (void *)source, len) < 0) {
file->last_error = BUFERR_WRITE;
return -1;
}
if (file->compute_digest)
git_hash_update(&file->digest, source, len);
}
return 0;
}
static int write_deflate(git_filebuf *file, void *source, size_t len)
{
z_stream *zs = &file->zs;
if (len > 0 || file->flush_mode == Z_FINISH) {
zs->next_in = source;
zs->avail_in = (uInt)len;
do {
size_t have;
zs->next_out = file->z_buf;
zs->avail_out = (uInt)file->buf_size;
if (deflate(zs, file->flush_mode) == Z_STREAM_ERROR) {
file->last_error = BUFERR_ZLIB;
return -1;
}
have = file->buf_size - (size_t)zs->avail_out;
if (p_write(file->fd, file->z_buf, have) < 0) {
file->last_error = BUFERR_WRITE;
return -1;
}
} while (zs->avail_out == 0);
GIT_ASSERT(zs->avail_in == 0);
if (file->compute_digest)
git_hash_update(&file->digest, source, len);
}
return 0;
}
#define MAX_SYMLINK_DEPTH 5
static int resolve_symlink(git_buf *out, const char *path)
{
int i, error, root;
ssize_t ret;
struct stat st;
git_buf curpath = GIT_BUF_INIT, target = GIT_BUF_INIT;
if ((error = git_buf_grow(&target, GIT_PATH_MAX + 1)) < 0 ||
(error = git_buf_puts(&curpath, path)) < 0)
return error;
for (i = 0; i < MAX_SYMLINK_DEPTH; i++) {
error = p_lstat(curpath.ptr, &st);
if (error < 0 && errno == ENOENT) {
error = git_buf_puts(out, curpath.ptr);
goto cleanup;
}
if (error < 0) {
git_error_set(GIT_ERROR_OS, "failed to stat '%s'", curpath.ptr);
error = -1;
goto cleanup;
}
if (!S_ISLNK(st.st_mode)) {
error = git_buf_puts(out, curpath.ptr);
goto cleanup;
}
ret = p_readlink(curpath.ptr, target.ptr, GIT_PATH_MAX);
if (ret < 0) {
git_error_set(GIT_ERROR_OS, "failed to read symlink '%s'", curpath.ptr);
error = -1;
goto cleanup;
}
if (ret == GIT_PATH_MAX) {
git_error_set(GIT_ERROR_INVALID, "symlink target too long");
error = -1;
goto cleanup;
}
/* readlink(2) won't NUL-terminate for us */
target.ptr[ret] = '\0';
target.size = ret;
root = git_path_root(target.ptr);
if (root >= 0) {
if ((error = git_buf_sets(&curpath, target.ptr)) < 0)
goto cleanup;
} else {
git_buf dir = GIT_BUF_INIT;
if ((error = git_path_dirname_r(&dir, curpath.ptr)) < 0)
goto cleanup;
git_buf_swap(&curpath, &dir);
git_buf_dispose(&dir);
if ((error = git_path_apply_relative(&curpath, target.ptr)) < 0)
goto cleanup;
}
}
git_error_set(GIT_ERROR_INVALID, "maximum symlink depth reached");
error = -1;
cleanup:
git_buf_dispose(&curpath);
git_buf_dispose(&target);
return error;
}
int git_filebuf_open(git_filebuf *file, const char *path, int flags, mode_t mode)
{
return git_filebuf_open_withsize(file, path, flags, mode, WRITE_BUFFER_SIZE);
}
int git_filebuf_open_withsize(git_filebuf *file, const char *path, int flags, mode_t mode, size_t size)
{
int compression, error = -1;
size_t path_len, alloc_len;
GIT_ASSERT_ARG(file);
GIT_ASSERT_ARG(path);
GIT_ASSERT(file->buffer == NULL);
memset(file, 0x0, sizeof(git_filebuf));
if (flags & GIT_FILEBUF_DO_NOT_BUFFER)
file->do_not_buffer = true;
if (flags & GIT_FILEBUF_FSYNC)
file->do_fsync = true;
file->buf_size = size;
file->buf_pos = 0;
file->fd = -1;
file->last_error = BUFERR_OK;
/* Allocate the main cache buffer */
if (!file->do_not_buffer) {
file->buffer = git__malloc(file->buf_size);
GIT_ERROR_CHECK_ALLOC(file->buffer);
}
/* If we are hashing on-write, allocate a new hash context */
if (flags & GIT_FILEBUF_HASH_CONTENTS) {
file->compute_digest = 1;
if (git_hash_ctx_init(&file->digest) < 0)
goto cleanup;
}
compression = flags >> GIT_FILEBUF_DEFLATE_SHIFT;
/* If we are deflating on-write, */
if (compression != 0) {
/* Initialize the ZLib stream */
if (deflateInit(&file->zs, compression) != Z_OK) {
git_error_set(GIT_ERROR_ZLIB, "failed to initialize zlib");
goto cleanup;
}
/* Allocate the Zlib cache buffer */
file->z_buf = git__malloc(file->buf_size);
GIT_ERROR_CHECK_ALLOC(file->z_buf);
/* Never flush */
file->flush_mode = Z_NO_FLUSH;
file->write = &write_deflate;
} else {
file->write = &write_normal;
}
/* If we are writing to a temp file */
if (flags & GIT_FILEBUF_TEMPORARY) {
git_buf tmp_path = GIT_BUF_INIT;
/* Open the file as temporary for locking */
file->fd = git_futils_mktmp(&tmp_path, path, mode);
if (file->fd < 0) {
git_buf_dispose(&tmp_path);
goto cleanup;
}
file->fd_is_open = true;
file->created_lock = true;
/* No original path */
file->path_original = NULL;
file->path_lock = git_buf_detach(&tmp_path);
GIT_ERROR_CHECK_ALLOC(file->path_lock);
} else {
git_buf resolved_path = GIT_BUF_INIT;
if ((error = resolve_symlink(&resolved_path, path)) < 0)
goto cleanup;
/* Save the original path of the file */
path_len = resolved_path.size;
file->path_original = git_buf_detach(&resolved_path);
/* create the locking path by appending ".lock" to the original */
GIT_ERROR_CHECK_ALLOC_ADD(&alloc_len, path_len, GIT_FILELOCK_EXTLENGTH);
file->path_lock = git__malloc(alloc_len);
GIT_ERROR_CHECK_ALLOC(file->path_lock);
memcpy(file->path_lock, file->path_original, path_len);
memcpy(file->path_lock + path_len, GIT_FILELOCK_EXTENSION, GIT_FILELOCK_EXTLENGTH);
if (git_path_isdir(file->path_original)) {
git_error_set(GIT_ERROR_FILESYSTEM, "path '%s' is a directory", file->path_original);
error = GIT_EDIRECTORY;
goto cleanup;
}
/* open the file for locking */
if ((error = lock_file(file, flags, mode)) < 0)
goto cleanup;
file->created_lock = true;
}
return 0;
cleanup:
git_filebuf_cleanup(file);
return error;
}
int git_filebuf_hash(git_oid *oid, git_filebuf *file)
{
GIT_ASSERT_ARG(oid);
GIT_ASSERT_ARG(file);
GIT_ASSERT_ARG(file->compute_digest);
flush_buffer(file);
if (verify_last_error(file) < 0)
return -1;
git_hash_final(oid, &file->digest);
git_hash_ctx_cleanup(&file->digest);
file->compute_digest = 0;
return 0;
}
int git_filebuf_commit_at(git_filebuf *file, const char *path)
{
git__free(file->path_original);
file->path_original = git__strdup(path);
GIT_ERROR_CHECK_ALLOC(file->path_original);
return git_filebuf_commit(file);
}
int git_filebuf_commit(git_filebuf *file)
{
/* temporary files cannot be committed */
GIT_ASSERT_ARG(file);
GIT_ASSERT(file->path_original);
file->flush_mode = Z_FINISH;
flush_buffer(file);
if (verify_last_error(file) < 0)
goto on_error;
file->fd_is_open = false;
if (file->do_fsync && p_fsync(file->fd) < 0) {
git_error_set(GIT_ERROR_OS, "failed to fsync '%s'", file->path_lock);
goto on_error;
}
if (p_close(file->fd) < 0) {
git_error_set(GIT_ERROR_OS, "failed to close file at '%s'", file->path_lock);
goto on_error;
}
file->fd = -1;
if (p_rename(file->path_lock, file->path_original) < 0) {
git_error_set(GIT_ERROR_OS, "failed to rename lockfile to '%s'", file->path_original);
goto on_error;
}
if (file->do_fsync && git_futils_fsync_parent(file->path_original) < 0)
goto on_error;
file->did_rename = true;
git_filebuf_cleanup(file);
return 0;
on_error:
git_filebuf_cleanup(file);
return -1;
}
GIT_INLINE(void) add_to_cache(git_filebuf *file, const void *buf, size_t len)
{
memcpy(file->buffer + file->buf_pos, buf, len);
file->buf_pos += len;
}
int git_filebuf_write(git_filebuf *file, const void *buff, size_t len)
{
const unsigned char *buf = buff;
ENSURE_BUF_OK(file);
if (file->do_not_buffer)
return file->write(file, (void *)buff, len);
for (;;) {
size_t space_left = file->buf_size - file->buf_pos;
/* cache if it's small */
if (space_left > len) {
add_to_cache(file, buf, len);
return 0;
}
add_to_cache(file, buf, space_left);
if (flush_buffer(file) < 0)
return -1;
len -= space_left;
buf += space_left;
}
}
int git_filebuf_reserve(git_filebuf *file, void **buffer, size_t len)
{
size_t space_left = file->buf_size - file->buf_pos;
*buffer = NULL;
ENSURE_BUF_OK(file);
if (len > file->buf_size) {
file->last_error = BUFERR_MEM;
return -1;
}
if (space_left <= len) {
if (flush_buffer(file) < 0)
return -1;
}
*buffer = (file->buffer + file->buf_pos);
file->buf_pos += len;
return 0;
}
int git_filebuf_printf(git_filebuf *file, const char *format, ...)
{
va_list arglist;
size_t space_left, len, alloclen;
int written, res;
char *tmp_buffer;
ENSURE_BUF_OK(file);
space_left = file->buf_size - file->buf_pos;
do {
va_start(arglist, format);
written = p_vsnprintf((char *)file->buffer + file->buf_pos, space_left, format, arglist);
va_end(arglist);
if (written < 0) {
file->last_error = BUFERR_MEM;
return -1;
}
len = written;
if (len + 1 <= space_left) {
file->buf_pos += len;
return 0;
}
if (flush_buffer(file) < 0)
return -1;
space_left = file->buf_size - file->buf_pos;
} while (len + 1 <= space_left);
if (GIT_ADD_SIZET_OVERFLOW(&alloclen, len, 1) ||
!(tmp_buffer = git__malloc(alloclen))) {
file->last_error = BUFERR_MEM;
return -1;
}
va_start(arglist, format);
written = p_vsnprintf(tmp_buffer, len + 1, format, arglist);
va_end(arglist);
if (written < 0) {
git__free(tmp_buffer);
file->last_error = BUFERR_MEM;
return -1;
}
res = git_filebuf_write(file, tmp_buffer, len);
git__free(tmp_buffer);
return res;
}
int git_filebuf_stats(time_t *mtime, size_t *size, git_filebuf *file)
{
int res;
struct stat st;
if (file->fd_is_open)
res = p_fstat(file->fd, &st);
else
res = p_stat(file->path_original, &st);
if (res < 0) {
git_error_set(GIT_ERROR_OS, "could not get stat info for '%s'",
file->path_original);
return res;
}
if (mtime)
*mtime = st.st_mtime;
if (size)
*size = (size_t)st.st_size;
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/filebuf.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_filebuf_h__
#define INCLUDE_filebuf_h__
#include "common.h"
#include "futils.h"
#include "hash.h"
#include <zlib.h>
#ifdef GIT_THREADS
# define GIT_FILEBUF_THREADS
#endif
#define GIT_FILEBUF_HASH_CONTENTS (1 << 0)
#define GIT_FILEBUF_APPEND (1 << 2)
#define GIT_FILEBUF_CREATE_LEADING_DIRS (1 << 3)
#define GIT_FILEBUF_TEMPORARY (1 << 4)
#define GIT_FILEBUF_DO_NOT_BUFFER (1 << 5)
#define GIT_FILEBUF_FSYNC (1 << 6)
#define GIT_FILEBUF_DEFLATE_SHIFT (7)
#define GIT_FILELOCK_EXTENSION ".lock\0"
#define GIT_FILELOCK_EXTLENGTH 6
typedef struct git_filebuf git_filebuf;
struct git_filebuf {
char *path_original;
char *path_lock;
int (*write)(git_filebuf *file, void *source, size_t len);
bool compute_digest;
git_hash_ctx digest;
unsigned char *buffer;
unsigned char *z_buf;
z_stream zs;
int flush_mode;
size_t buf_size, buf_pos;
git_file fd;
bool fd_is_open;
bool created_lock;
bool did_rename;
bool do_not_buffer;
bool do_fsync;
int last_error;
};
#define GIT_FILEBUF_INIT {0}
/*
* The git_filebuf object lifecycle is:
* - Allocate git_filebuf, preferably using GIT_FILEBUF_INIT.
*
* - Call git_filebuf_open() to initialize the filebuf for use.
*
* - Make as many calls to git_filebuf_write(), git_filebuf_printf(),
* git_filebuf_reserve() as you like. The error codes for these
* functions don't need to be checked. They are stored internally
* by the file buffer.
*
* - While you are writing, you may call git_filebuf_hash() to get
* the hash of all you have written so far. This function will
* fail if any of the previous writes to the buffer failed.
*
* - To close the git_filebuf, you may call git_filebuf_commit() or
* git_filebuf_commit_at() to save the file, or
* git_filebuf_cleanup() to abandon the file. All of these will
* free the git_filebuf object. Likewise, all of these will fail
* if any of the previous writes to the buffer failed, and set
* an error code accordingly.
*/
int git_filebuf_write(git_filebuf *lock, const void *buff, size_t len);
int git_filebuf_reserve(git_filebuf *file, void **buff, size_t len);
int git_filebuf_printf(git_filebuf *file, const char *format, ...) GIT_FORMAT_PRINTF(2, 3);
int git_filebuf_open(git_filebuf *lock, const char *path, int flags, mode_t mode);
int git_filebuf_open_withsize(git_filebuf *file, const char *path, int flags, mode_t mode, size_t size);
int git_filebuf_commit(git_filebuf *lock);
int git_filebuf_commit_at(git_filebuf *lock, const char *path);
void git_filebuf_cleanup(git_filebuf *lock);
int git_filebuf_hash(git_oid *oid, git_filebuf *file);
int git_filebuf_flush(git_filebuf *file);
int git_filebuf_stats(time_t *mtime, size_t *size, git_filebuf *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/odb.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_odb_h__
#define INCLUDE_odb_h__
#include "common.h"
#include "git2/odb.h"
#include "git2/oid.h"
#include "git2/types.h"
#include "git2/sys/commit_graph.h"
#include "cache.h"
#include "commit_graph.h"
#include "filter.h"
#include "posix.h"
#include "vector.h"
#define GIT_OBJECTS_DIR "objects/"
#define GIT_OBJECT_DIR_MODE 0777
#define GIT_OBJECT_FILE_MODE 0444
#define GIT_ODB_DEFAULT_LOOSE_PRIORITY 1
#define GIT_ODB_DEFAULT_PACKED_PRIORITY 2
extern bool git_odb__strict_hash_verification;
/* DO NOT EXPORT */
typedef struct {
void *data; /**< Raw, decompressed object data. */
size_t len; /**< Total number of bytes in data. */
git_object_t type; /**< Type of this object. */
} git_rawobj;
/* EXPORT */
struct git_odb_object {
git_cached_obj cached;
void *buffer;
};
/* EXPORT */
struct git_odb {
git_refcount rc;
git_mutex lock; /* protects backends */
git_vector backends;
git_cache own_cache;
git_commit_graph *cgraph;
unsigned int do_fsync :1;
};
typedef enum {
GIT_ODB_CAP_FROM_OWNER = -1,
} git_odb_cap_t;
/*
* Set the capabilities for the object database.
*/
int git_odb__set_caps(git_odb *odb, int caps);
/*
* Add the default loose and packed backends for a database.
*/
int git_odb__add_default_backends(
git_odb *db, const char *objects_dir,
bool as_alternates, int alternate_depth);
/*
* Hash a git_rawobj internally.
* The `git_rawobj` is supposed to be previously initialized
*/
int git_odb__hashobj(git_oid *id, git_rawobj *obj);
/*
* Format the object header such as it would appear in the on-disk object
*/
int git_odb__format_object_header(size_t *out_len, char *hdr, size_t hdr_size, git_object_size_t obj_len, git_object_t obj_type);
/*
* Hash an open file descriptor.
* This is a performance call when the contents of a fd need to be hashed,
* but the fd is already open and we have the size of the contents.
*
* Saves us some `stat` calls.
*
* The fd is never closed, not even on error. It must be opened and closed
* by the caller
*/
int git_odb__hashfd(git_oid *out, git_file fd, size_t size, git_object_t type);
/*
* Hash an open file descriptor applying an array of filters
* Acts just like git_odb__hashfd with the addition of filters...
*/
int git_odb__hashfd_filtered(
git_oid *out, git_file fd, size_t len, git_object_t type, git_filter_list *fl);
/*
* Hash a `path`, assuming it could be a POSIX symlink: if the path is a
* symlink, then the raw contents of the symlink will be hashed. Otherwise,
* this will fallback to `git_odb__hashfd`.
*
* The hash type for this call is always `GIT_OBJECT_BLOB` because
* symlinks may only point to blobs.
*/
int git_odb__hashlink(git_oid *out, const char *path);
/**
* Generate a GIT_EMISMATCH error for the ODB.
*/
int git_odb__error_mismatch(
const git_oid *expected, const git_oid *actual);
/*
* Generate a GIT_ENOTFOUND error for the ODB.
*/
int git_odb__error_notfound(
const char *message, const git_oid *oid, size_t oid_len);
/*
* Generate a GIT_EAMBIGUOUS error for the ODB.
*/
int git_odb__error_ambiguous(const char *message);
/*
* Attempt to read object header or just return whole object if it could
* not be read.
*/
int git_odb__read_header_or_object(
git_odb_object **out, size_t *len_p, git_object_t *type_p,
git_odb *db, const git_oid *id);
/*
* Attempt to get the ODB's commit-graph file. This object is still owned by
* the ODB. If the repository does not contain a commit-graph, it will return
* GIT_ENOTFOUND.
*/
int git_odb__get_commit_graph_file(git_commit_graph_file **out, git_odb *odb);
/* freshen an entry in the object database */
int git_odb__freshen(git_odb *db, const git_oid *id);
/* fully free the object; internal method, DO NOT EXPORT */
void git_odb_object__free(void *object);
#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.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_fetchhead_h__
#define INCLUDE_fetchhead_h__
#include "common.h"
#include "oid.h"
#include "vector.h"
typedef struct git_fetchhead_ref {
git_oid oid;
unsigned int is_merge;
char *ref_name;
char *remote_url;
} git_fetchhead_ref;
int git_fetchhead_ref_create(
git_fetchhead_ref **fetchhead_ref_out,
git_oid *oid,
unsigned int is_merge,
const char *ref_name,
const char *remote_url);
int git_fetchhead_ref_cmp(const void *a, const void *b);
int git_fetchhead_write(git_repository *repo, git_vector *fetchhead_refs);
void git_fetchhead_ref_free(git_fetchhead_ref *fetchhead_ref);
#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/iterator.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 "iterator.h"
#include "tree.h"
#include "index.h"
#define GIT_ITERATOR_FIRST_ACCESS (1 << 15)
#define GIT_ITERATOR_HONOR_IGNORES (1 << 16)
#define GIT_ITERATOR_IGNORE_DOT_GIT (1 << 17)
#define iterator__flag(I,F) ((((git_iterator *)(I))->flags & GIT_ITERATOR_ ## F) != 0)
#define iterator__ignore_case(I) iterator__flag(I,IGNORE_CASE)
#define iterator__include_trees(I) iterator__flag(I,INCLUDE_TREES)
#define iterator__dont_autoexpand(I) iterator__flag(I,DONT_AUTOEXPAND)
#define iterator__do_autoexpand(I) !iterator__flag(I,DONT_AUTOEXPAND)
#define iterator__include_conflicts(I) iterator__flag(I,INCLUDE_CONFLICTS)
#define iterator__has_been_accessed(I) iterator__flag(I,FIRST_ACCESS)
#define iterator__honor_ignores(I) iterator__flag(I,HONOR_IGNORES)
#define iterator__ignore_dot_git(I) iterator__flag(I,IGNORE_DOT_GIT)
#define iterator__descend_symlinks(I) iterator__flag(I,DESCEND_SYMLINKS)
static void iterator_set_ignore_case(git_iterator *iter, bool ignore_case)
{
if (ignore_case)
iter->flags |= GIT_ITERATOR_IGNORE_CASE;
else
iter->flags &= ~GIT_ITERATOR_IGNORE_CASE;
iter->strcomp = ignore_case ? git__strcasecmp : git__strcmp;
iter->strncomp = ignore_case ? git__strncasecmp : git__strncmp;
iter->prefixcomp = ignore_case ? git__prefixcmp_icase : git__prefixcmp;
iter->entry_srch = ignore_case ? git_index_entry_isrch : git_index_entry_srch;
git_vector_set_cmp(&iter->pathlist, (git_vector_cmp)iter->strcomp);
}
static int iterator_range_init(
git_iterator *iter, const char *start, const char *end)
{
if (start && *start) {
iter->start = git__strdup(start);
GIT_ERROR_CHECK_ALLOC(iter->start);
iter->start_len = strlen(iter->start);
}
if (end && *end) {
iter->end = git__strdup(end);
GIT_ERROR_CHECK_ALLOC(iter->end);
iter->end_len = strlen(iter->end);
}
iter->started = (iter->start == NULL);
iter->ended = false;
return 0;
}
static void iterator_range_free(git_iterator *iter)
{
if (iter->start) {
git__free(iter->start);
iter->start = NULL;
iter->start_len = 0;
}
if (iter->end) {
git__free(iter->end);
iter->end = NULL;
iter->end_len = 0;
}
}
static int iterator_reset_range(
git_iterator *iter, const char *start, const char *end)
{
iterator_range_free(iter);
return iterator_range_init(iter, start, end);
}
static int iterator_pathlist_init(git_iterator *iter, git_strarray *pathlist)
{
size_t i;
if (git_vector_init(&iter->pathlist, pathlist->count, NULL) < 0)
return -1;
for (i = 0; i < pathlist->count; i++) {
if (!pathlist->strings[i])
continue;
if (git_vector_insert(&iter->pathlist, pathlist->strings[i]) < 0)
return -1;
}
return 0;
}
static int iterator_init_common(
git_iterator *iter,
git_repository *repo,
git_index *index,
git_iterator_options *given_opts)
{
static git_iterator_options default_opts = GIT_ITERATOR_OPTIONS_INIT;
git_iterator_options *options = given_opts ? given_opts : &default_opts;
bool ignore_case;
int precompose;
int error;
iter->repo = repo;
iter->index = index;
iter->flags = options->flags;
if ((iter->flags & GIT_ITERATOR_IGNORE_CASE) != 0) {
ignore_case = true;
} else if ((iter->flags & GIT_ITERATOR_DONT_IGNORE_CASE) != 0) {
ignore_case = false;
} else if (repo) {
git_index *index;
if ((error = git_repository_index__weakptr(&index, iter->repo)) < 0)
return error;
ignore_case = !!index->ignore_case;
if (ignore_case == 1)
iter->flags |= GIT_ITERATOR_IGNORE_CASE;
else
iter->flags |= GIT_ITERATOR_DONT_IGNORE_CASE;
} else {
ignore_case = false;
}
/* try to look up precompose and set flag if appropriate */
if (repo &&
(iter->flags & GIT_ITERATOR_PRECOMPOSE_UNICODE) == 0 &&
(iter->flags & GIT_ITERATOR_DONT_PRECOMPOSE_UNICODE) == 0) {
if (git_repository__configmap_lookup(&precompose, repo, GIT_CONFIGMAP_PRECOMPOSE) < 0)
git_error_clear();
else if (precompose)
iter->flags |= GIT_ITERATOR_PRECOMPOSE_UNICODE;
}
if ((iter->flags & GIT_ITERATOR_DONT_AUTOEXPAND))
iter->flags |= GIT_ITERATOR_INCLUDE_TREES;
if ((error = iterator_range_init(iter, options->start, options->end)) < 0 ||
(error = iterator_pathlist_init(iter, &options->pathlist)) < 0)
return error;
iterator_set_ignore_case(iter, ignore_case);
return 0;
}
static void iterator_clear(git_iterator *iter)
{
iter->started = false;
iter->ended = false;
iter->stat_calls = 0;
iter->pathlist_walk_idx = 0;
iter->flags &= ~GIT_ITERATOR_FIRST_ACCESS;
}
GIT_INLINE(bool) iterator_has_started(
git_iterator *iter, const char *path, bool is_submodule)
{
size_t path_len;
if (iter->start == NULL || iter->started == true)
return true;
/* the starting path is generally a prefix - we have started once we
* are prefixed by this path
*/
iter->started = (iter->prefixcomp(path, iter->start) >= 0);
if (iter->started)
return true;
path_len = strlen(path);
/* if, however, we are a submodule, then we support `start` being
* suffixed with a `/` for crazy legacy reasons. match `submod`
* with a start path of `submod/`.
*/
if (is_submodule && iter->start_len && path_len == iter->start_len - 1 &&
iter->start[iter->start_len-1] == '/')
return true;
/* if, however, our current path is a directory, and our starting path
* is _beneath_ that directory, then recurse into the directory (even
* though we have not yet "started")
*/
if (path_len > 0 && path[path_len-1] == '/' &&
iter->strncomp(path, iter->start, path_len) == 0)
return true;
return false;
}
GIT_INLINE(bool) iterator_has_ended(git_iterator *iter, const char *path)
{
if (iter->end == NULL)
return false;
else if (iter->ended)
return true;
iter->ended = (iter->prefixcomp(path, iter->end) > 0);
return iter->ended;
}
/* walker for the index and tree iterator that allows it to walk the sorted
* pathlist entries alongside sorted iterator entries.
*/
static bool iterator_pathlist_next_is(git_iterator *iter, const char *path)
{
char *p;
size_t path_len, p_len, cmp_len, i;
int cmp;
if (iter->pathlist.length == 0)
return true;
git_vector_sort(&iter->pathlist);
path_len = strlen(path);
/* for comparison, drop the trailing slash on the current '/' */
if (path_len && path[path_len-1] == '/')
path_len--;
for (i = iter->pathlist_walk_idx; i < iter->pathlist.length; i++) {
p = iter->pathlist.contents[i];
p_len = strlen(p);
if (p_len && p[p_len-1] == '/')
p_len--;
cmp_len = min(path_len, p_len);
/* see if the pathlist entry is a prefix of this path */
cmp = iter->strncomp(p, path, cmp_len);
/* prefix match - see if there's an exact match, or if we were
* given a path that matches the directory
*/
if (cmp == 0) {
/* if this pathlist entry is not suffixed with a '/' then
* it matches a path that is a file or a directory.
* (eg, pathlist = "foo" and path is "foo" or "foo/" or
* "foo/something")
*/
if (p[cmp_len] == '\0' &&
(path[cmp_len] == '\0' || path[cmp_len] == '/'))
return true;
/* if this pathlist entry _is_ suffixed with a '/' then
* it matches only paths that are directories.
* (eg, pathlist = "foo/" and path is "foo/" or "foo/something")
*/
if (p[cmp_len] == '/' && path[cmp_len] == '/')
return true;
}
/* this pathlist entry sorts before the given path, try the next */
else if (cmp < 0) {
iter->pathlist_walk_idx++;
continue;
}
/* this pathlist sorts after the given path, no match. */
else if (cmp > 0) {
break;
}
}
return false;
}
typedef enum {
ITERATOR_PATHLIST_NONE = 0,
ITERATOR_PATHLIST_IS_FILE = 1,
ITERATOR_PATHLIST_IS_DIR = 2,
ITERATOR_PATHLIST_IS_PARENT = 3,
ITERATOR_PATHLIST_FULL = 4,
} iterator_pathlist_search_t;
static iterator_pathlist_search_t iterator_pathlist_search(
git_iterator *iter, const char *path, size_t path_len)
{
const char *p;
size_t idx;
int error;
if (iter->pathlist.length == 0)
return ITERATOR_PATHLIST_FULL;
git_vector_sort(&iter->pathlist);
error = git_vector_bsearch2(&idx, &iter->pathlist,
(git_vector_cmp)iter->strcomp, path);
/* the given path was found in the pathlist. since the pathlist only
* matches directories when they're suffixed with a '/', analyze the
* path string to determine whether it's a directory or not.
*/
if (error == 0) {
if (path_len && path[path_len-1] == '/')
return ITERATOR_PATHLIST_IS_DIR;
return ITERATOR_PATHLIST_IS_FILE;
}
/* at this point, the path we're examining may be a directory (though we
* don't know that yet, since we're avoiding a stat unless it's necessary)
* so walk the pathlist looking for the given path with a '/' after it,
*/
while ((p = git_vector_get(&iter->pathlist, idx)) != NULL) {
if (iter->prefixcomp(p, path) != 0)
break;
/* an exact match would have been matched by the bsearch above */
GIT_ASSERT_WITH_RETVAL(p[path_len], ITERATOR_PATHLIST_NONE);
/* is this a literal directory entry (eg `foo/`) or a file beneath */
if (p[path_len] == '/') {
return (p[path_len+1] == '\0') ?
ITERATOR_PATHLIST_IS_DIR :
ITERATOR_PATHLIST_IS_PARENT;
}
if (p[path_len] > '/')
break;
idx++;
}
return ITERATOR_PATHLIST_NONE;
}
/* Empty iterator */
static int empty_iterator_noop(const git_index_entry **e, git_iterator *i)
{
GIT_UNUSED(i);
if (e)
*e = NULL;
return GIT_ITEROVER;
}
static int empty_iterator_advance_over(
const git_index_entry **e,
git_iterator_status_t *s,
git_iterator *i)
{
*s = GIT_ITERATOR_STATUS_EMPTY;
return empty_iterator_noop(e, i);
}
static int empty_iterator_reset(git_iterator *i)
{
GIT_UNUSED(i);
return 0;
}
static void empty_iterator_free(git_iterator *i)
{
GIT_UNUSED(i);
}
typedef struct {
git_iterator base;
git_iterator_callbacks cb;
} empty_iterator;
int git_iterator_for_nothing(
git_iterator **out,
git_iterator_options *options)
{
empty_iterator *iter;
static git_iterator_callbacks callbacks = {
empty_iterator_noop,
empty_iterator_noop,
empty_iterator_noop,
empty_iterator_advance_over,
empty_iterator_reset,
empty_iterator_free
};
*out = NULL;
iter = git__calloc(1, sizeof(empty_iterator));
GIT_ERROR_CHECK_ALLOC(iter);
iter->base.type = GIT_ITERATOR_EMPTY;
iter->base.cb = &callbacks;
iter->base.flags = options->flags;
*out = &iter->base;
return 0;
}
/* Tree iterator */
typedef struct {
git_tree_entry *tree_entry;
const char *parent_path;
} tree_iterator_entry;
typedef struct {
git_tree *tree;
/* path to this particular frame (folder) */
git_buf path;
/* a sorted list of the entries for this frame (folder), these are
* actually pointers to the iterator's entry pool.
*/
git_vector entries;
tree_iterator_entry *current;
size_t next_idx;
/* on case insensitive iterations, we also have an array of other
* paths that were case insensitively equal to this one, and their
* tree objects. we have coalesced the tree entries into this frame.
* a child `tree_iterator_entry` will contain a pointer to its actual
* parent path.
*/
git_vector similar_trees;
git_array_t(git_buf) similar_paths;
} tree_iterator_frame;
typedef struct {
git_iterator base;
git_tree *root;
git_array_t(tree_iterator_frame) frames;
git_index_entry entry;
git_buf entry_path;
/* a pool of entries to reduce the number of allocations */
git_pool entry_pool;
} tree_iterator;
GIT_INLINE(tree_iterator_frame *) tree_iterator_parent_frame(
tree_iterator *iter)
{
return iter->frames.size > 1 ?
&iter->frames.ptr[iter->frames.size-2] : NULL;
}
GIT_INLINE(tree_iterator_frame *) tree_iterator_current_frame(
tree_iterator *iter)
{
return iter->frames.size ? &iter->frames.ptr[iter->frames.size-1] : NULL;
}
GIT_INLINE(int) tree_entry_cmp(
const git_tree_entry *a, const git_tree_entry *b, bool icase)
{
return git_path_cmp(
a->filename, a->filename_len, a->attr == GIT_FILEMODE_TREE,
b->filename, b->filename_len, b->attr == GIT_FILEMODE_TREE,
icase ? git__strncasecmp : git__strncmp);
}
GIT_INLINE(int) tree_iterator_entry_cmp_icase(
const void *ptr_a, const void *ptr_b)
{
const tree_iterator_entry *a = (const tree_iterator_entry *)ptr_a;
const tree_iterator_entry *b = (const tree_iterator_entry *)ptr_b;
return tree_entry_cmp(a->tree_entry, b->tree_entry, true);
}
static int tree_iterator_entry_sort_icase(const void *ptr_a, const void *ptr_b)
{
const tree_iterator_entry *a = (const tree_iterator_entry *)ptr_a;
const tree_iterator_entry *b = (const tree_iterator_entry *)ptr_b;
int c = tree_entry_cmp(a->tree_entry, b->tree_entry, true);
/* stabilize the sort order for filenames that are (case insensitively)
* the same by examining the parent path (case sensitively) before
* falling back to a case sensitive sort of the filename.
*/
if (!c && a->parent_path != b->parent_path)
c = git__strcmp(a->parent_path, b->parent_path);
if (!c)
c = tree_entry_cmp(a->tree_entry, b->tree_entry, false);
return c;
}
static int tree_iterator_compute_path(
git_buf *out,
tree_iterator_entry *entry)
{
git_buf_clear(out);
if (entry->parent_path)
git_buf_joinpath(out, entry->parent_path, entry->tree_entry->filename);
else
git_buf_puts(out, entry->tree_entry->filename);
if (git_tree_entry__is_tree(entry->tree_entry))
git_buf_putc(out, '/');
if (git_buf_oom(out))
return -1;
return 0;
}
static int tree_iterator_frame_init(
tree_iterator *iter,
git_tree *tree,
tree_iterator_entry *frame_entry)
{
tree_iterator_frame *new_frame = NULL;
tree_iterator_entry *new_entry;
git_tree *dup = NULL;
git_tree_entry *tree_entry;
git_vector_cmp cmp;
size_t i;
int error = 0;
new_frame = git_array_alloc(iter->frames);
GIT_ERROR_CHECK_ALLOC(new_frame);
if ((error = git_tree_dup(&dup, tree)) < 0)
goto done;
memset(new_frame, 0x0, sizeof(tree_iterator_frame));
new_frame->tree = dup;
if (frame_entry &&
(error = tree_iterator_compute_path(&new_frame->path, frame_entry)) < 0)
goto done;
cmp = iterator__ignore_case(&iter->base) ?
tree_iterator_entry_sort_icase : NULL;
if ((error = git_vector_init(&new_frame->entries,
dup->entries.size, cmp)) < 0)
goto done;
git_array_foreach(dup->entries, i, tree_entry) {
if ((new_entry = git_pool_malloc(&iter->entry_pool, 1)) == NULL) {
git_error_set_oom();
error = -1;
goto done;
}
new_entry->tree_entry = tree_entry;
new_entry->parent_path = new_frame->path.ptr;
if ((error = git_vector_insert(&new_frame->entries, new_entry)) < 0)
goto done;
}
git_vector_set_sorted(&new_frame->entries,
!iterator__ignore_case(&iter->base));
done:
if (error < 0) {
git_tree_free(dup);
git_array_pop(iter->frames);
}
return error;
}
GIT_INLINE(tree_iterator_entry *) tree_iterator_current_entry(
tree_iterator_frame *frame)
{
return frame->current;
}
GIT_INLINE(int) tree_iterator_frame_push_neighbors(
tree_iterator *iter,
tree_iterator_frame *parent_frame,
tree_iterator_frame *frame,
const char *filename)
{
tree_iterator_entry *entry, *new_entry;
git_tree *tree = NULL;
git_tree_entry *tree_entry;
git_buf *path;
size_t new_size, i;
int error = 0;
while (parent_frame->next_idx < parent_frame->entries.length) {
entry = parent_frame->entries.contents[parent_frame->next_idx];
if (strcasecmp(filename, entry->tree_entry->filename) != 0)
break;
if ((error = git_tree_lookup(&tree,
iter->base.repo, entry->tree_entry->oid)) < 0)
break;
if (git_vector_insert(&parent_frame->similar_trees, tree) < 0)
break;
path = git_array_alloc(parent_frame->similar_paths);
GIT_ERROR_CHECK_ALLOC(path);
memset(path, 0, sizeof(git_buf));
if ((error = tree_iterator_compute_path(path, entry)) < 0)
break;
GIT_ERROR_CHECK_ALLOC_ADD(&new_size,
frame->entries.length, tree->entries.size);
git_vector_size_hint(&frame->entries, new_size);
git_array_foreach(tree->entries, i, tree_entry) {
new_entry = git_pool_malloc(&iter->entry_pool, 1);
GIT_ERROR_CHECK_ALLOC(new_entry);
new_entry->tree_entry = tree_entry;
new_entry->parent_path = path->ptr;
if ((error = git_vector_insert(&frame->entries, new_entry)) < 0)
break;
}
if (error)
break;
parent_frame->next_idx++;
}
return error;
}
GIT_INLINE(int) tree_iterator_frame_push(
tree_iterator *iter, tree_iterator_entry *entry)
{
tree_iterator_frame *parent_frame, *frame;
git_tree *tree = NULL;
int error;
if ((error = git_tree_lookup(&tree,
iter->base.repo, entry->tree_entry->oid)) < 0 ||
(error = tree_iterator_frame_init(iter, tree, entry)) < 0)
goto done;
parent_frame = tree_iterator_parent_frame(iter);
frame = tree_iterator_current_frame(iter);
/* if we're case insensitive, then we may have another directory that
* is (case insensitively) equal to this one. coalesce those children
* into this tree.
*/
if (iterator__ignore_case(&iter->base))
error = tree_iterator_frame_push_neighbors(iter,
parent_frame, frame, entry->tree_entry->filename);
done:
git_tree_free(tree);
return error;
}
static int tree_iterator_frame_pop(tree_iterator *iter)
{
tree_iterator_frame *frame;
git_buf *buf = NULL;
git_tree *tree;
size_t i;
GIT_ASSERT(iter->frames.size);
frame = git_array_pop(iter->frames);
git_vector_free(&frame->entries);
git_tree_free(frame->tree);
do {
buf = git_array_pop(frame->similar_paths);
git_buf_dispose(buf);
} while (buf != NULL);
git_array_clear(frame->similar_paths);
git_vector_foreach(&frame->similar_trees, i, tree)
git_tree_free(tree);
git_vector_free(&frame->similar_trees);
git_buf_dispose(&frame->path);
return 0;
}
static int tree_iterator_current(
const git_index_entry **out, git_iterator *i)
{
tree_iterator *iter = (tree_iterator *)i;
if (!iterator__has_been_accessed(i))
return iter->base.cb->advance(out, i);
if (!iter->frames.size) {
*out = NULL;
return GIT_ITEROVER;
}
*out = &iter->entry;
return 0;
}
static void tree_iterator_set_current(
tree_iterator *iter,
tree_iterator_frame *frame,
tree_iterator_entry *entry)
{
git_tree_entry *tree_entry = entry->tree_entry;
frame->current = entry;
memset(&iter->entry, 0x0, sizeof(git_index_entry));
iter->entry.mode = tree_entry->attr;
iter->entry.path = iter->entry_path.ptr;
git_oid_cpy(&iter->entry.id, tree_entry->oid);
}
static int tree_iterator_advance(const git_index_entry **out, git_iterator *i)
{
tree_iterator *iter = (tree_iterator *)i;
int error = 0;
iter->base.flags |= GIT_ITERATOR_FIRST_ACCESS;
/* examine tree entries until we find the next one to return */
while (true) {
tree_iterator_entry *prev_entry, *entry;
tree_iterator_frame *frame;
bool is_tree;
if ((frame = tree_iterator_current_frame(iter)) == NULL) {
error = GIT_ITEROVER;
break;
}
/* no more entries in this frame. pop the frame out */
if (frame->next_idx == frame->entries.length) {
if ((error = tree_iterator_frame_pop(iter)) < 0)
break;
continue;
}
/* we may have coalesced the contents of case-insensitively same-named
* directories, so do the sort now.
*/
if (frame->next_idx == 0 && !git_vector_is_sorted(&frame->entries))
git_vector_sort(&frame->entries);
/* we have more entries in the current frame, that's our next entry */
prev_entry = tree_iterator_current_entry(frame);
entry = frame->entries.contents[frame->next_idx];
frame->next_idx++;
/* we can have collisions when iterating case insensitively. (eg,
* 'A/a' and 'a/A'). squash this one if it's already been seen.
*/
if (iterator__ignore_case(&iter->base) &&
prev_entry &&
tree_iterator_entry_cmp_icase(prev_entry, entry) == 0)
continue;
if ((error = tree_iterator_compute_path(&iter->entry_path, entry)) < 0)
break;
/* if this path is before our start, advance over this entry */
if (!iterator_has_started(&iter->base, iter->entry_path.ptr, false))
continue;
/* if this path is after our end, stop */
if (iterator_has_ended(&iter->base, iter->entry_path.ptr)) {
error = GIT_ITEROVER;
break;
}
/* if we have a list of paths we're interested in, examine it */
if (!iterator_pathlist_next_is(&iter->base, iter->entry_path.ptr))
continue;
is_tree = git_tree_entry__is_tree(entry->tree_entry);
/* if we are *not* including trees then advance over this entry */
if (is_tree && !iterator__include_trees(iter)) {
/* if we've found a tree (and are not returning it to the caller)
* and we are autoexpanding, then we want to return the first
* child. push the new directory and advance.
*/
if (iterator__do_autoexpand(iter)) {
if ((error = tree_iterator_frame_push(iter, entry)) < 0)
break;
}
continue;
}
tree_iterator_set_current(iter, frame, entry);
/* if we are autoexpanding, then push this as a new frame, so that
* the next call to `advance` will dive into this directory.
*/
if (is_tree && iterator__do_autoexpand(iter))
error = tree_iterator_frame_push(iter, entry);
break;
}
if (out)
*out = (error == 0) ? &iter->entry : NULL;
return error;
}
static int tree_iterator_advance_into(
const git_index_entry **out, git_iterator *i)
{
tree_iterator *iter = (tree_iterator *)i;
tree_iterator_frame *frame;
tree_iterator_entry *prev_entry;
int error;
if (out)
*out = NULL;
if ((frame = tree_iterator_current_frame(iter)) == NULL)
return GIT_ITEROVER;
/* get the last seen entry */
prev_entry = tree_iterator_current_entry(frame);
/* it's legal to call advance_into when auto-expand is on. in this case,
* we will have pushed a new (empty) frame on to the stack for this
* new directory. since it's empty, its current_entry should be null.
*/
GIT_ASSERT(iterator__do_autoexpand(i) ^ (prev_entry != NULL));
if (prev_entry) {
if (!git_tree_entry__is_tree(prev_entry->tree_entry))
return 0;
if ((error = tree_iterator_frame_push(iter, prev_entry)) < 0)
return error;
}
/* we've advanced into the directory in question, let advance
* find the first entry
*/
return tree_iterator_advance(out, i);
}
static int tree_iterator_advance_over(
const git_index_entry **out,
git_iterator_status_t *status,
git_iterator *i)
{
*status = GIT_ITERATOR_STATUS_NORMAL;
return git_iterator_advance(out, i);
}
static void tree_iterator_clear(tree_iterator *iter)
{
while (iter->frames.size)
tree_iterator_frame_pop(iter);
git_array_clear(iter->frames);
git_pool_clear(&iter->entry_pool);
git_buf_clear(&iter->entry_path);
iterator_clear(&iter->base);
}
static int tree_iterator_init(tree_iterator *iter)
{
int error;
if ((error = git_pool_init(&iter->entry_pool, sizeof(tree_iterator_entry))) < 0 ||
(error = tree_iterator_frame_init(iter, iter->root, NULL)) < 0)
return error;
iter->base.flags &= ~GIT_ITERATOR_FIRST_ACCESS;
return 0;
}
static int tree_iterator_reset(git_iterator *i)
{
tree_iterator *iter = (tree_iterator *)i;
tree_iterator_clear(iter);
return tree_iterator_init(iter);
}
static void tree_iterator_free(git_iterator *i)
{
tree_iterator *iter = (tree_iterator *)i;
tree_iterator_clear(iter);
git_tree_free(iter->root);
git_buf_dispose(&iter->entry_path);
}
int git_iterator_for_tree(
git_iterator **out,
git_tree *tree,
git_iterator_options *options)
{
tree_iterator *iter;
int error;
static git_iterator_callbacks callbacks = {
tree_iterator_current,
tree_iterator_advance,
tree_iterator_advance_into,
tree_iterator_advance_over,
tree_iterator_reset,
tree_iterator_free
};
*out = NULL;
if (tree == NULL)
return git_iterator_for_nothing(out, options);
iter = git__calloc(1, sizeof(tree_iterator));
GIT_ERROR_CHECK_ALLOC(iter);
iter->base.type = GIT_ITERATOR_TREE;
iter->base.cb = &callbacks;
if ((error = iterator_init_common(&iter->base,
git_tree_owner(tree), NULL, options)) < 0 ||
(error = git_tree_dup(&iter->root, tree)) < 0 ||
(error = tree_iterator_init(iter)) < 0)
goto on_error;
*out = &iter->base;
return 0;
on_error:
git_iterator_free(&iter->base);
return error;
}
int git_iterator_current_tree_entry(
const git_tree_entry **tree_entry, git_iterator *i)
{
tree_iterator *iter;
tree_iterator_frame *frame;
tree_iterator_entry *entry;
GIT_ASSERT(i->type == GIT_ITERATOR_TREE);
iter = (tree_iterator *)i;
frame = tree_iterator_current_frame(iter);
entry = tree_iterator_current_entry(frame);
*tree_entry = entry->tree_entry;
return 0;
}
int git_iterator_current_parent_tree(
const git_tree **parent_tree, git_iterator *i, size_t depth)
{
tree_iterator *iter;
tree_iterator_frame *frame;
GIT_ASSERT(i->type == GIT_ITERATOR_TREE);
iter = (tree_iterator *)i;
GIT_ASSERT(depth < iter->frames.size);
frame = &iter->frames.ptr[iter->frames.size-depth-1];
*parent_tree = frame->tree;
return 0;
}
/* Filesystem iterator */
typedef struct {
struct stat st;
size_t path_len;
iterator_pathlist_search_t match;
git_oid id;
char path[GIT_FLEX_ARRAY];
} filesystem_iterator_entry;
typedef struct {
git_vector entries;
git_pool entry_pool;
size_t next_idx;
size_t path_len;
int is_ignored;
} filesystem_iterator_frame;
typedef struct {
git_iterator base;
char *root;
size_t root_len;
unsigned int dirload_flags;
git_tree *tree;
git_index *index;
git_vector index_snapshot;
git_array_t(filesystem_iterator_frame) frames;
git_ignores ignores;
/* info about the current entry */
git_index_entry entry;
git_buf current_path;
int current_is_ignored;
/* temporary buffer for advance_over */
git_buf tmp_buf;
} filesystem_iterator;
GIT_INLINE(filesystem_iterator_frame *) filesystem_iterator_parent_frame(
filesystem_iterator *iter)
{
return iter->frames.size > 1 ?
&iter->frames.ptr[iter->frames.size-2] : NULL;
}
GIT_INLINE(filesystem_iterator_frame *) filesystem_iterator_current_frame(
filesystem_iterator *iter)
{
return iter->frames.size ? &iter->frames.ptr[iter->frames.size-1] : NULL;
}
GIT_INLINE(filesystem_iterator_entry *) filesystem_iterator_current_entry(
filesystem_iterator_frame *frame)
{
return frame->next_idx == 0 ?
NULL : frame->entries.contents[frame->next_idx-1];
}
static int filesystem_iterator_entry_cmp(const void *_a, const void *_b)
{
const filesystem_iterator_entry *a = (const filesystem_iterator_entry *)_a;
const filesystem_iterator_entry *b = (const filesystem_iterator_entry *)_b;
return git__strcmp(a->path, b->path);
}
static int filesystem_iterator_entry_cmp_icase(const void *_a, const void *_b)
{
const filesystem_iterator_entry *a = (const filesystem_iterator_entry *)_a;
const filesystem_iterator_entry *b = (const filesystem_iterator_entry *)_b;
return git__strcasecmp(a->path, b->path);
}
#define FILESYSTEM_MAX_DEPTH 100
/**
* Figure out if an entry is a submodule.
*
* We consider it a submodule if the path is listed as a submodule in
* either the tree or the index.
*/
static int filesystem_iterator_is_submodule(
bool *out, filesystem_iterator *iter, const char *path, size_t path_len)
{
bool is_submodule = false;
int error;
*out = false;
/* first see if this path is a submodule in HEAD */
if (iter->tree) {
git_tree_entry *entry;
error = git_tree_entry_bypath(&entry, iter->tree, path);
if (error < 0 && error != GIT_ENOTFOUND)
return error;
if (!error) {
is_submodule = (entry->attr == GIT_FILEMODE_COMMIT);
git_tree_entry_free(entry);
}
}
if (!is_submodule && iter->base.index) {
size_t pos;
error = git_index_snapshot_find(&pos,
&iter->index_snapshot, iter->base.entry_srch, path, path_len, 0);
if (error < 0 && error != GIT_ENOTFOUND)
return error;
if (!error) {
git_index_entry *e = git_vector_get(&iter->index_snapshot, pos);
is_submodule = (e->mode == GIT_FILEMODE_COMMIT);
}
}
*out = is_submodule;
return 0;
}
static void filesystem_iterator_frame_push_ignores(
filesystem_iterator *iter,
filesystem_iterator_entry *frame_entry,
filesystem_iterator_frame *new_frame)
{
filesystem_iterator_frame *previous_frame;
const char *path = frame_entry ? frame_entry->path : "";
if (!iterator__honor_ignores(&iter->base))
return;
if (git_ignore__lookup(&new_frame->is_ignored,
&iter->ignores, path, GIT_DIR_FLAG_TRUE) < 0) {
git_error_clear();
new_frame->is_ignored = GIT_IGNORE_NOTFOUND;
}
/* if this is not the top level directory... */
if (frame_entry) {
const char *relative_path;
previous_frame = filesystem_iterator_parent_frame(iter);
/* push new ignores for files in this directory */
relative_path = frame_entry->path + previous_frame->path_len;
/* inherit ignored from parent if no rule specified */
if (new_frame->is_ignored <= GIT_IGNORE_NOTFOUND)
new_frame->is_ignored = previous_frame->is_ignored;
git_ignore__push_dir(&iter->ignores, relative_path);
}
}
static void filesystem_iterator_frame_pop_ignores(
filesystem_iterator *iter)
{
if (iterator__honor_ignores(&iter->base))
git_ignore__pop_dir(&iter->ignores);
}
GIT_INLINE(bool) filesystem_iterator_examine_path(
bool *is_dir_out,
iterator_pathlist_search_t *match_out,
filesystem_iterator *iter,
filesystem_iterator_entry *frame_entry,
const char *path,
size_t path_len)
{
bool is_dir = 0;
iterator_pathlist_search_t match = ITERATOR_PATHLIST_FULL;
*is_dir_out = false;
*match_out = ITERATOR_PATHLIST_NONE;
if (iter->base.start_len) {
int cmp = iter->base.strncomp(path, iter->base.start, path_len);
/* we haven't stat'ed `path` yet, so we don't yet know if it's a
* directory or not. special case if the current path may be a
* directory that matches the start prefix.
*/
if (cmp == 0) {
if (iter->base.start[path_len] == '/')
is_dir = true;
else if (iter->base.start[path_len] != '\0')
cmp = -1;
}
if (cmp < 0)
return false;
}
if (iter->base.end_len) {
int cmp = iter->base.strncomp(path, iter->base.end, iter->base.end_len);
if (cmp > 0)
return false;
}
/* if we have a pathlist that we're limiting to, examine this path now
* to avoid a `stat` if we're not interested in the path.
*/
if (iter->base.pathlist.length) {
/* if our parent was explicitly included, so too are we */
if (frame_entry && frame_entry->match != ITERATOR_PATHLIST_IS_PARENT)
match = ITERATOR_PATHLIST_FULL;
else
match = iterator_pathlist_search(&iter->base, path, path_len);
if (match == ITERATOR_PATHLIST_NONE)
return false;
/* Ensure that the pathlist entry lines up with what we expected */
if (match == ITERATOR_PATHLIST_IS_DIR ||
match == ITERATOR_PATHLIST_IS_PARENT)
is_dir = true;
}
*is_dir_out = is_dir;
*match_out = match;
return true;
}
GIT_INLINE(bool) filesystem_iterator_is_dot_git(
filesystem_iterator *iter, const char *path, size_t path_len)
{
size_t len;
if (!iterator__ignore_dot_git(&iter->base))
return false;
if ((len = path_len) < 4)
return false;
if (path[len - 1] == '/')
len--;
if (git__tolower(path[len - 1]) != 't' ||
git__tolower(path[len - 2]) != 'i' ||
git__tolower(path[len - 3]) != 'g' ||
git__tolower(path[len - 4]) != '.')
return false;
return (len == 4 || path[len - 5] == '/');
}
static int filesystem_iterator_entry_hash(
filesystem_iterator *iter,
filesystem_iterator_entry *entry)
{
git_buf fullpath = GIT_BUF_INIT;
int error;
if (S_ISDIR(entry->st.st_mode)) {
memset(&entry->id, 0, GIT_OID_RAWSZ);
return 0;
}
if (iter->base.type == GIT_ITERATOR_WORKDIR)
return git_repository_hashfile(&entry->id,
iter->base.repo, entry->path, GIT_OBJECT_BLOB, NULL);
if (!(error = git_buf_joinpath(&fullpath, iter->root, entry->path)) &&
!(error = git_path_validate_workdir_buf(iter->base.repo, &fullpath)))
error = git_odb_hashfile(&entry->id, fullpath.ptr, GIT_OBJECT_BLOB);
git_buf_dispose(&fullpath);
return error;
}
static int filesystem_iterator_entry_init(
filesystem_iterator_entry **out,
filesystem_iterator *iter,
filesystem_iterator_frame *frame,
const char *path,
size_t path_len,
struct stat *statbuf,
iterator_pathlist_search_t pathlist_match)
{
filesystem_iterator_entry *entry;
size_t entry_size;
int error = 0;
*out = NULL;
/* Make sure to append two bytes, one for the path's null
* termination, one for a possible trailing '/' for folders.
*/
GIT_ERROR_CHECK_ALLOC_ADD(&entry_size,
sizeof(filesystem_iterator_entry), path_len);
GIT_ERROR_CHECK_ALLOC_ADD(&entry_size, entry_size, 2);
entry = git_pool_malloc(&frame->entry_pool, entry_size);
GIT_ERROR_CHECK_ALLOC(entry);
entry->path_len = path_len;
entry->match = pathlist_match;
memcpy(entry->path, path, path_len);
memcpy(&entry->st, statbuf, sizeof(struct stat));
/* Suffix directory paths with a '/' */
if (S_ISDIR(entry->st.st_mode))
entry->path[entry->path_len++] = '/';
entry->path[entry->path_len] = '\0';
if (iter->base.flags & GIT_ITERATOR_INCLUDE_HASH)
error = filesystem_iterator_entry_hash(iter, entry);
if (!error)
*out = entry;
return error;
}
static int filesystem_iterator_frame_push(
filesystem_iterator *iter,
filesystem_iterator_entry *frame_entry)
{
filesystem_iterator_frame *new_frame = NULL;
git_path_diriter diriter = GIT_PATH_DIRITER_INIT;
git_buf root = GIT_BUF_INIT;
const char *path;
filesystem_iterator_entry *entry;
struct stat statbuf;
size_t path_len;
int error;
if (iter->frames.size == FILESYSTEM_MAX_DEPTH) {
git_error_set(GIT_ERROR_REPOSITORY,
"directory nesting too deep (%"PRIuZ")", iter->frames.size);
return -1;
}
new_frame = git_array_alloc(iter->frames);
GIT_ERROR_CHECK_ALLOC(new_frame);
memset(new_frame, 0, sizeof(filesystem_iterator_frame));
if (frame_entry)
git_buf_joinpath(&root, iter->root, frame_entry->path);
else
git_buf_puts(&root, iter->root);
if (git_buf_oom(&root) ||
git_path_validate_workdir_buf(iter->base.repo, &root) < 0) {
error = -1;
goto done;
}
new_frame->path_len = frame_entry ? frame_entry->path_len : 0;
/* Any error here is equivalent to the dir not existing, skip over it */
if ((error = git_path_diriter_init(
&diriter, root.ptr, iter->dirload_flags)) < 0) {
error = GIT_ENOTFOUND;
goto done;
}
if ((error = git_vector_init(&new_frame->entries, 64,
iterator__ignore_case(&iter->base) ?
filesystem_iterator_entry_cmp_icase :
filesystem_iterator_entry_cmp)) < 0)
goto done;
if ((error = git_pool_init(&new_frame->entry_pool, 1)) < 0)
goto done;
/* check if this directory is ignored */
filesystem_iterator_frame_push_ignores(iter, frame_entry, new_frame);
while ((error = git_path_diriter_next(&diriter)) == 0) {
iterator_pathlist_search_t pathlist_match = ITERATOR_PATHLIST_FULL;
bool dir_expected = false;
if ((error = git_path_diriter_fullpath(&path, &path_len, &diriter)) < 0 ||
(error = git_path_validate_workdir_with_len(iter->base.repo, path, path_len)) < 0)
goto done;
GIT_ASSERT(path_len > iter->root_len);
/* remove the prefix if requested */
path += iter->root_len;
path_len -= iter->root_len;
/* examine start / end and the pathlist to see if this path is in it.
* note that since we haven't yet stat'ed the path, we cannot know
* whether it's a directory yet or not, so this can give us an
* expected type (S_IFDIR or S_IFREG) that we should examine)
*/
if (!filesystem_iterator_examine_path(&dir_expected, &pathlist_match,
iter, frame_entry, path, path_len))
continue;
/* TODO: don't need to stat if assume unchanged for this path and
* we have an index, we can just copy the data out of it.
*/
if ((error = git_path_diriter_stat(&statbuf, &diriter)) < 0) {
/* file was removed between readdir and lstat */
if (error == GIT_ENOTFOUND)
continue;
/* treat the file as unreadable */
memset(&statbuf, 0, sizeof(statbuf));
statbuf.st_mode = GIT_FILEMODE_UNREADABLE;
error = 0;
}
iter->base.stat_calls++;
/* Ignore wacky things in the filesystem */
if (!S_ISDIR(statbuf.st_mode) &&
!S_ISREG(statbuf.st_mode) &&
!S_ISLNK(statbuf.st_mode) &&
statbuf.st_mode != GIT_FILEMODE_UNREADABLE)
continue;
if (filesystem_iterator_is_dot_git(iter, path, path_len))
continue;
/* convert submodules to GITLINK and remove trailing slashes */
if (S_ISDIR(statbuf.st_mode)) {
bool submodule = false;
if ((error = filesystem_iterator_is_submodule(&submodule,
iter, path, path_len)) < 0)
goto done;
if (submodule)
statbuf.st_mode = GIT_FILEMODE_COMMIT;
}
/* Ensure that the pathlist entry lines up with what we expected */
else if (dir_expected)
continue;
if ((error = filesystem_iterator_entry_init(&entry,
iter, new_frame, path, path_len, &statbuf, pathlist_match)) < 0)
goto done;
git_vector_insert(&new_frame->entries, entry);
}
if (error == GIT_ITEROVER)
error = 0;
/* sort now that directory suffix is added */
git_vector_sort(&new_frame->entries);
done:
if (error < 0)
git_array_pop(iter->frames);
git_buf_dispose(&root);
git_path_diriter_free(&diriter);
return error;
}
GIT_INLINE(int) filesystem_iterator_frame_pop(filesystem_iterator *iter)
{
filesystem_iterator_frame *frame;
GIT_ASSERT(iter->frames.size);
frame = git_array_pop(iter->frames);
filesystem_iterator_frame_pop_ignores(iter);
git_pool_clear(&frame->entry_pool);
git_vector_free(&frame->entries);
return 0;
}
static void filesystem_iterator_set_current(
filesystem_iterator *iter,
filesystem_iterator_entry *entry)
{
/*
* Index entries are limited to 32 bit timestamps. We can safely
* cast this since workdir times are only used in the cache; any
* mismatch will cause a hash recomputation which is unfortunate
* but affects only people who set their filetimes to 2038.
* (Same with the file size.)
*/
iter->entry.ctime.seconds = (int32_t)entry->st.st_ctime;
iter->entry.mtime.seconds = (int32_t)entry->st.st_mtime;
#if defined(GIT_USE_NSEC)
iter->entry.ctime.nanoseconds = entry->st.st_ctime_nsec;
iter->entry.mtime.nanoseconds = entry->st.st_mtime_nsec;
#else
iter->entry.ctime.nanoseconds = 0;
iter->entry.mtime.nanoseconds = 0;
#endif
iter->entry.dev = entry->st.st_dev;
iter->entry.ino = entry->st.st_ino;
iter->entry.mode = git_futils_canonical_mode(entry->st.st_mode);
iter->entry.uid = entry->st.st_uid;
iter->entry.gid = entry->st.st_gid;
iter->entry.file_size = (uint32_t)entry->st.st_size;
if (iter->base.flags & GIT_ITERATOR_INCLUDE_HASH)
git_oid_cpy(&iter->entry.id, &entry->id);
iter->entry.path = entry->path;
iter->current_is_ignored = GIT_IGNORE_UNCHECKED;
}
static int filesystem_iterator_current(
const git_index_entry **out, git_iterator *i)
{
filesystem_iterator *iter = GIT_CONTAINER_OF(i, filesystem_iterator, base);
if (!iterator__has_been_accessed(i))
return iter->base.cb->advance(out, i);
if (!iter->frames.size) {
*out = NULL;
return GIT_ITEROVER;
}
*out = &iter->entry;
return 0;
}
static int filesystem_iterator_is_dir(
bool *is_dir,
const filesystem_iterator *iter,
const filesystem_iterator_entry *entry)
{
struct stat st;
git_buf fullpath = GIT_BUF_INIT;
int error = 0;
if (S_ISDIR(entry->st.st_mode)) {
*is_dir = 1;
goto done;
}
if (!iterator__descend_symlinks(iter) || !S_ISLNK(entry->st.st_mode)) {
*is_dir = 0;
goto done;
}
if ((error = git_buf_joinpath(&fullpath, iter->root, entry->path)) < 0 ||
(error = git_path_validate_workdir_buf(iter->base.repo, &fullpath)) < 0 ||
(error = p_stat(fullpath.ptr, &st)) < 0)
goto done;
*is_dir = S_ISDIR(st.st_mode);
done:
git_buf_dispose(&fullpath);
return error;
}
static int filesystem_iterator_advance(
const git_index_entry **out, git_iterator *i)
{
filesystem_iterator *iter = GIT_CONTAINER_OF(i, filesystem_iterator, base);
bool is_dir;
int error = 0;
iter->base.flags |= GIT_ITERATOR_FIRST_ACCESS;
/* examine filesystem entries until we find the next one to return */
while (true) {
filesystem_iterator_frame *frame;
filesystem_iterator_entry *entry;
if ((frame = filesystem_iterator_current_frame(iter)) == NULL) {
error = GIT_ITEROVER;
break;
}
/* no more entries in this frame. pop the frame out */
if (frame->next_idx == frame->entries.length) {
filesystem_iterator_frame_pop(iter);
continue;
}
/* we have more entries in the current frame, that's our next entry */
entry = frame->entries.contents[frame->next_idx];
frame->next_idx++;
if ((error = filesystem_iterator_is_dir(&is_dir, iter, entry)) < 0)
break;
if (is_dir) {
if (iterator__do_autoexpand(iter)) {
error = filesystem_iterator_frame_push(iter, entry);
/* may get GIT_ENOTFOUND due to races or permission problems
* that we want to quietly swallow
*/
if (error == GIT_ENOTFOUND)
continue;
else if (error < 0)
break;
}
if (!iterator__include_trees(iter))
continue;
}
filesystem_iterator_set_current(iter, entry);
break;
}
if (out)
*out = (error == 0) ? &iter->entry : NULL;
return error;
}
static int filesystem_iterator_advance_into(
const git_index_entry **out, git_iterator *i)
{
filesystem_iterator *iter = GIT_CONTAINER_OF(i, filesystem_iterator, base);
filesystem_iterator_frame *frame;
filesystem_iterator_entry *prev_entry;
int error;
if (out)
*out = NULL;
if ((frame = filesystem_iterator_current_frame(iter)) == NULL)
return GIT_ITEROVER;
/* get the last seen entry */
prev_entry = filesystem_iterator_current_entry(frame);
/* it's legal to call advance_into when auto-expand is on. in this case,
* we will have pushed a new (empty) frame on to the stack for this
* new directory. since it's empty, its current_entry should be null.
*/
GIT_ASSERT(iterator__do_autoexpand(i) ^ (prev_entry != NULL));
if (prev_entry) {
if (prev_entry->st.st_mode != GIT_FILEMODE_COMMIT &&
!S_ISDIR(prev_entry->st.st_mode))
return 0;
if ((error = filesystem_iterator_frame_push(iter, prev_entry)) < 0)
return error;
}
/* we've advanced into the directory in question, let advance
* find the first entry
*/
return filesystem_iterator_advance(out, i);
}
int git_iterator_current_workdir_path(git_buf **out, git_iterator *i)
{
filesystem_iterator *iter = GIT_CONTAINER_OF(i, filesystem_iterator, base);
const git_index_entry *entry;
if (i->type != GIT_ITERATOR_FS &&
i->type != GIT_ITERATOR_WORKDIR) {
*out = NULL;
return 0;
}
git_buf_truncate(&iter->current_path, iter->root_len);
if (git_iterator_current(&entry, i) < 0 ||
git_buf_puts(&iter->current_path, entry->path) < 0)
return -1;
*out = &iter->current_path;
return 0;
}
GIT_INLINE(git_dir_flag) entry_dir_flag(git_index_entry *entry)
{
#if defined(GIT_WIN32) && !defined(__MINGW32__)
return (entry && entry->mode) ?
(S_ISDIR(entry->mode) ? GIT_DIR_FLAG_TRUE : GIT_DIR_FLAG_FALSE) :
GIT_DIR_FLAG_UNKNOWN;
#else
GIT_UNUSED(entry);
return GIT_DIR_FLAG_UNKNOWN;
#endif
}
static void filesystem_iterator_update_ignored(filesystem_iterator *iter)
{
filesystem_iterator_frame *frame;
git_dir_flag dir_flag = entry_dir_flag(&iter->entry);
if (git_ignore__lookup(&iter->current_is_ignored,
&iter->ignores, iter->entry.path, dir_flag) < 0) {
git_error_clear();
iter->current_is_ignored = GIT_IGNORE_NOTFOUND;
}
/* use ignore from containing frame stack */
if (iter->current_is_ignored <= GIT_IGNORE_NOTFOUND) {
frame = filesystem_iterator_current_frame(iter);
iter->current_is_ignored = frame->is_ignored;
}
}
GIT_INLINE(bool) filesystem_iterator_current_is_ignored(
filesystem_iterator *iter)
{
if (iter->current_is_ignored == GIT_IGNORE_UNCHECKED)
filesystem_iterator_update_ignored(iter);
return (iter->current_is_ignored == GIT_IGNORE_TRUE);
}
bool git_iterator_current_is_ignored(git_iterator *i)
{
filesystem_iterator *iter = NULL;
if (i->type != GIT_ITERATOR_WORKDIR)
return false;
iter = GIT_CONTAINER_OF(i, filesystem_iterator, base);
return filesystem_iterator_current_is_ignored(iter);
}
bool git_iterator_current_tree_is_ignored(git_iterator *i)
{
filesystem_iterator *iter = GIT_CONTAINER_OF(i, filesystem_iterator, base);
filesystem_iterator_frame *frame;
if (i->type != GIT_ITERATOR_WORKDIR)
return false;
frame = filesystem_iterator_current_frame(iter);
return (frame->is_ignored == GIT_IGNORE_TRUE);
}
static int filesystem_iterator_advance_over(
const git_index_entry **out,
git_iterator_status_t *status,
git_iterator *i)
{
filesystem_iterator *iter = GIT_CONTAINER_OF(i, filesystem_iterator, base);
filesystem_iterator_frame *current_frame;
filesystem_iterator_entry *current_entry;
const git_index_entry *entry = NULL;
const char *base;
int error = 0;
*out = NULL;
*status = GIT_ITERATOR_STATUS_NORMAL;
GIT_ASSERT(iterator__has_been_accessed(i));
current_frame = filesystem_iterator_current_frame(iter);
GIT_ASSERT(current_frame);
current_entry = filesystem_iterator_current_entry(current_frame);
GIT_ASSERT(current_entry);
if ((error = git_iterator_current(&entry, i)) < 0)
return error;
if (!S_ISDIR(entry->mode)) {
if (filesystem_iterator_current_is_ignored(iter))
*status = GIT_ITERATOR_STATUS_IGNORED;
return filesystem_iterator_advance(out, i);
}
git_buf_clear(&iter->tmp_buf);
if ((error = git_buf_puts(&iter->tmp_buf, entry->path)) < 0)
return error;
base = iter->tmp_buf.ptr;
/* scan inside the directory looking for files. if we find nothing,
* we will remain EMPTY. if we find any ignored item, upgrade EMPTY to
* IGNORED. if we find a real actual item, upgrade all the way to NORMAL
* and then stop.
*
* however, if we're here looking for a pathlist item (but are not
* actually in the pathlist ourselves) then start at FILTERED instead of
* EMPTY. callers then know that this path was not something they asked
* about.
*/
*status = current_entry->match == ITERATOR_PATHLIST_IS_PARENT ?
GIT_ITERATOR_STATUS_FILTERED : GIT_ITERATOR_STATUS_EMPTY;
while (entry && !iter->base.prefixcomp(entry->path, base)) {
if (filesystem_iterator_current_is_ignored(iter)) {
/* if we found an explicitly ignored item, then update from
* EMPTY to IGNORED
*/
*status = GIT_ITERATOR_STATUS_IGNORED;
} else if (S_ISDIR(entry->mode)) {
error = filesystem_iterator_advance_into(&entry, i);
if (!error)
continue;
/* this directory disappeared, ignore it */
else if (error == GIT_ENOTFOUND)
error = 0;
/* a real error occurred */
else
break;
} else {
/* we found a non-ignored item, treat parent as untracked */
*status = GIT_ITERATOR_STATUS_NORMAL;
break;
}
if ((error = git_iterator_advance(&entry, i)) < 0)
break;
}
/* wrap up scan back to base directory */
while (entry && !iter->base.prefixcomp(entry->path, base)) {
if ((error = git_iterator_advance(&entry, i)) < 0)
break;
}
if (!error)
*out = entry;
return error;
}
static void filesystem_iterator_clear(filesystem_iterator *iter)
{
while (iter->frames.size)
filesystem_iterator_frame_pop(iter);
git_array_clear(iter->frames);
git_ignore__free(&iter->ignores);
git_buf_dispose(&iter->tmp_buf);
iterator_clear(&iter->base);
}
static int filesystem_iterator_init(filesystem_iterator *iter)
{
int error;
if (iterator__honor_ignores(&iter->base) &&
(error = git_ignore__for_path(iter->base.repo,
".gitignore", &iter->ignores)) < 0)
return error;
if ((error = filesystem_iterator_frame_push(iter, NULL)) < 0)
return error;
iter->base.flags &= ~GIT_ITERATOR_FIRST_ACCESS;
return 0;
}
static int filesystem_iterator_reset(git_iterator *i)
{
filesystem_iterator *iter = GIT_CONTAINER_OF(i, filesystem_iterator, base);
filesystem_iterator_clear(iter);
return filesystem_iterator_init(iter);
}
static void filesystem_iterator_free(git_iterator *i)
{
filesystem_iterator *iter = GIT_CONTAINER_OF(i, filesystem_iterator, base);
git__free(iter->root);
git_buf_dispose(&iter->current_path);
git_tree_free(iter->tree);
if (iter->index)
git_index_snapshot_release(&iter->index_snapshot, iter->index);
filesystem_iterator_clear(iter);
}
static int iterator_for_filesystem(
git_iterator **out,
git_repository *repo,
const char *root,
git_index *index,
git_tree *tree,
git_iterator_t type,
git_iterator_options *options)
{
filesystem_iterator *iter;
size_t root_len;
int error;
static git_iterator_callbacks callbacks = {
filesystem_iterator_current,
filesystem_iterator_advance,
filesystem_iterator_advance_into,
filesystem_iterator_advance_over,
filesystem_iterator_reset,
filesystem_iterator_free
};
*out = NULL;
if (root == NULL)
return git_iterator_for_nothing(out, options);
iter = git__calloc(1, sizeof(filesystem_iterator));
GIT_ERROR_CHECK_ALLOC(iter);
iter->base.type = type;
iter->base.cb = &callbacks;
root_len = strlen(root);
iter->root = git__malloc(root_len+2);
GIT_ERROR_CHECK_ALLOC(iter->root);
memcpy(iter->root, root, root_len);
if (root_len == 0 || root[root_len-1] != '/') {
iter->root[root_len] = '/';
root_len++;
}
iter->root[root_len] = '\0';
iter->root_len = root_len;
if ((error = git_buf_puts(&iter->current_path, iter->root)) < 0)
goto on_error;
if ((error = iterator_init_common(&iter->base, repo, index, options)) < 0)
goto on_error;
if (tree && (error = git_tree_dup(&iter->tree, tree)) < 0)
goto on_error;
if (index &&
(error = git_index_snapshot_new(&iter->index_snapshot, index)) < 0)
goto on_error;
iter->index = index;
iter->dirload_flags =
(iterator__ignore_case(&iter->base) ? GIT_PATH_DIR_IGNORE_CASE : 0) |
(iterator__flag(&iter->base, PRECOMPOSE_UNICODE) ?
GIT_PATH_DIR_PRECOMPOSE_UNICODE : 0);
if ((error = filesystem_iterator_init(iter)) < 0)
goto on_error;
*out = &iter->base;
return 0;
on_error:
git_iterator_free(&iter->base);
return error;
}
int git_iterator_for_filesystem(
git_iterator **out,
const char *root,
git_iterator_options *options)
{
return iterator_for_filesystem(out,
NULL, root, NULL, NULL, GIT_ITERATOR_FS, options);
}
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 *given_opts)
{
git_iterator_options options = GIT_ITERATOR_OPTIONS_INIT;
if (!repo_workdir) {
if (git_repository__ensure_not_bare(repo, "scan working directory") < 0)
return GIT_EBAREREPO;
repo_workdir = git_repository_workdir(repo);
}
/* upgrade to a workdir iterator, adding necessary internal flags */
if (given_opts)
memcpy(&options, given_opts, sizeof(git_iterator_options));
options.flags |= GIT_ITERATOR_HONOR_IGNORES |
GIT_ITERATOR_IGNORE_DOT_GIT;
return iterator_for_filesystem(out,
repo, repo_workdir, index, tree, GIT_ITERATOR_WORKDIR, &options);
}
/* Index iterator */
typedef struct {
git_iterator base;
git_vector entries;
size_t next_idx;
/* the pseudotree entry */
git_index_entry tree_entry;
git_buf tree_buf;
bool skip_tree;
const git_index_entry *entry;
} index_iterator;
static int index_iterator_current(
const git_index_entry **out, git_iterator *i)
{
index_iterator *iter = (index_iterator *)i;
if (!iterator__has_been_accessed(i))
return iter->base.cb->advance(out, i);
if (iter->entry == NULL) {
*out = NULL;
return GIT_ITEROVER;
}
*out = iter->entry;
return 0;
}
static bool index_iterator_create_pseudotree(
const git_index_entry **out,
index_iterator *iter,
const char *path)
{
const char *prev_path, *relative_path, *dirsep;
size_t common_len;
prev_path = iter->entry ? iter->entry->path : "";
/* determine if the new path is in a different directory from the old */
common_len = git_path_common_dirlen(prev_path, path);
relative_path = path + common_len;
if ((dirsep = strchr(relative_path, '/')) == NULL)
return false;
git_buf_clear(&iter->tree_buf);
git_buf_put(&iter->tree_buf, path, (dirsep - path) + 1);
iter->tree_entry.mode = GIT_FILEMODE_TREE;
iter->tree_entry.path = iter->tree_buf.ptr;
*out = &iter->tree_entry;
return true;
}
static int index_iterator_skip_pseudotree(index_iterator *iter)
{
GIT_ASSERT(iterator__has_been_accessed(&iter->base));
GIT_ASSERT(S_ISDIR(iter->entry->mode));
while (true) {
const git_index_entry *next_entry = NULL;
if (++iter->next_idx >= iter->entries.length)
return GIT_ITEROVER;
next_entry = iter->entries.contents[iter->next_idx];
if (iter->base.strncomp(iter->tree_buf.ptr, next_entry->path,
iter->tree_buf.size) != 0)
break;
}
iter->skip_tree = false;
return 0;
}
static int index_iterator_advance(
const git_index_entry **out, git_iterator *i)
{
index_iterator *iter = GIT_CONTAINER_OF(i, index_iterator, base);
const git_index_entry *entry = NULL;
bool is_submodule;
int error = 0;
iter->base.flags |= GIT_ITERATOR_FIRST_ACCESS;
while (true) {
if (iter->next_idx >= iter->entries.length) {
error = GIT_ITEROVER;
break;
}
/* we were not asked to expand this pseudotree. advance over it. */
if (iter->skip_tree) {
index_iterator_skip_pseudotree(iter);
continue;
}
entry = iter->entries.contents[iter->next_idx];
is_submodule = S_ISGITLINK(entry->mode);
if (!iterator_has_started(&iter->base, entry->path, is_submodule)) {
iter->next_idx++;
continue;
}
if (iterator_has_ended(&iter->base, entry->path)) {
error = GIT_ITEROVER;
break;
}
/* if we have a list of paths we're interested in, examine it */
if (!iterator_pathlist_next_is(&iter->base, entry->path)) {
iter->next_idx++;
continue;
}
/* if this is a conflict, skip it unless we're including conflicts */
if (git_index_entry_is_conflict(entry) &&
!iterator__include_conflicts(&iter->base)) {
iter->next_idx++;
continue;
}
/* we've found what will be our next _file_ entry. but if we are
* returning trees entries, we may need to return a pseudotree
* entry that will contain this. don't advance over this entry,
* though, we still need to return it on the next `advance`.
*/
if (iterator__include_trees(&iter->base) &&
index_iterator_create_pseudotree(&entry, iter, entry->path)) {
/* Note whether this pseudo tree should be expanded or not */
iter->skip_tree = iterator__dont_autoexpand(&iter->base);
break;
}
iter->next_idx++;
break;
}
iter->entry = (error == 0) ? entry : NULL;
if (out)
*out = iter->entry;
return error;
}
static int index_iterator_advance_into(
const git_index_entry **out, git_iterator *i)
{
index_iterator *iter = GIT_CONTAINER_OF(i, index_iterator, base);
if (! S_ISDIR(iter->tree_entry.mode)) {
if (out)
*out = NULL;
return 0;
}
iter->skip_tree = false;
return index_iterator_advance(out, i);
}
static int index_iterator_advance_over(
const git_index_entry **out,
git_iterator_status_t *status,
git_iterator *i)
{
index_iterator *iter = GIT_CONTAINER_OF(i, index_iterator, base);
const git_index_entry *entry;
int error;
if ((error = index_iterator_current(&entry, i)) < 0)
return error;
if (S_ISDIR(entry->mode))
index_iterator_skip_pseudotree(iter);
*status = GIT_ITERATOR_STATUS_NORMAL;
return index_iterator_advance(out, i);
}
static void index_iterator_clear(index_iterator *iter)
{
iterator_clear(&iter->base);
}
static int index_iterator_init(index_iterator *iter)
{
iter->base.flags &= ~GIT_ITERATOR_FIRST_ACCESS;
iter->next_idx = 0;
iter->skip_tree = false;
return 0;
}
static int index_iterator_reset(git_iterator *i)
{
index_iterator *iter = GIT_CONTAINER_OF(i, index_iterator, base);
index_iterator_clear(iter);
return index_iterator_init(iter);
}
static void index_iterator_free(git_iterator *i)
{
index_iterator *iter = GIT_CONTAINER_OF(i, index_iterator, base);
git_index_snapshot_release(&iter->entries, iter->base.index);
git_buf_dispose(&iter->tree_buf);
}
int git_iterator_for_index(
git_iterator **out,
git_repository *repo,
git_index *index,
git_iterator_options *options)
{
index_iterator *iter;
int error;
static git_iterator_callbacks callbacks = {
index_iterator_current,
index_iterator_advance,
index_iterator_advance_into,
index_iterator_advance_over,
index_iterator_reset,
index_iterator_free
};
*out = NULL;
if (index == NULL)
return git_iterator_for_nothing(out, options);
iter = git__calloc(1, sizeof(index_iterator));
GIT_ERROR_CHECK_ALLOC(iter);
iter->base.type = GIT_ITERATOR_INDEX;
iter->base.cb = &callbacks;
if ((error = iterator_init_common(&iter->base, repo, index, options)) < 0 ||
(error = git_index_snapshot_new(&iter->entries, index)) < 0 ||
(error = index_iterator_init(iter)) < 0)
goto on_error;
git_vector_set_cmp(&iter->entries, iterator__ignore_case(&iter->base) ?
git_index_entry_icmp : git_index_entry_cmp);
git_vector_sort(&iter->entries);
*out = &iter->base;
return 0;
on_error:
git_iterator_free(&iter->base);
return error;
}
/* Iterator API */
int git_iterator_reset_range(
git_iterator *i, const char *start, const char *end)
{
if (iterator_reset_range(i, start, end) < 0)
return -1;
return i->cb->reset(i);
}
int git_iterator_set_ignore_case(git_iterator *i, bool ignore_case)
{
GIT_ASSERT(!iterator__has_been_accessed(i));
iterator_set_ignore_case(i, ignore_case);
return 0;
}
void git_iterator_free(git_iterator *iter)
{
if (iter == NULL)
return;
iter->cb->free(iter);
git_vector_free(&iter->pathlist);
git__free(iter->start);
git__free(iter->end);
memset(iter, 0, sizeof(*iter));
git__free(iter);
}
int git_iterator_foreach(
git_iterator *iterator,
git_iterator_foreach_cb cb,
void *data)
{
const git_index_entry *iterator_item;
int error = 0;
if ((error = git_iterator_current(&iterator_item, iterator)) < 0)
goto done;
if ((error = cb(iterator_item, data)) != 0)
goto done;
while (true) {
if ((error = git_iterator_advance(&iterator_item, iterator)) < 0)
goto done;
if ((error = cb(iterator_item, data)) != 0)
goto done;
}
done:
if (error == GIT_ITEROVER)
error = 0;
return error;
}
int git_iterator_walk(
git_iterator **iterators,
size_t cnt,
git_iterator_walk_cb cb,
void *data)
{
const git_index_entry **iterator_item; /* next in each iterator */
const git_index_entry **cur_items; /* current path in each iter */
const git_index_entry *first_match;
size_t i, j;
int error = 0;
iterator_item = git__calloc(cnt, sizeof(git_index_entry *));
cur_items = git__calloc(cnt, sizeof(git_index_entry *));
GIT_ERROR_CHECK_ALLOC(iterator_item);
GIT_ERROR_CHECK_ALLOC(cur_items);
/* Set up the iterators */
for (i = 0; i < cnt; i++) {
error = git_iterator_current(&iterator_item[i], iterators[i]);
if (error < 0 && error != GIT_ITEROVER)
goto done;
}
while (true) {
for (i = 0; i < cnt; i++)
cur_items[i] = NULL;
first_match = NULL;
/* Find the next path(s) to consume from each iterator */
for (i = 0; i < cnt; i++) {
if (iterator_item[i] == NULL)
continue;
if (first_match == NULL) {
first_match = iterator_item[i];
cur_items[i] = iterator_item[i];
} else {
int path_diff = git_index_entry_cmp(iterator_item[i], first_match);
if (path_diff < 0) {
/* Found an index entry that sorts before the one we're
* looking at. Forget that we've seen the other and
* look at the other iterators for this path.
*/
for (j = 0; j < i; j++)
cur_items[j] = NULL;
first_match = iterator_item[i];
cur_items[i] = iterator_item[i];
} else if (path_diff == 0) {
cur_items[i] = iterator_item[i];
}
}
}
if (first_match == NULL)
break;
if ((error = cb(cur_items, data)) != 0)
goto done;
/* Advance each iterator that participated */
for (i = 0; i < cnt; i++) {
if (cur_items[i] == NULL)
continue;
error = git_iterator_advance(&iterator_item[i], iterators[i]);
if (error < 0 && error != GIT_ITEROVER)
goto done;
}
}
done:
git__free((git_index_entry **)iterator_item);
git__free((git_index_entry **)cur_items);
if (error == GIT_ITEROVER)
error = 0;
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/mailmap.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 "mailmap.h"
#include "common.h"
#include "path.h"
#include "repository.h"
#include "signature.h"
#include "git2/config.h"
#include "git2/revparse.h"
#include "blob.h"
#include "parse.h"
#define MM_FILE ".mailmap"
#define MM_FILE_CONFIG "mailmap.file"
#define MM_BLOB_CONFIG "mailmap.blob"
#define MM_BLOB_DEFAULT "HEAD:" MM_FILE
static void mailmap_entry_free(git_mailmap_entry *entry)
{
if (!entry)
return;
git__free(entry->real_name);
git__free(entry->real_email);
git__free(entry->replace_name);
git__free(entry->replace_email);
git__free(entry);
}
/*
* First we sort by replace_email, then replace_name (if present).
* Entries with names are greater than entries without.
*/
static int mailmap_entry_cmp(const void *a_raw, const void *b_raw)
{
const git_mailmap_entry *a = (const git_mailmap_entry *)a_raw;
const git_mailmap_entry *b = (const git_mailmap_entry *)b_raw;
int cmp;
GIT_ASSERT_ARG(a && a->replace_email);
GIT_ASSERT_ARG(b && b->replace_email);
cmp = git__strcmp(a->replace_email, b->replace_email);
if (cmp)
return cmp;
/* NULL replace_names are less than not-NULL ones */
if (a->replace_name == NULL || b->replace_name == NULL)
return (int)(a->replace_name != NULL) - (int)(b->replace_name != NULL);
return git__strcmp(a->replace_name, b->replace_name);
}
/* Replace the old entry with the new on duplicate. */
static int mailmap_entry_replace(void **old_raw, void *new_raw)
{
mailmap_entry_free((git_mailmap_entry *)*old_raw);
*old_raw = new_raw;
return GIT_EEXISTS;
}
/* Check if we're at the end of line, w/ comments */
static bool is_eol(git_parse_ctx *ctx)
{
char c;
return git_parse_peek(&c, ctx, GIT_PARSE_PEEK_SKIP_WHITESPACE) < 0 || c == '#';
}
static int advance_until(
const char **start, size_t *len, git_parse_ctx *ctx, char needle)
{
*start = ctx->line;
while (ctx->line_len > 0 && *ctx->line != '#' && *ctx->line != needle)
git_parse_advance_chars(ctx, 1);
if (ctx->line_len == 0 || *ctx->line == '#')
return -1; /* end of line */
*len = ctx->line - *start;
git_parse_advance_chars(ctx, 1); /* advance past needle */
return 0;
}
/*
* Parse a single entry from a mailmap file.
*
* The output git_bufs will be non-owning, and should be copied before being
* persisted.
*/
static int parse_mailmap_entry(
git_buf *real_name, git_buf *real_email,
git_buf *replace_name, git_buf *replace_email,
git_parse_ctx *ctx)
{
const char *start;
size_t len;
git_buf_clear(real_name);
git_buf_clear(real_email);
git_buf_clear(replace_name);
git_buf_clear(replace_email);
git_parse_advance_ws(ctx);
if (is_eol(ctx))
return -1; /* blank line */
/* Parse the real name */
if (advance_until(&start, &len, ctx, '<') < 0)
return -1;
git_buf_attach_notowned(real_name, start, len);
git_buf_rtrim(real_name);
/*
* If this is the last email in the line, this is the email to replace,
* otherwise, it's the real email.
*/
if (advance_until(&start, &len, ctx, '>') < 0)
return -1;
/* If we aren't at the end of the line, parse a second name and email */
if (!is_eol(ctx)) {
git_buf_attach_notowned(real_email, start, len);
git_parse_advance_ws(ctx);
if (advance_until(&start, &len, ctx, '<') < 0)
return -1;
git_buf_attach_notowned(replace_name, start, len);
git_buf_rtrim(replace_name);
if (advance_until(&start, &len, ctx, '>') < 0)
return -1;
}
git_buf_attach_notowned(replace_email, start, len);
if (!is_eol(ctx))
return -1;
return 0;
}
int git_mailmap_new(git_mailmap **out)
{
int error;
git_mailmap *mm = git__calloc(1, sizeof(git_mailmap));
GIT_ERROR_CHECK_ALLOC(mm);
error = git_vector_init(&mm->entries, 0, mailmap_entry_cmp);
if (error < 0) {
git__free(mm);
return error;
}
*out = mm;
return 0;
}
void git_mailmap_free(git_mailmap *mm)
{
size_t idx;
git_mailmap_entry *entry;
if (!mm)
return;
git_vector_foreach(&mm->entries, idx, entry)
mailmap_entry_free(entry);
git_vector_free(&mm->entries);
git__free(mm);
}
static int mailmap_add_entry_unterminated(
git_mailmap *mm,
const char *real_name, size_t real_name_size,
const char *real_email, size_t real_email_size,
const char *replace_name, size_t replace_name_size,
const char *replace_email, size_t replace_email_size)
{
int error;
git_mailmap_entry *entry = git__calloc(1, sizeof(git_mailmap_entry));
GIT_ERROR_CHECK_ALLOC(entry);
GIT_ASSERT_ARG(mm);
GIT_ASSERT_ARG(replace_email && *replace_email);
if (real_name_size > 0) {
entry->real_name = git__substrdup(real_name, real_name_size);
GIT_ERROR_CHECK_ALLOC(entry->real_name);
}
if (real_email_size > 0) {
entry->real_email = git__substrdup(real_email, real_email_size);
GIT_ERROR_CHECK_ALLOC(entry->real_email);
}
if (replace_name_size > 0) {
entry->replace_name = git__substrdup(replace_name, replace_name_size);
GIT_ERROR_CHECK_ALLOC(entry->replace_name);
}
entry->replace_email = git__substrdup(replace_email, replace_email_size);
GIT_ERROR_CHECK_ALLOC(entry->replace_email);
error = git_vector_insert_sorted(&mm->entries, entry, mailmap_entry_replace);
if (error == GIT_EEXISTS)
error = GIT_OK;
else if (error < 0)
mailmap_entry_free(entry);
return error;
}
int git_mailmap_add_entry(
git_mailmap *mm, const char *real_name, const char *real_email,
const char *replace_name, const char *replace_email)
{
return mailmap_add_entry_unterminated(
mm,
real_name, real_name ? strlen(real_name) : 0,
real_email, real_email ? strlen(real_email) : 0,
replace_name, replace_name ? strlen(replace_name) : 0,
replace_email, strlen(replace_email));
}
static int mailmap_add_buffer(git_mailmap *mm, const char *buf, size_t len)
{
int error = 0;
git_parse_ctx ctx;
/* Scratch buffers containing the real parsed names & emails */
git_buf real_name = GIT_BUF_INIT;
git_buf real_email = GIT_BUF_INIT;
git_buf replace_name = GIT_BUF_INIT;
git_buf replace_email = GIT_BUF_INIT;
/* Buffers may not contain '\0's. */
if (memchr(buf, '\0', len) != NULL)
return -1;
git_parse_ctx_init(&ctx, buf, len);
/* Run the parser */
while (ctx.remain_len > 0) {
error = parse_mailmap_entry(
&real_name, &real_email, &replace_name, &replace_email, &ctx);
if (error < 0) {
error = 0; /* Skip lines which don't contain a valid entry */
git_parse_advance_line(&ctx);
continue; /* TODO: warn */
}
/* NOTE: Can't use add_entry(...) as our buffers aren't terminated */
error = mailmap_add_entry_unterminated(
mm, real_name.ptr, real_name.size, real_email.ptr, real_email.size,
replace_name.ptr, replace_name.size, replace_email.ptr, replace_email.size);
if (error < 0)
goto cleanup;
error = 0;
}
cleanup:
git_buf_dispose(&real_name);
git_buf_dispose(&real_email);
git_buf_dispose(&replace_name);
git_buf_dispose(&replace_email);
return error;
}
int git_mailmap_from_buffer(git_mailmap **out, const char *data, size_t len)
{
int error = git_mailmap_new(out);
if (error < 0)
return error;
error = mailmap_add_buffer(*out, data, len);
if (error < 0) {
git_mailmap_free(*out);
*out = NULL;
}
return error;
}
static int mailmap_add_blob(
git_mailmap *mm, git_repository *repo, const char *rev)
{
git_object *object = NULL;
git_blob *blob = NULL;
git_buf content = GIT_BUF_INIT;
int error;
GIT_ASSERT_ARG(mm);
GIT_ASSERT_ARG(repo);
error = git_revparse_single(&object, repo, rev);
if (error < 0)
goto cleanup;
error = git_object_peel((git_object **)&blob, object, GIT_OBJECT_BLOB);
if (error < 0)
goto cleanup;
error = git_blob__getbuf(&content, blob);
if (error < 0)
goto cleanup;
error = mailmap_add_buffer(mm, content.ptr, content.size);
if (error < 0)
goto cleanup;
cleanup:
git_buf_dispose(&content);
git_blob_free(blob);
git_object_free(object);
return error;
}
static int mailmap_add_file_ondisk(
git_mailmap *mm, const char *path, git_repository *repo)
{
const char *base = repo ? git_repository_workdir(repo) : NULL;
git_buf fullpath = GIT_BUF_INIT;
git_buf content = GIT_BUF_INIT;
int error;
error = git_path_join_unrooted(&fullpath, path, base, NULL);
if (error < 0)
goto cleanup;
error = git_path_validate_workdir_buf(repo, &fullpath);
if (error < 0)
goto cleanup;
error = git_futils_readbuffer(&content, fullpath.ptr);
if (error < 0)
goto cleanup;
error = mailmap_add_buffer(mm, content.ptr, content.size);
if (error < 0)
goto cleanup;
cleanup:
git_buf_dispose(&fullpath);
git_buf_dispose(&content);
return error;
}
/* NOTE: Only expose with an error return, currently never errors */
static void mailmap_add_from_repository(git_mailmap *mm, git_repository *repo)
{
git_config *config = NULL;
git_buf rev_buf = GIT_BUF_INIT;
git_buf path_buf = GIT_BUF_INIT;
const char *rev = NULL;
const char *path = NULL;
/* If we're in a bare repo, default blob to 'HEAD:.mailmap' */
if (repo->is_bare)
rev = MM_BLOB_DEFAULT;
/* Try to load 'mailmap.file' and 'mailmap.blob' cfgs from the repo */
if (git_repository_config(&config, repo) == 0) {
if (git_config_get_string_buf(&rev_buf, config, MM_BLOB_CONFIG) == 0)
rev = rev_buf.ptr;
if (git_config_get_path(&path_buf, config, MM_FILE_CONFIG) == 0)
path = path_buf.ptr;
}
/*
* Load mailmap files in order, overriding previous entries with new ones.
* 1. The '.mailmap' file in the repository's workdir root,
* 2. The blob described by the 'mailmap.blob' config (default HEAD:.mailmap),
* 3. The file described by the 'mailmap.file' config.
*
* We ignore errors from these loads, as these files may not exist, or may
* contain invalid information, and we don't want to report that error.
*
* XXX: Warn?
*/
if (!repo->is_bare)
mailmap_add_file_ondisk(mm, MM_FILE, repo);
if (rev != NULL)
mailmap_add_blob(mm, repo, rev);
if (path != NULL)
mailmap_add_file_ondisk(mm, path, repo);
git_buf_dispose(&rev_buf);
git_buf_dispose(&path_buf);
git_config_free(config);
}
int git_mailmap_from_repository(git_mailmap **out, git_repository *repo)
{
int error;
GIT_ASSERT_ARG(out);
GIT_ASSERT_ARG(repo);
if ((error = git_mailmap_new(out)) < 0)
return error;
mailmap_add_from_repository(*out, repo);
return 0;
}
const git_mailmap_entry *git_mailmap_entry_lookup(
const git_mailmap *mm, const char *name, const char *email)
{
int error;
ssize_t fallback = -1;
size_t idx;
git_mailmap_entry *entry;
/* The lookup needle we want to use only sets the replace_email. */
git_mailmap_entry needle = { NULL };
needle.replace_email = (char *)email;
GIT_ASSERT_ARG_WITH_RETVAL(email, NULL);
if (!mm)
return NULL;
/*
* We want to find the place to start looking. so we do a binary search for
* the "fallback" nameless entry. If we find it, we advance past it and record
* the index.
*/
error = git_vector_bsearch(&idx, (git_vector *)&mm->entries, &needle);
if (error >= 0)
fallback = idx++;
else if (error != GIT_ENOTFOUND)
return NULL;
/* do a linear search for an exact match */
for (; idx < git_vector_length(&mm->entries); ++idx) {
entry = git_vector_get(&mm->entries, idx);
if (git__strcmp(entry->replace_email, email))
break; /* it's a different email, so we're done looking */
/* should be specific */
GIT_ASSERT_WITH_RETVAL(entry->replace_name, NULL);
if (!name || !git__strcmp(entry->replace_name, name))
return entry;
}
if (fallback < 0)
return NULL; /* no fallback */
return git_vector_get(&mm->entries, fallback);
}
int git_mailmap_resolve(
const char **real_name, const char **real_email,
const git_mailmap *mailmap,
const char *name, const char *email)
{
const git_mailmap_entry *entry = NULL;
GIT_ASSERT(name);
GIT_ASSERT(email);
*real_name = name;
*real_email = email;
if ((entry = git_mailmap_entry_lookup(mailmap, name, email))) {
if (entry->real_name)
*real_name = entry->real_name;
if (entry->real_email)
*real_email = entry->real_email;
}
return 0;
}
int git_mailmap_resolve_signature(
git_signature **out, const git_mailmap *mailmap, const git_signature *sig)
{
const char *name = NULL;
const char *email = NULL;
int error;
if (!sig)
return 0;
error = git_mailmap_resolve(&name, &email, mailmap, sig->name, sig->email);
if (error < 0)
return error;
error = git_signature_new(out, name, email, sig->when.time, sig->when.offset);
if (error < 0)
return error;
/* Copy over the sign, as git_signature_new doesn't let you pass it. */
(*out)->when.sign = sig->when.sign;
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/commit_graph.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 "commit_graph.h"
#include "array.h"
#include "filebuf.h"
#include "futils.h"
#include "hash.h"
#include "oidarray.h"
#include "oidmap.h"
#include "pack.h"
#include "repository.h"
#include "revwalk.h"
#define GIT_COMMIT_GRAPH_MISSING_PARENT 0x70000000
#define GIT_COMMIT_GRAPH_GENERATION_NUMBER_MAX 0x3FFFFFFF
#define GIT_COMMIT_GRAPH_GENERATION_NUMBER_INFINITY 0xFFFFFFFF
#define COMMIT_GRAPH_SIGNATURE 0x43475048 /* "CGPH" */
#define COMMIT_GRAPH_VERSION 1
#define COMMIT_GRAPH_OBJECT_ID_VERSION 1
struct git_commit_graph_header {
uint32_t signature;
uint8_t version;
uint8_t object_id_version;
uint8_t chunks;
uint8_t base_graph_files;
};
#define COMMIT_GRAPH_OID_FANOUT_ID 0x4f494446 /* "OIDF" */
#define COMMIT_GRAPH_OID_LOOKUP_ID 0x4f49444c /* "OIDL" */
#define COMMIT_GRAPH_COMMIT_DATA_ID 0x43444154 /* "CDAT" */
#define COMMIT_GRAPH_EXTRA_EDGE_LIST_ID 0x45444745 /* "EDGE" */
#define COMMIT_GRAPH_BLOOM_FILTER_INDEX_ID 0x42494458 /* "BIDX" */
#define COMMIT_GRAPH_BLOOM_FILTER_DATA_ID 0x42444154 /* "BDAT" */
struct git_commit_graph_chunk {
off64_t offset;
size_t length;
};
typedef git_array_t(size_t) parent_index_array_t;
struct packed_commit {
size_t index;
git_oid sha1;
git_oid tree_oid;
uint32_t generation;
git_time_t commit_time;
git_array_oid_t parents;
parent_index_array_t parent_indices;
};
static void packed_commit_free(struct packed_commit *p)
{
if (!p)
return;
git_array_clear(p->parents);
git_array_clear(p->parent_indices);
git__free(p);
}
static struct packed_commit *packed_commit_new(git_commit *commit)
{
unsigned int i, parentcount = git_commit_parentcount(commit);
struct packed_commit *p = git__calloc(1, sizeof(struct packed_commit));
if (!p)
goto cleanup;
git_array_init_to_size(p->parents, parentcount);
if (parentcount && !p->parents.ptr)
goto cleanup;
if (git_oid_cpy(&p->sha1, git_commit_id(commit)) < 0)
goto cleanup;
if (git_oid_cpy(&p->tree_oid, git_commit_tree_id(commit)) < 0)
goto cleanup;
p->commit_time = git_commit_time(commit);
for (i = 0; i < parentcount; ++i) {
git_oid *parent_id = git_array_alloc(p->parents);
if (!parent_id)
goto cleanup;
if (git_oid_cpy(parent_id, git_commit_parent_id(commit, i)) < 0)
goto cleanup;
}
return p;
cleanup:
packed_commit_free(p);
return NULL;
}
typedef int (*commit_graph_write_cb)(const char *buf, size_t size, void *cb_data);
static int commit_graph_error(const char *message)
{
git_error_set(GIT_ERROR_ODB, "invalid commit-graph file - %s", message);
return -1;
}
static int commit_graph_parse_oid_fanout(
git_commit_graph_file *file,
const unsigned char *data,
struct git_commit_graph_chunk *chunk_oid_fanout)
{
uint32_t i, nr;
if (chunk_oid_fanout->offset == 0)
return commit_graph_error("missing OID Fanout chunk");
if (chunk_oid_fanout->length == 0)
return commit_graph_error("empty OID Fanout chunk");
if (chunk_oid_fanout->length != 256 * 4)
return commit_graph_error("OID Fanout chunk has wrong length");
file->oid_fanout = (const uint32_t *)(data + chunk_oid_fanout->offset);
nr = 0;
for (i = 0; i < 256; ++i) {
uint32_t n = ntohl(file->oid_fanout[i]);
if (n < nr)
return commit_graph_error("index is non-monotonic");
nr = n;
}
file->num_commits = nr;
return 0;
}
static int commit_graph_parse_oid_lookup(
git_commit_graph_file *file,
const unsigned char *data,
struct git_commit_graph_chunk *chunk_oid_lookup)
{
uint32_t i;
git_oid *oid, *prev_oid, zero_oid = {{0}};
if (chunk_oid_lookup->offset == 0)
return commit_graph_error("missing OID Lookup chunk");
if (chunk_oid_lookup->length == 0)
return commit_graph_error("empty OID Lookup chunk");
if (chunk_oid_lookup->length != file->num_commits * GIT_OID_RAWSZ)
return commit_graph_error("OID Lookup chunk has wrong length");
file->oid_lookup = oid = (git_oid *)(data + chunk_oid_lookup->offset);
prev_oid = &zero_oid;
for (i = 0; i < file->num_commits; ++i, ++oid) {
if (git_oid_cmp(prev_oid, oid) >= 0)
return commit_graph_error("OID Lookup index is non-monotonic");
prev_oid = oid;
}
return 0;
}
static int commit_graph_parse_commit_data(
git_commit_graph_file *file,
const unsigned char *data,
struct git_commit_graph_chunk *chunk_commit_data)
{
if (chunk_commit_data->offset == 0)
return commit_graph_error("missing Commit Data chunk");
if (chunk_commit_data->length == 0)
return commit_graph_error("empty Commit Data chunk");
if (chunk_commit_data->length != file->num_commits * (GIT_OID_RAWSZ + 16))
return commit_graph_error("Commit Data chunk has wrong length");
file->commit_data = data + chunk_commit_data->offset;
return 0;
}
static int commit_graph_parse_extra_edge_list(
git_commit_graph_file *file,
const unsigned char *data,
struct git_commit_graph_chunk *chunk_extra_edge_list)
{
if (chunk_extra_edge_list->length == 0)
return 0;
if (chunk_extra_edge_list->length % 4 != 0)
return commit_graph_error("malformed Extra Edge List chunk");
file->extra_edge_list = data + chunk_extra_edge_list->offset;
file->num_extra_edge_list = chunk_extra_edge_list->length / 4;
return 0;
}
int git_commit_graph_file_parse(
git_commit_graph_file *file,
const unsigned char *data,
size_t size)
{
struct git_commit_graph_header *hdr;
const unsigned char *chunk_hdr;
struct git_commit_graph_chunk *last_chunk;
uint32_t i;
off64_t last_chunk_offset, chunk_offset, trailer_offset;
git_oid cgraph_checksum = {{0}};
int error;
struct git_commit_graph_chunk chunk_oid_fanout = {0}, chunk_oid_lookup = {0},
chunk_commit_data = {0}, chunk_extra_edge_list = {0},
chunk_unsupported = {0};
GIT_ASSERT_ARG(file);
if (size < sizeof(struct git_commit_graph_header) + GIT_OID_RAWSZ)
return commit_graph_error("commit-graph is too short");
hdr = ((struct git_commit_graph_header *)data);
if (hdr->signature != htonl(COMMIT_GRAPH_SIGNATURE) || hdr->version != COMMIT_GRAPH_VERSION
|| hdr->object_id_version != COMMIT_GRAPH_OBJECT_ID_VERSION) {
return commit_graph_error("unsupported commit-graph version");
}
if (hdr->chunks == 0)
return commit_graph_error("no chunks in commit-graph");
/*
* The very first chunk's offset should be after the header, all the chunk
* headers, and a special zero chunk.
*/
last_chunk_offset = sizeof(struct git_commit_graph_header) + (1 + hdr->chunks) * 12;
trailer_offset = size - GIT_OID_RAWSZ;
if (trailer_offset < last_chunk_offset)
return commit_graph_error("wrong commit-graph size");
git_oid_cpy(&file->checksum, (git_oid *)(data + trailer_offset));
if (git_hash_buf(&cgraph_checksum, data, (size_t)trailer_offset) < 0)
return commit_graph_error("could not calculate signature");
if (!git_oid_equal(&cgraph_checksum, &file->checksum))
return commit_graph_error("index signature mismatch");
chunk_hdr = data + sizeof(struct git_commit_graph_header);
last_chunk = NULL;
for (i = 0; i < hdr->chunks; ++i, chunk_hdr += 12) {
chunk_offset = ((off64_t)ntohl(*((uint32_t *)(chunk_hdr + 4)))) << 32
| ((off64_t)ntohl(*((uint32_t *)(chunk_hdr + 8))));
if (chunk_offset < last_chunk_offset)
return commit_graph_error("chunks are non-monotonic");
if (chunk_offset >= trailer_offset)
return commit_graph_error("chunks extend beyond the trailer");
if (last_chunk != NULL)
last_chunk->length = (size_t)(chunk_offset - last_chunk_offset);
last_chunk_offset = chunk_offset;
switch (ntohl(*((uint32_t *)(chunk_hdr + 0)))) {
case COMMIT_GRAPH_OID_FANOUT_ID:
chunk_oid_fanout.offset = last_chunk_offset;
last_chunk = &chunk_oid_fanout;
break;
case COMMIT_GRAPH_OID_LOOKUP_ID:
chunk_oid_lookup.offset = last_chunk_offset;
last_chunk = &chunk_oid_lookup;
break;
case COMMIT_GRAPH_COMMIT_DATA_ID:
chunk_commit_data.offset = last_chunk_offset;
last_chunk = &chunk_commit_data;
break;
case COMMIT_GRAPH_EXTRA_EDGE_LIST_ID:
chunk_extra_edge_list.offset = last_chunk_offset;
last_chunk = &chunk_extra_edge_list;
break;
case COMMIT_GRAPH_BLOOM_FILTER_INDEX_ID:
case COMMIT_GRAPH_BLOOM_FILTER_DATA_ID:
chunk_unsupported.offset = last_chunk_offset;
last_chunk = &chunk_unsupported;
break;
default:
return commit_graph_error("unrecognized chunk ID");
}
}
last_chunk->length = (size_t)(trailer_offset - last_chunk_offset);
error = commit_graph_parse_oid_fanout(file, data, &chunk_oid_fanout);
if (error < 0)
return error;
error = commit_graph_parse_oid_lookup(file, data, &chunk_oid_lookup);
if (error < 0)
return error;
error = commit_graph_parse_commit_data(file, data, &chunk_commit_data);
if (error < 0)
return error;
error = commit_graph_parse_extra_edge_list(file, data, &chunk_extra_edge_list);
if (error < 0)
return error;
return 0;
}
int git_commit_graph_new(git_commit_graph **cgraph_out, const char *objects_dir, bool open_file)
{
git_commit_graph *cgraph = NULL;
int error = 0;
GIT_ASSERT_ARG(cgraph_out);
GIT_ASSERT_ARG(objects_dir);
cgraph = git__calloc(1, sizeof(git_commit_graph));
GIT_ERROR_CHECK_ALLOC(cgraph);
error = git_buf_joinpath(&cgraph->filename, objects_dir, "info/commit-graph");
if (error < 0)
goto error;
if (open_file) {
error = git_commit_graph_file_open(&cgraph->file, git_buf_cstr(&cgraph->filename));
if (error < 0)
goto error;
cgraph->checked = 1;
}
*cgraph_out = cgraph;
return 0;
error:
git_commit_graph_free(cgraph);
return error;
}
int git_commit_graph_open(git_commit_graph **cgraph_out, const char *objects_dir)
{
return git_commit_graph_new(cgraph_out, objects_dir, true);
}
int git_commit_graph_file_open(git_commit_graph_file **file_out, const char *path)
{
git_commit_graph_file *file;
git_file fd = -1;
size_t cgraph_size;
struct stat st;
int error;
/* TODO: properly open the file without access time using O_NOATIME */
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_ODB, "commit-graph file not found - '%s'", path);
return GIT_ENOTFOUND;
}
if (!S_ISREG(st.st_mode) || !git__is_sizet(st.st_size)) {
p_close(fd);
git_error_set(GIT_ERROR_ODB, "invalid pack index '%s'", path);
return GIT_ENOTFOUND;
}
cgraph_size = (size_t)st.st_size;
file = git__calloc(1, sizeof(git_commit_graph_file));
GIT_ERROR_CHECK_ALLOC(file);
error = git_futils_mmap_ro(&file->graph_map, fd, 0, cgraph_size);
p_close(fd);
if (error < 0) {
git_commit_graph_file_free(file);
return error;
}
if ((error = git_commit_graph_file_parse(file, file->graph_map.data, cgraph_size)) < 0) {
git_commit_graph_file_free(file);
return error;
}
*file_out = file;
return 0;
}
int git_commit_graph_get_file(git_commit_graph_file **file_out, git_commit_graph *cgraph)
{
if (!cgraph->checked) {
int error = 0;
git_commit_graph_file *result = NULL;
/* We only check once, no matter the result. */
cgraph->checked = 1;
/* Best effort */
error = git_commit_graph_file_open(&result, git_buf_cstr(&cgraph->filename));
if (error < 0)
return error;
cgraph->file = result;
}
if (!cgraph->file)
return GIT_ENOTFOUND;
*file_out = cgraph->file;
return 0;
}
void git_commit_graph_refresh(git_commit_graph *cgraph)
{
if (!cgraph->checked)
return;
if (cgraph->file
&& git_commit_graph_file_needs_refresh(cgraph->file, git_buf_cstr(&cgraph->filename))) {
/* We just free the commit graph. The next time it is requested, it will be
* re-loaded. */
git_commit_graph_file_free(cgraph->file);
cgraph->file = NULL;
}
/* Force a lazy re-check next time it is needed. */
cgraph->checked = 0;
}
static int git_commit_graph_entry_get_byindex(
git_commit_graph_entry *e,
const git_commit_graph_file *file,
size_t pos)
{
const unsigned char *commit_data;
GIT_ASSERT_ARG(e);
GIT_ASSERT_ARG(file);
if (pos >= file->num_commits) {
git_error_set(GIT_ERROR_INVALID, "commit index %zu does not exist", pos);
return GIT_ENOTFOUND;
}
commit_data = file->commit_data + pos * (GIT_OID_RAWSZ + 4 * sizeof(uint32_t));
git_oid_cpy(&e->tree_oid, (const git_oid *)commit_data);
e->parent_indices[0] = ntohl(*((uint32_t *)(commit_data + GIT_OID_RAWSZ)));
e->parent_indices[1] = ntohl(
*((uint32_t *)(commit_data + GIT_OID_RAWSZ + sizeof(uint32_t))));
e->parent_count = (e->parent_indices[0] != GIT_COMMIT_GRAPH_MISSING_PARENT)
+ (e->parent_indices[1] != GIT_COMMIT_GRAPH_MISSING_PARENT);
e->generation = ntohl(*((uint32_t *)(commit_data + GIT_OID_RAWSZ + 2 * sizeof(uint32_t))));
e->commit_time = ntohl(*((uint32_t *)(commit_data + GIT_OID_RAWSZ + 3 * sizeof(uint32_t))));
e->commit_time |= (e->generation & UINT64_C(0x3)) << UINT64_C(32);
e->generation >>= 2u;
if (e->parent_indices[1] & 0x80000000u) {
uint32_t extra_edge_list_pos = e->parent_indices[1] & 0x7fffffff;
/* Make sure we're not being sent out of bounds */
if (extra_edge_list_pos >= file->num_extra_edge_list) {
git_error_set(GIT_ERROR_INVALID,
"commit %u does not exist",
extra_edge_list_pos);
return GIT_ENOTFOUND;
}
e->extra_parents_index = extra_edge_list_pos;
while (extra_edge_list_pos < file->num_extra_edge_list
&& (ntohl(*(
(uint32_t *)(file->extra_edge_list
+ extra_edge_list_pos * sizeof(uint32_t))))
& 0x80000000u)
== 0) {
extra_edge_list_pos++;
e->parent_count++;
}
}
git_oid_cpy(&e->sha1, &file->oid_lookup[pos]);
return 0;
}
bool git_commit_graph_file_needs_refresh(const git_commit_graph_file *file, const char *path)
{
git_file fd = -1;
struct stat st;
ssize_t bytes_read;
git_oid cgraph_checksum = {{0}};
/* TODO: properly open the file without access time using O_NOATIME */
fd = git_futils_open_ro(path);
if (fd < 0)
return true;
if (p_fstat(fd, &st) < 0) {
p_close(fd);
return true;
}
if (!S_ISREG(st.st_mode) || !git__is_sizet(st.st_size)
|| (size_t)st.st_size != file->graph_map.len) {
p_close(fd);
return true;
}
bytes_read = p_pread(fd, cgraph_checksum.id, GIT_OID_RAWSZ, st.st_size - GIT_OID_RAWSZ);
p_close(fd);
if (bytes_read != GIT_OID_RAWSZ)
return true;
return !git_oid_equal(&cgraph_checksum, &file->checksum);
}
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 pos, found = 0;
uint32_t hi, lo;
const git_oid *current = NULL;
GIT_ASSERT_ARG(e);
GIT_ASSERT_ARG(file);
GIT_ASSERT_ARG(short_oid);
hi = ntohl(file->oid_fanout[(int)short_oid->id[0]]);
lo = ((short_oid->id[0] == 0x0) ? 0 : ntohl(file->oid_fanout[(int)short_oid->id[0] - 1]));
pos = git_pack__lookup_sha1(file->oid_lookup, GIT_OID_RAWSZ, lo, hi, short_oid->id);
if (pos >= 0) {
/* An object matching exactly the oid was found */
found = 1;
current = file->oid_lookup + pos;
} else {
/* No object was found */
/* pos refers to the object with the "closest" oid to short_oid */
pos = -1 - pos;
if (pos < (int)file->num_commits) {
current = file->oid_lookup + pos;
if (!git_oid_ncmp(short_oid, current, len))
found = 1;
}
}
if (found && len != GIT_OID_HEXSZ && pos + 1 < (int)file->num_commits) {
/* Check for ambiguousity */
const git_oid *next = current + 1;
if (!git_oid_ncmp(short_oid, next, len)) {
found = 2;
}
}
if (!found)
return git_odb__error_notfound(
"failed to find offset for commit-graph index entry", short_oid, len);
if (found > 1)
return git_odb__error_ambiguous(
"found multiple offsets for commit-graph index entry");
return git_commit_graph_entry_get_byindex(e, file, pos);
}
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)
{
GIT_ASSERT_ARG(parent);
GIT_ASSERT_ARG(file);
if (n >= entry->parent_count) {
git_error_set(GIT_ERROR_INVALID, "parent index %zu does not exist", n);
return GIT_ENOTFOUND;
}
if (n == 0 || (n == 1 && entry->parent_count == 2))
return git_commit_graph_entry_get_byindex(parent, file, entry->parent_indices[n]);
return git_commit_graph_entry_get_byindex(
parent,
file,
ntohl(
*(uint32_t *)(file->extra_edge_list
+ (entry->extra_parents_index + n - 1)
* sizeof(uint32_t)))
& 0x7fffffff);
}
int git_commit_graph_file_close(git_commit_graph_file *file)
{
GIT_ASSERT_ARG(file);
if (file->graph_map.data)
git_futils_mmap_free(&file->graph_map);
return 0;
}
void git_commit_graph_free(git_commit_graph *cgraph)
{
if (!cgraph)
return;
git_buf_dispose(&cgraph->filename);
git_commit_graph_file_free(cgraph->file);
git__free(cgraph);
}
void git_commit_graph_file_free(git_commit_graph_file *file)
{
if (!file)
return;
git_commit_graph_file_close(file);
git__free(file);
}
static int packed_commit__cmp(const void *a_, const void *b_)
{
const struct packed_commit *a = a_;
const struct packed_commit *b = b_;
return git_oid_cmp(&a->sha1, &b->sha1);
}
int git_commit_graph_writer_new(git_commit_graph_writer **out, const char *objects_info_dir)
{
git_commit_graph_writer *w = git__calloc(1, sizeof(git_commit_graph_writer));
GIT_ERROR_CHECK_ALLOC(w);
if (git_buf_sets(&w->objects_info_dir, objects_info_dir) < 0) {
git__free(w);
return -1;
}
if (git_vector_init(&w->commits, 0, packed_commit__cmp) < 0) {
git_buf_dispose(&w->objects_info_dir);
git__free(w);
return -1;
}
*out = w;
return 0;
}
void git_commit_graph_writer_free(git_commit_graph_writer *w)
{
struct packed_commit *packed_commit;
size_t i;
if (!w)
return;
git_vector_foreach (&w->commits, i, packed_commit)
packed_commit_free(packed_commit);
git_vector_free(&w->commits);
git_buf_dispose(&w->objects_info_dir);
git__free(w);
}
struct object_entry_cb_state {
git_repository *repo;
git_odb *db;
git_vector *commits;
};
static int object_entry__cb(const git_oid *id, void *data)
{
struct object_entry_cb_state *state = (struct object_entry_cb_state *)data;
git_commit *commit = NULL;
struct packed_commit *packed_commit = NULL;
size_t header_len;
git_object_t header_type;
int error = 0;
error = git_odb_read_header(&header_len, &header_type, state->db, id);
if (error < 0)
return error;
if (header_type != GIT_OBJECT_COMMIT)
return 0;
error = git_commit_lookup(&commit, state->repo, id);
if (error < 0)
return error;
packed_commit = packed_commit_new(commit);
git_commit_free(commit);
GIT_ERROR_CHECK_ALLOC(packed_commit);
error = git_vector_insert(state->commits, packed_commit);
if (error < 0) {
packed_commit_free(packed_commit);
return error;
}
return 0;
}
int git_commit_graph_writer_add_index_file(
git_commit_graph_writer *w,
git_repository *repo,
const char *idx_path)
{
int error;
struct git_pack_file *p = NULL;
struct object_entry_cb_state state = {0};
state.repo = repo;
state.commits = &w->commits;
error = git_repository_odb(&state.db, repo);
if (error < 0)
goto cleanup;
error = git_mwindow_get_pack(&p, idx_path);
if (error < 0)
goto cleanup;
error = git_pack_foreach_entry(p, object_entry__cb, &state);
if (error < 0)
goto cleanup;
cleanup:
if (p)
git_mwindow_put_pack(p);
git_odb_free(state.db);
return error;
}
int git_commit_graph_writer_add_revwalk(git_commit_graph_writer *w, git_revwalk *walk)
{
int error;
git_oid id;
git_repository *repo = git_revwalk_repository(walk);
git_commit *commit;
struct packed_commit *packed_commit;
while ((git_revwalk_next(&id, walk)) == 0) {
error = git_commit_lookup(&commit, repo, &id);
if (error < 0)
return error;
packed_commit = packed_commit_new(commit);
git_commit_free(commit);
GIT_ERROR_CHECK_ALLOC(packed_commit);
error = git_vector_insert(&w->commits, packed_commit);
if (error < 0) {
packed_commit_free(packed_commit);
return error;
}
}
return 0;
}
enum generation_number_commit_state {
GENERATION_NUMBER_COMMIT_STATE_UNVISITED = 0,
GENERATION_NUMBER_COMMIT_STATE_ADDED = 1,
GENERATION_NUMBER_COMMIT_STATE_EXPANDED = 2,
GENERATION_NUMBER_COMMIT_STATE_VISITED = 3,
};
static int compute_generation_numbers(git_vector *commits)
{
git_array_t(size_t) index_stack = GIT_ARRAY_INIT;
size_t i, j;
size_t *parent_idx;
enum generation_number_commit_state *commit_states = NULL;
struct packed_commit *child_packed_commit;
git_oidmap *packed_commit_map = NULL;
int error = 0;
/* First populate the parent indices fields */
error = git_oidmap_new(&packed_commit_map);
if (error < 0)
goto cleanup;
git_vector_foreach (commits, i, child_packed_commit) {
child_packed_commit->index = i;
error = git_oidmap_set(
packed_commit_map, &child_packed_commit->sha1, child_packed_commit);
if (error < 0)
goto cleanup;
}
git_vector_foreach (commits, i, child_packed_commit) {
size_t parent_i, *parent_idx_ptr;
struct packed_commit *parent_packed_commit;
git_oid *parent_id;
git_array_init_to_size(
child_packed_commit->parent_indices,
git_array_size(child_packed_commit->parents));
if (git_array_size(child_packed_commit->parents)
&& !child_packed_commit->parent_indices.ptr) {
error = -1;
goto cleanup;
}
git_array_foreach (child_packed_commit->parents, parent_i, parent_id) {
parent_packed_commit = git_oidmap_get(packed_commit_map, parent_id);
if (!parent_packed_commit) {
git_error_set(GIT_ERROR_ODB,
"parent commit %s not found in commit graph",
git_oid_tostr_s(parent_id));
error = GIT_ENOTFOUND;
goto cleanup;
}
parent_idx_ptr = git_array_alloc(child_packed_commit->parent_indices);
if (!parent_idx_ptr) {
error = -1;
goto cleanup;
}
*parent_idx_ptr = parent_packed_commit->index;
}
}
/*
* We copy all the commits to the stack and then during visitation,
* each node can be added up to two times to the stack.
*/
git_array_init_to_size(index_stack, 3 * git_vector_length(commits));
if (!index_stack.ptr) {
error = -1;
goto cleanup;
}
commit_states = (enum generation_number_commit_state *)git__calloc(
git_vector_length(commits), sizeof(enum generation_number_commit_state));
if (!commit_states) {
error = -1;
goto cleanup;
}
/*
* Perform a Post-Order traversal so that all parent nodes are fully
* visited before the child node.
*/
git_vector_foreach (commits, i, child_packed_commit)
*(size_t *)git_array_alloc(index_stack) = i;
while (git_array_size(index_stack)) {
size_t *index_ptr = git_array_pop(index_stack);
i = *index_ptr;
child_packed_commit = git_vector_get(commits, i);
if (commit_states[i] == GENERATION_NUMBER_COMMIT_STATE_VISITED) {
/* This commit has already been fully visited. */
continue;
}
if (commit_states[i] == GENERATION_NUMBER_COMMIT_STATE_EXPANDED) {
/* All of the commits parents have been visited. */
child_packed_commit->generation = 0;
git_array_foreach (child_packed_commit->parent_indices, j, parent_idx) {
struct packed_commit *parent = git_vector_get(commits, *parent_idx);
if (child_packed_commit->generation < parent->generation)
child_packed_commit->generation = parent->generation;
}
if (child_packed_commit->generation
< GIT_COMMIT_GRAPH_GENERATION_NUMBER_MAX) {
++child_packed_commit->generation;
}
commit_states[i] = GENERATION_NUMBER_COMMIT_STATE_VISITED;
continue;
}
/*
* This is the first time we see this commit. We need
* to visit all its parents before we can fully visit
* it.
*/
if (git_array_size(child_packed_commit->parent_indices) == 0) {
/*
* Special case: if the commit has no parents, there's
* no need to add it to the stack just to immediately
* remove it.
*/
commit_states[i] = GENERATION_NUMBER_COMMIT_STATE_VISITED;
child_packed_commit->generation = 1;
continue;
}
/*
* Add this current commit again so that it is visited
* again once all its children have been visited.
*/
*(size_t *)git_array_alloc(index_stack) = i;
git_array_foreach (child_packed_commit->parent_indices, j, parent_idx) {
if (commit_states[*parent_idx]
!= GENERATION_NUMBER_COMMIT_STATE_UNVISITED) {
/* This commit has already been considered. */
continue;
}
commit_states[*parent_idx] = GENERATION_NUMBER_COMMIT_STATE_ADDED;
*(size_t *)git_array_alloc(index_stack) = *parent_idx;
}
commit_states[i] = GENERATION_NUMBER_COMMIT_STATE_EXPANDED;
}
cleanup:
git_oidmap_free(packed_commit_map);
git__free(commit_states);
git_array_clear(index_stack);
return error;
}
static int write_offset(off64_t offset, commit_graph_write_cb write_cb, void *cb_data)
{
int error;
uint32_t word;
word = htonl((uint32_t)((offset >> 32) & 0xffffffffu));
error = write_cb((const char *)&word, sizeof(word), cb_data);
if (error < 0)
return error;
word = htonl((uint32_t)((offset >> 0) & 0xffffffffu));
error = write_cb((const char *)&word, sizeof(word), cb_data);
if (error < 0)
return error;
return 0;
}
static int write_chunk_header(
int chunk_id,
off64_t offset,
commit_graph_write_cb write_cb,
void *cb_data)
{
uint32_t word = htonl(chunk_id);
int error = write_cb((const char *)&word, sizeof(word), cb_data);
if (error < 0)
return error;
return write_offset(offset, write_cb, cb_data);
}
static int commit_graph_write_buf(const char *buf, size_t size, void *data)
{
git_buf *b = (git_buf *)data;
return git_buf_put(b, buf, size);
}
struct commit_graph_write_hash_context {
commit_graph_write_cb write_cb;
void *cb_data;
git_hash_ctx *ctx;
};
static int commit_graph_write_hash(const char *buf, size_t size, void *data)
{
struct commit_graph_write_hash_context *ctx = data;
int error;
error = git_hash_update(ctx->ctx, buf, size);
if (error < 0)
return error;
return ctx->write_cb(buf, size, ctx->cb_data);
}
static void packed_commit_free_dup(void *packed_commit)
{
packed_commit_free(packed_commit);
}
static int commit_graph_write(
git_commit_graph_writer *w,
commit_graph_write_cb write_cb,
void *cb_data)
{
int error = 0;
size_t i;
struct packed_commit *packed_commit;
struct git_commit_graph_header hdr = {0};
uint32_t oid_fanout_count;
uint32_t extra_edge_list_count;
uint32_t oid_fanout[256];
off64_t offset;
git_buf oid_lookup = GIT_BUF_INIT, commit_data = GIT_BUF_INIT,
extra_edge_list = GIT_BUF_INIT;
git_oid cgraph_checksum = {{0}};
git_hash_ctx ctx;
struct commit_graph_write_hash_context hash_cb_data = {0};
hdr.signature = htonl(COMMIT_GRAPH_SIGNATURE);
hdr.version = COMMIT_GRAPH_VERSION;
hdr.object_id_version = COMMIT_GRAPH_OBJECT_ID_VERSION;
hdr.chunks = 0;
hdr.base_graph_files = 0;
hash_cb_data.write_cb = write_cb;
hash_cb_data.cb_data = cb_data;
hash_cb_data.ctx = &ctx;
error = git_hash_ctx_init(&ctx);
if (error < 0)
return error;
cb_data = &hash_cb_data;
write_cb = commit_graph_write_hash;
/* Sort the commits. */
git_vector_sort(&w->commits);
git_vector_uniq(&w->commits, packed_commit_free_dup);
error = compute_generation_numbers(&w->commits);
if (error < 0)
goto cleanup;
/* Fill the OID Fanout table. */
oid_fanout_count = 0;
for (i = 0; i < 256; i++) {
while (oid_fanout_count < git_vector_length(&w->commits) &&
(packed_commit = (struct packed_commit *)git_vector_get(&w->commits, oid_fanout_count)) &&
packed_commit->sha1.id[0] <= i)
++oid_fanout_count;
oid_fanout[i] = htonl(oid_fanout_count);
}
/* Fill the OID Lookup table. */
git_vector_foreach (&w->commits, i, packed_commit) {
error = git_buf_put(&oid_lookup,
(const char *)&packed_commit->sha1, sizeof(git_oid));
if (error < 0)
goto cleanup;
}
/* Fill the Commit Data and Extra Edge List tables. */
extra_edge_list_count = 0;
git_vector_foreach (&w->commits, i, packed_commit) {
uint64_t commit_time;
uint32_t generation;
uint32_t word;
size_t *packed_index;
unsigned int parentcount = (unsigned int)git_array_size(packed_commit->parents);
error = git_buf_put(&commit_data,
(const char *)&packed_commit->tree_oid,
sizeof(git_oid));
if (error < 0)
goto cleanup;
if (parentcount == 0) {
word = htonl(GIT_COMMIT_GRAPH_MISSING_PARENT);
} else {
packed_index = git_array_get(packed_commit->parent_indices, 0);
word = htonl((uint32_t)*packed_index);
}
error = git_buf_put(&commit_data, (const char *)&word, sizeof(word));
if (error < 0)
goto cleanup;
if (parentcount < 2) {
word = htonl(GIT_COMMIT_GRAPH_MISSING_PARENT);
} else if (parentcount == 2) {
packed_index = git_array_get(packed_commit->parent_indices, 1);
word = htonl((uint32_t)*packed_index);
} else {
word = htonl(0x80000000u | extra_edge_list_count);
}
error = git_buf_put(&commit_data, (const char *)&word, sizeof(word));
if (error < 0)
goto cleanup;
if (parentcount > 2) {
unsigned int parent_i;
for (parent_i = 1; parent_i < parentcount; ++parent_i) {
packed_index = git_array_get(
packed_commit->parent_indices, parent_i);
word = htonl((uint32_t)(*packed_index | (parent_i + 1 == parentcount ? 0x80000000u : 0)));
error = git_buf_put(&extra_edge_list,
(const char *)&word,
sizeof(word));
if (error < 0)
goto cleanup;
}
extra_edge_list_count += parentcount - 1;
}
generation = packed_commit->generation;
commit_time = (uint64_t)packed_commit->commit_time;
if (generation > GIT_COMMIT_GRAPH_GENERATION_NUMBER_MAX)
generation = GIT_COMMIT_GRAPH_GENERATION_NUMBER_MAX;
word = ntohl((uint32_t)((generation << 2) | ((commit_time >> 32ull) & 0x3ull)));
error = git_buf_put(&commit_data, (const char *)&word, sizeof(word));
if (error < 0)
goto cleanup;
word = ntohl((uint32_t)(commit_time & 0xffffffffull));
error = git_buf_put(&commit_data, (const char *)&word, sizeof(word));
if (error < 0)
goto cleanup;
}
/* Write the header. */
hdr.chunks = 3;
if (git_buf_len(&extra_edge_list) > 0)
hdr.chunks++;
error = write_cb((const char *)&hdr, sizeof(hdr), cb_data);
if (error < 0)
goto cleanup;
/* Write the chunk headers. */
offset = sizeof(hdr) + (hdr.chunks + 1) * 12;
error = write_chunk_header(COMMIT_GRAPH_OID_FANOUT_ID, offset, write_cb, cb_data);
if (error < 0)
goto cleanup;
offset += sizeof(oid_fanout);
error = write_chunk_header(COMMIT_GRAPH_OID_LOOKUP_ID, offset, write_cb, cb_data);
if (error < 0)
goto cleanup;
offset += git_buf_len(&oid_lookup);
error = write_chunk_header(COMMIT_GRAPH_COMMIT_DATA_ID, offset, write_cb, cb_data);
if (error < 0)
goto cleanup;
offset += git_buf_len(&commit_data);
if (git_buf_len(&extra_edge_list) > 0) {
error = write_chunk_header(
COMMIT_GRAPH_EXTRA_EDGE_LIST_ID, offset, write_cb, cb_data);
if (error < 0)
goto cleanup;
offset += git_buf_len(&extra_edge_list);
}
error = write_chunk_header(0, offset, write_cb, cb_data);
if (error < 0)
goto cleanup;
/* Write all the chunks. */
error = write_cb((const char *)oid_fanout, sizeof(oid_fanout), cb_data);
if (error < 0)
goto cleanup;
error = write_cb(git_buf_cstr(&oid_lookup), git_buf_len(&oid_lookup), cb_data);
if (error < 0)
goto cleanup;
error = write_cb(git_buf_cstr(&commit_data), git_buf_len(&commit_data), cb_data);
if (error < 0)
goto cleanup;
error = write_cb(git_buf_cstr(&extra_edge_list), git_buf_len(&extra_edge_list), cb_data);
if (error < 0)
goto cleanup;
/* Finalize the checksum and write the trailer. */
error = git_hash_final(&cgraph_checksum, &ctx);
if (error < 0)
goto cleanup;
error = write_cb((const char *)&cgraph_checksum, sizeof(cgraph_checksum), cb_data);
if (error < 0)
goto cleanup;
cleanup:
git_buf_dispose(&oid_lookup);
git_buf_dispose(&commit_data);
git_buf_dispose(&extra_edge_list);
git_hash_ctx_cleanup(&ctx);
return error;
}
static int commit_graph_write_filebuf(const char *buf, size_t size, void *data)
{
git_filebuf *f = (git_filebuf *)data;
return git_filebuf_write(f, buf, size);
}
int git_commit_graph_writer_options_init(
git_commit_graph_writer_options *opts,
unsigned int version)
{
GIT_INIT_STRUCTURE_FROM_TEMPLATE(
opts,
version,
git_commit_graph_writer_options,
GIT_COMMIT_GRAPH_WRITER_OPTIONS_INIT);
return 0;
}
int git_commit_graph_writer_commit(
git_commit_graph_writer *w,
git_commit_graph_writer_options *opts)
{
int error;
int filebuf_flags = GIT_FILEBUF_DO_NOT_BUFFER;
git_buf commit_graph_path = GIT_BUF_INIT;
git_filebuf output = GIT_FILEBUF_INIT;
/* TODO: support options and fill in defaults. */
GIT_UNUSED(opts);
error = git_buf_joinpath(
&commit_graph_path, git_buf_cstr(&w->objects_info_dir), "commit-graph");
if (error < 0)
return error;
if (git_repository__fsync_gitdir)
filebuf_flags |= GIT_FILEBUF_FSYNC;
error = git_filebuf_open(&output, git_buf_cstr(&commit_graph_path), filebuf_flags, 0644);
git_buf_dispose(&commit_graph_path);
if (error < 0)
return error;
error = commit_graph_write(w, commit_graph_write_filebuf, &output);
if (error < 0) {
git_filebuf_cleanup(&output);
return error;
}
return git_filebuf_commit(&output);
}
int git_commit_graph_writer_dump(
git_buf *cgraph,
git_commit_graph_writer *w,
git_commit_graph_writer_options *opts)
{
/* TODO: support options. */
GIT_UNUSED(opts);
return commit_graph_write(w, commit_graph_write_buf, cgraph);
}
|
0 |
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2
|
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2/src/strarray.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 "util.h"
#include "common.h"
int git_strarray_copy(git_strarray *tgt, const git_strarray *src)
{
size_t i;
GIT_ASSERT_ARG(tgt);
GIT_ASSERT_ARG(src);
memset(tgt, 0, sizeof(*tgt));
if (!src->count)
return 0;
tgt->strings = git__calloc(src->count, sizeof(char *));
GIT_ERROR_CHECK_ALLOC(tgt->strings);
for (i = 0; i < src->count; ++i) {
if (!src->strings[i])
continue;
tgt->strings[tgt->count] = git__strdup(src->strings[i]);
if (!tgt->strings[tgt->count]) {
git_strarray_dispose(tgt);
memset(tgt, 0, sizeof(*tgt));
return -1;
}
tgt->count++;
}
return 0;
}
void git_strarray_dispose(git_strarray *array)
{
size_t i;
if (array == NULL)
return;
for (i = 0; i < array->count; ++i)
git__free(array->strings[i]);
git__free(array->strings);
memset(array, 0, sizeof(*array));
}
#ifndef GIT_DEPRECATE_HARD
void git_strarray_free(git_strarray *array)
{
git_strarray_dispose(array);
}
#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.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 "delta.h"
/* maximum hash entry list for the same hash bucket */
#define HASH_LIMIT 64
#define RABIN_SHIFT 23
#define RABIN_WINDOW 16
static const unsigned int T[256] = {
0x00000000, 0xab59b4d1, 0x56b369a2, 0xfdeadd73, 0x063f6795, 0xad66d344,
0x508c0e37, 0xfbd5bae6, 0x0c7ecf2a, 0xa7277bfb, 0x5acda688, 0xf1941259,
0x0a41a8bf, 0xa1181c6e, 0x5cf2c11d, 0xf7ab75cc, 0x18fd9e54, 0xb3a42a85,
0x4e4ef7f6, 0xe5174327, 0x1ec2f9c1, 0xb59b4d10, 0x48719063, 0xe32824b2,
0x1483517e, 0xbfdae5af, 0x423038dc, 0xe9698c0d, 0x12bc36eb, 0xb9e5823a,
0x440f5f49, 0xef56eb98, 0x31fb3ca8, 0x9aa28879, 0x6748550a, 0xcc11e1db,
0x37c45b3d, 0x9c9defec, 0x6177329f, 0xca2e864e, 0x3d85f382, 0x96dc4753,
0x6b369a20, 0xc06f2ef1, 0x3bba9417, 0x90e320c6, 0x6d09fdb5, 0xc6504964,
0x2906a2fc, 0x825f162d, 0x7fb5cb5e, 0xd4ec7f8f, 0x2f39c569, 0x846071b8,
0x798aaccb, 0xd2d3181a, 0x25786dd6, 0x8e21d907, 0x73cb0474, 0xd892b0a5,
0x23470a43, 0x881ebe92, 0x75f463e1, 0xdeadd730, 0x63f67950, 0xc8afcd81,
0x354510f2, 0x9e1ca423, 0x65c91ec5, 0xce90aa14, 0x337a7767, 0x9823c3b6,
0x6f88b67a, 0xc4d102ab, 0x393bdfd8, 0x92626b09, 0x69b7d1ef, 0xc2ee653e,
0x3f04b84d, 0x945d0c9c, 0x7b0be704, 0xd05253d5, 0x2db88ea6, 0x86e13a77,
0x7d348091, 0xd66d3440, 0x2b87e933, 0x80de5de2, 0x7775282e, 0xdc2c9cff,
0x21c6418c, 0x8a9ff55d, 0x714a4fbb, 0xda13fb6a, 0x27f92619, 0x8ca092c8,
0x520d45f8, 0xf954f129, 0x04be2c5a, 0xafe7988b, 0x5432226d, 0xff6b96bc,
0x02814bcf, 0xa9d8ff1e, 0x5e738ad2, 0xf52a3e03, 0x08c0e370, 0xa39957a1,
0x584ced47, 0xf3155996, 0x0eff84e5, 0xa5a63034, 0x4af0dbac, 0xe1a96f7d,
0x1c43b20e, 0xb71a06df, 0x4ccfbc39, 0xe79608e8, 0x1a7cd59b, 0xb125614a,
0x468e1486, 0xedd7a057, 0x103d7d24, 0xbb64c9f5, 0x40b17313, 0xebe8c7c2,
0x16021ab1, 0xbd5bae60, 0x6cb54671, 0xc7ecf2a0, 0x3a062fd3, 0x915f9b02,
0x6a8a21e4, 0xc1d39535, 0x3c394846, 0x9760fc97, 0x60cb895b, 0xcb923d8a,
0x3678e0f9, 0x9d215428, 0x66f4eece, 0xcdad5a1f, 0x3047876c, 0x9b1e33bd,
0x7448d825, 0xdf116cf4, 0x22fbb187, 0x89a20556, 0x7277bfb0, 0xd92e0b61,
0x24c4d612, 0x8f9d62c3, 0x7836170f, 0xd36fa3de, 0x2e857ead, 0x85dcca7c,
0x7e09709a, 0xd550c44b, 0x28ba1938, 0x83e3ade9, 0x5d4e7ad9, 0xf617ce08,
0x0bfd137b, 0xa0a4a7aa, 0x5b711d4c, 0xf028a99d, 0x0dc274ee, 0xa69bc03f,
0x5130b5f3, 0xfa690122, 0x0783dc51, 0xacda6880, 0x570fd266, 0xfc5666b7,
0x01bcbbc4, 0xaae50f15, 0x45b3e48d, 0xeeea505c, 0x13008d2f, 0xb85939fe,
0x438c8318, 0xe8d537c9, 0x153feaba, 0xbe665e6b, 0x49cd2ba7, 0xe2949f76,
0x1f7e4205, 0xb427f6d4, 0x4ff24c32, 0xe4abf8e3, 0x19412590, 0xb2189141,
0x0f433f21, 0xa41a8bf0, 0x59f05683, 0xf2a9e252, 0x097c58b4, 0xa225ec65,
0x5fcf3116, 0xf49685c7, 0x033df00b, 0xa86444da, 0x558e99a9, 0xfed72d78,
0x0502979e, 0xae5b234f, 0x53b1fe3c, 0xf8e84aed, 0x17bea175, 0xbce715a4,
0x410dc8d7, 0xea547c06, 0x1181c6e0, 0xbad87231, 0x4732af42, 0xec6b1b93,
0x1bc06e5f, 0xb099da8e, 0x4d7307fd, 0xe62ab32c, 0x1dff09ca, 0xb6a6bd1b,
0x4b4c6068, 0xe015d4b9, 0x3eb80389, 0x95e1b758, 0x680b6a2b, 0xc352defa,
0x3887641c, 0x93ded0cd, 0x6e340dbe, 0xc56db96f, 0x32c6cca3, 0x999f7872,
0x6475a501, 0xcf2c11d0, 0x34f9ab36, 0x9fa01fe7, 0x624ac294, 0xc9137645,
0x26459ddd, 0x8d1c290c, 0x70f6f47f, 0xdbaf40ae, 0x207afa48, 0x8b234e99,
0x76c993ea, 0xdd90273b, 0x2a3b52f7, 0x8162e626, 0x7c883b55, 0xd7d18f84,
0x2c043562, 0x875d81b3, 0x7ab75cc0, 0xd1eee811
};
static const unsigned int U[256] = {
0x00000000, 0x7eb5200d, 0x5633f4cb, 0x2886d4c6, 0x073e5d47, 0x798b7d4a,
0x510da98c, 0x2fb88981, 0x0e7cba8e, 0x70c99a83, 0x584f4e45, 0x26fa6e48,
0x0942e7c9, 0x77f7c7c4, 0x5f711302, 0x21c4330f, 0x1cf9751c, 0x624c5511,
0x4aca81d7, 0x347fa1da, 0x1bc7285b, 0x65720856, 0x4df4dc90, 0x3341fc9d,
0x1285cf92, 0x6c30ef9f, 0x44b63b59, 0x3a031b54, 0x15bb92d5, 0x6b0eb2d8,
0x4388661e, 0x3d3d4613, 0x39f2ea38, 0x4747ca35, 0x6fc11ef3, 0x11743efe,
0x3eccb77f, 0x40799772, 0x68ff43b4, 0x164a63b9, 0x378e50b6, 0x493b70bb,
0x61bda47d, 0x1f088470, 0x30b00df1, 0x4e052dfc, 0x6683f93a, 0x1836d937,
0x250b9f24, 0x5bbebf29, 0x73386bef, 0x0d8d4be2, 0x2235c263, 0x5c80e26e,
0x740636a8, 0x0ab316a5, 0x2b7725aa, 0x55c205a7, 0x7d44d161, 0x03f1f16c,
0x2c4978ed, 0x52fc58e0, 0x7a7a8c26, 0x04cfac2b, 0x73e5d470, 0x0d50f47d,
0x25d620bb, 0x5b6300b6, 0x74db8937, 0x0a6ea93a, 0x22e87dfc, 0x5c5d5df1,
0x7d996efe, 0x032c4ef3, 0x2baa9a35, 0x551fba38, 0x7aa733b9, 0x041213b4,
0x2c94c772, 0x5221e77f, 0x6f1ca16c, 0x11a98161, 0x392f55a7, 0x479a75aa,
0x6822fc2b, 0x1697dc26, 0x3e1108e0, 0x40a428ed, 0x61601be2, 0x1fd53bef,
0x3753ef29, 0x49e6cf24, 0x665e46a5, 0x18eb66a8, 0x306db26e, 0x4ed89263,
0x4a173e48, 0x34a21e45, 0x1c24ca83, 0x6291ea8e, 0x4d29630f, 0x339c4302,
0x1b1a97c4, 0x65afb7c9, 0x446b84c6, 0x3adea4cb, 0x1258700d, 0x6ced5000,
0x4355d981, 0x3de0f98c, 0x15662d4a, 0x6bd30d47, 0x56ee4b54, 0x285b6b59,
0x00ddbf9f, 0x7e689f92, 0x51d01613, 0x2f65361e, 0x07e3e2d8, 0x7956c2d5,
0x5892f1da, 0x2627d1d7, 0x0ea10511, 0x7014251c, 0x5facac9d, 0x21198c90,
0x099f5856, 0x772a785b, 0x4c921c31, 0x32273c3c, 0x1aa1e8fa, 0x6414c8f7,
0x4bac4176, 0x3519617b, 0x1d9fb5bd, 0x632a95b0, 0x42eea6bf, 0x3c5b86b2,
0x14dd5274, 0x6a687279, 0x45d0fbf8, 0x3b65dbf5, 0x13e30f33, 0x6d562f3e,
0x506b692d, 0x2ede4920, 0x06589de6, 0x78edbdeb, 0x5755346a, 0x29e01467,
0x0166c0a1, 0x7fd3e0ac, 0x5e17d3a3, 0x20a2f3ae, 0x08242768, 0x76910765,
0x59298ee4, 0x279caee9, 0x0f1a7a2f, 0x71af5a22, 0x7560f609, 0x0bd5d604,
0x235302c2, 0x5de622cf, 0x725eab4e, 0x0ceb8b43, 0x246d5f85, 0x5ad87f88,
0x7b1c4c87, 0x05a96c8a, 0x2d2fb84c, 0x539a9841, 0x7c2211c0, 0x029731cd,
0x2a11e50b, 0x54a4c506, 0x69998315, 0x172ca318, 0x3faa77de, 0x411f57d3,
0x6ea7de52, 0x1012fe5f, 0x38942a99, 0x46210a94, 0x67e5399b, 0x19501996,
0x31d6cd50, 0x4f63ed5d, 0x60db64dc, 0x1e6e44d1, 0x36e89017, 0x485db01a,
0x3f77c841, 0x41c2e84c, 0x69443c8a, 0x17f11c87, 0x38499506, 0x46fcb50b,
0x6e7a61cd, 0x10cf41c0, 0x310b72cf, 0x4fbe52c2, 0x67388604, 0x198da609,
0x36352f88, 0x48800f85, 0x6006db43, 0x1eb3fb4e, 0x238ebd5d, 0x5d3b9d50,
0x75bd4996, 0x0b08699b, 0x24b0e01a, 0x5a05c017, 0x728314d1, 0x0c3634dc,
0x2df207d3, 0x534727de, 0x7bc1f318, 0x0574d315, 0x2acc5a94, 0x54797a99,
0x7cffae5f, 0x024a8e52, 0x06852279, 0x78300274, 0x50b6d6b2, 0x2e03f6bf,
0x01bb7f3e, 0x7f0e5f33, 0x57888bf5, 0x293dabf8, 0x08f998f7, 0x764cb8fa,
0x5eca6c3c, 0x207f4c31, 0x0fc7c5b0, 0x7172e5bd, 0x59f4317b, 0x27411176,
0x1a7c5765, 0x64c97768, 0x4c4fa3ae, 0x32fa83a3, 0x1d420a22, 0x63f72a2f,
0x4b71fee9, 0x35c4dee4, 0x1400edeb, 0x6ab5cde6, 0x42331920, 0x3c86392d,
0x133eb0ac, 0x6d8b90a1, 0x450d4467, 0x3bb8646a
};
struct index_entry {
const unsigned char *ptr;
unsigned int val;
struct index_entry *next;
};
struct git_delta_index {
unsigned long memsize;
const void *src_buf;
size_t src_size;
unsigned int hash_mask;
struct index_entry *hash[GIT_FLEX_ARRAY];
};
static int lookup_index_alloc(
void **out, unsigned long *out_len, size_t entries, size_t hash_count)
{
size_t entries_len, hash_len, index_len;
GIT_ERROR_CHECK_ALLOC_MULTIPLY(&entries_len, entries, sizeof(struct index_entry));
GIT_ERROR_CHECK_ALLOC_MULTIPLY(&hash_len, hash_count, sizeof(struct index_entry *));
GIT_ERROR_CHECK_ALLOC_ADD(&index_len, sizeof(struct git_delta_index), entries_len);
GIT_ERROR_CHECK_ALLOC_ADD(&index_len, index_len, hash_len);
if (!git__is_ulong(index_len)) {
git_error_set(GIT_ERROR_NOMEMORY, "overly large delta");
return -1;
}
*out = git__malloc(index_len);
GIT_ERROR_CHECK_ALLOC(*out);
*out_len = (unsigned long)index_len;
return 0;
}
int git_delta_index_init(
git_delta_index **out, const void *buf, size_t bufsize)
{
unsigned int i, hsize, hmask, entries, prev_val, *hash_count;
const unsigned char *data, *buffer = buf;
struct git_delta_index *index;
struct index_entry *entry, **hash;
void *mem;
unsigned long memsize;
*out = NULL;
if (!buf || !bufsize)
return 0;
/* Determine index hash size. Note that indexing skips the
first byte to allow for optimizing the rabin polynomial
initialization in create_delta(). */
entries = (unsigned int)(bufsize - 1) / RABIN_WINDOW;
if (bufsize >= 0xffffffffUL) {
/*
* Current delta format can't encode offsets into
* reference buffer with more than 32 bits.
*/
entries = 0xfffffffeU / RABIN_WINDOW;
}
hsize = entries / 4;
for (i = 4; i < 31 && (1u << i) < hsize; i++);
hsize = 1 << i;
hmask = hsize - 1;
if (lookup_index_alloc(&mem, &memsize, entries, hsize) < 0)
return -1;
index = mem;
mem = index->hash;
hash = mem;
mem = hash + hsize;
entry = mem;
index->memsize = memsize;
index->src_buf = buf;
index->src_size = bufsize;
index->hash_mask = hmask;
memset(hash, 0, hsize * sizeof(*hash));
/* allocate an array to count hash entries */
hash_count = git__calloc(hsize, sizeof(*hash_count));
if (!hash_count) {
git__free(index);
return -1;
}
/* then populate the index */
prev_val = ~0;
for (data = buffer + entries * RABIN_WINDOW - RABIN_WINDOW;
data >= buffer;
data -= RABIN_WINDOW) {
unsigned int val = 0;
for (i = 1; i <= RABIN_WINDOW; i++)
val = ((val << 8) | data[i]) ^ T[val >> RABIN_SHIFT];
if (val == prev_val) {
/* keep the lowest of consecutive identical blocks */
entry[-1].ptr = data + RABIN_WINDOW;
} else {
prev_val = val;
i = val & hmask;
entry->ptr = data + RABIN_WINDOW;
entry->val = val;
entry->next = hash[i];
hash[i] = entry++;
hash_count[i]++;
}
}
/*
* Determine a limit on the number of entries in the same hash
* bucket. This guard us against patological data sets causing
* really bad hash distribution with most entries in the same hash
* bucket that would bring us to O(m*n) computing costs (m and n
* corresponding to reference and target buffer sizes).
*
* Make sure none of the hash buckets has more entries than
* we're willing to test. Otherwise we cull the entry list
* uniformly to still preserve a good repartition across
* the reference buffer.
*/
for (i = 0; i < hsize; i++) {
if (hash_count[i] < HASH_LIMIT)
continue;
entry = hash[i];
do {
struct index_entry *keep = entry;
int skip = hash_count[i] / HASH_LIMIT / 2;
do {
entry = entry->next;
} while(--skip && entry);
keep->next = entry;
} while (entry);
}
git__free(hash_count);
*out = index;
return 0;
}
void git_delta_index_free(git_delta_index *index)
{
git__free(index);
}
size_t git_delta_index_size(git_delta_index *index)
{
GIT_ASSERT_ARG(index);
return index->memsize;
}
/*
* The maximum size for any opcode sequence, including the initial header
* plus rabin window plus biggest copy.
*/
#define MAX_OP_SIZE (5 + 5 + 1 + RABIN_WINDOW + 7)
int git_delta_create_from_index(
void **out,
size_t *out_len,
const struct git_delta_index *index,
const void *trg_buf,
size_t trg_size,
size_t max_size)
{
unsigned int i, bufpos, bufsize, moff, msize, val;
int inscnt;
const unsigned char *ref_data, *ref_top, *data, *top;
unsigned char *buf;
*out = NULL;
*out_len = 0;
if (!trg_buf || !trg_size)
return 0;
if (index->src_size > UINT_MAX ||
trg_size > UINT_MAX ||
max_size > (UINT_MAX - MAX_OP_SIZE - 1)) {
git_error_set(GIT_ERROR_INVALID, "buffer sizes too large for delta processing");
return -1;
}
bufpos = 0;
bufsize = 8192;
if (max_size && bufsize >= max_size)
bufsize = (unsigned int)(max_size + MAX_OP_SIZE + 1);
buf = git__malloc(bufsize);
GIT_ERROR_CHECK_ALLOC(buf);
/* store reference buffer size */
i = (unsigned int)index->src_size;
while (i >= 0x80) {
buf[bufpos++] = i | 0x80;
i >>= 7;
}
buf[bufpos++] = i;
/* store target buffer size */
i = (unsigned int)trg_size;
while (i >= 0x80) {
buf[bufpos++] = i | 0x80;
i >>= 7;
}
buf[bufpos++] = i;
ref_data = index->src_buf;
ref_top = ref_data + index->src_size;
data = trg_buf;
top = (const unsigned char *) trg_buf + trg_size;
bufpos++;
val = 0;
for (i = 0; i < RABIN_WINDOW && data < top; i++, data++) {
buf[bufpos++] = *data;
val = ((val << 8) | *data) ^ T[val >> RABIN_SHIFT];
}
inscnt = i;
moff = 0;
msize = 0;
while (data < top) {
if (msize < 4096) {
struct index_entry *entry;
val ^= U[data[-RABIN_WINDOW]];
val = ((val << 8) | *data) ^ T[val >> RABIN_SHIFT];
i = val & index->hash_mask;
for (entry = index->hash[i]; entry; entry = entry->next) {
const unsigned char *ref = entry->ptr;
const unsigned char *src = data;
unsigned int ref_size = (unsigned int)(ref_top - ref);
if (entry->val != val)
continue;
if (ref_size > (unsigned int)(top - src))
ref_size = (unsigned int)(top - src);
if (ref_size <= msize)
break;
while (ref_size-- && *src++ == *ref)
ref++;
if (msize < (unsigned int)(ref - entry->ptr)) {
/* this is our best match so far */
msize = (unsigned int)(ref - entry->ptr);
moff = (unsigned int)(entry->ptr - ref_data);
if (msize >= 4096) /* good enough */
break;
}
}
}
if (msize < 4) {
if (!inscnt)
bufpos++;
buf[bufpos++] = *data++;
inscnt++;
if (inscnt == 0x7f) {
buf[bufpos - inscnt - 1] = inscnt;
inscnt = 0;
}
msize = 0;
} else {
unsigned int left;
unsigned char *op;
if (inscnt) {
while (moff && ref_data[moff-1] == data[-1]) {
/* we can match one byte back */
msize++;
moff--;
data--;
bufpos--;
if (--inscnt)
continue;
bufpos--; /* remove count slot */
inscnt--; /* make it -1 */
break;
}
buf[bufpos - inscnt - 1] = inscnt;
inscnt = 0;
}
/* A copy op is currently limited to 64KB (pack v2) */
left = (msize < 0x10000) ? 0 : (msize - 0x10000);
msize -= left;
op = buf + bufpos++;
i = 0x80;
if (moff & 0x000000ff)
buf[bufpos++] = moff >> 0, i |= 0x01;
if (moff & 0x0000ff00)
buf[bufpos++] = moff >> 8, i |= 0x02;
if (moff & 0x00ff0000)
buf[bufpos++] = moff >> 16, i |= 0x04;
if (moff & 0xff000000)
buf[bufpos++] = moff >> 24, i |= 0x08;
if (msize & 0x00ff)
buf[bufpos++] = msize >> 0, i |= 0x10;
if (msize & 0xff00)
buf[bufpos++] = msize >> 8, i |= 0x20;
*op = i;
data += msize;
moff += msize;
msize = left;
if (msize < 4096) {
int j;
val = 0;
for (j = -RABIN_WINDOW; j < 0; j++)
val = ((val << 8) | data[j])
^ T[val >> RABIN_SHIFT];
}
}
if (bufpos >= bufsize - MAX_OP_SIZE) {
void *tmp = buf;
bufsize = bufsize * 3 / 2;
if (max_size && bufsize >= max_size)
bufsize = (unsigned int)(max_size + MAX_OP_SIZE + 1);
if (max_size && bufpos > max_size)
break;
buf = git__realloc(buf, bufsize);
if (!buf) {
git__free(tmp);
return -1;
}
}
}
if (inscnt)
buf[bufpos - inscnt - 1] = inscnt;
if (max_size && bufpos > max_size) {
git_error_set(GIT_ERROR_NOMEMORY, "delta would be larger than maximum size");
git__free(buf);
return GIT_EBUFS;
}
*out_len = bufpos;
*out = buf;
return 0;
}
/*
* Delta application was heavily cribbed from BinaryDelta.java in JGit, which
* itself was heavily cribbed from <code>patch-delta.c</code> in the
* GIT project. The original delta patching code was written by
* Nicolas Pitre <[email protected]>.
*/
static int hdr_sz(
size_t *size,
const unsigned char **delta,
const unsigned char *end)
{
const unsigned char *d = *delta;
size_t r = 0;
unsigned int c, shift = 0;
do {
if (d == end) {
git_error_set(GIT_ERROR_INVALID, "truncated delta");
return -1;
}
c = *d++;
r |= (c & 0x7f) << shift;
shift += 7;
} while (c & 0x80);
*delta = d;
*size = r;
return 0;
}
int git_delta_read_header(
size_t *base_out,
size_t *result_out,
const unsigned char *delta,
size_t delta_len)
{
const unsigned char *delta_end = delta + delta_len;
if ((hdr_sz(base_out, &delta, delta_end) < 0) ||
(hdr_sz(result_out, &delta, delta_end) < 0))
return -1;
return 0;
}
#define DELTA_HEADER_BUFFER_LEN 16
int git_delta_read_header_fromstream(
size_t *base_sz, size_t *res_sz, git_packfile_stream *stream)
{
static const size_t buffer_len = DELTA_HEADER_BUFFER_LEN;
unsigned char buffer[DELTA_HEADER_BUFFER_LEN];
const unsigned char *delta, *delta_end;
size_t len;
ssize_t read;
len = read = 0;
while (len < buffer_len) {
read = git_packfile_stream_read(stream, &buffer[len], buffer_len - len);
if (read == 0)
break;
if (read == GIT_EBUFS)
continue;
len += read;
}
delta = buffer;
delta_end = delta + len;
if ((hdr_sz(base_sz, &delta, delta_end) < 0) ||
(hdr_sz(res_sz, &delta, delta_end) < 0))
return -1;
return 0;
}
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)
{
const unsigned char *delta_end = delta + delta_len;
size_t base_sz, res_sz, alloc_sz;
unsigned char *res_dp;
*out = NULL;
*out_len = 0;
/*
* Check that the base size matches the data we were given;
* if not we would underflow while accessing data from the
* base object, resulting in data corruption or segfault.
*/
if ((hdr_sz(&base_sz, &delta, delta_end) < 0) || (base_sz != base_len)) {
git_error_set(GIT_ERROR_INVALID, "failed to apply delta: base size does not match given data");
return -1;
}
if (hdr_sz(&res_sz, &delta, delta_end) < 0) {
git_error_set(GIT_ERROR_INVALID, "failed to apply delta: base size does not match given data");
return -1;
}
GIT_ERROR_CHECK_ALLOC_ADD(&alloc_sz, res_sz, 1);
res_dp = git__malloc(alloc_sz);
GIT_ERROR_CHECK_ALLOC(res_dp);
res_dp[res_sz] = '\0';
*out = res_dp;
*out_len = res_sz;
while (delta < delta_end) {
unsigned char cmd = *delta++;
if (cmd & 0x80) {
/* cmd is a copy instruction; copy from the base. */
size_t off = 0, len = 0, end;
#define ADD_DELTA(o, shift) { if (delta < delta_end) (o) |= ((unsigned) *delta++ << shift); else goto fail; }
if (cmd & 0x01) ADD_DELTA(off, 0UL);
if (cmd & 0x02) ADD_DELTA(off, 8UL);
if (cmd & 0x04) ADD_DELTA(off, 16UL);
if (cmd & 0x08) ADD_DELTA(off, 24UL);
if (cmd & 0x10) ADD_DELTA(len, 0UL);
if (cmd & 0x20) ADD_DELTA(len, 8UL);
if (cmd & 0x40) ADD_DELTA(len, 16UL);
if (!len) len = 0x10000;
#undef ADD_DELTA
if (GIT_ADD_SIZET_OVERFLOW(&end, off, len) ||
base_len < end || res_sz < len)
goto fail;
memcpy(res_dp, base + off, len);
res_dp += len;
res_sz -= len;
} else if (cmd) {
/*
* cmd is a literal insert instruction; copy from
* the delta stream itself.
*/
if (delta_end - delta < cmd || res_sz < cmd)
goto fail;
memcpy(res_dp, delta, cmd);
delta += cmd;
res_dp += cmd;
res_sz -= cmd;
} else {
/* cmd == 0 is reserved for future encodings. */
goto fail;
}
}
if (delta != delta_end || res_sz)
goto fail;
return 0;
fail:
git__free(*out);
*out = NULL;
*out_len = 0;
git_error_set(GIT_ERROR_INVALID, "failed to apply delta");
return -1;
}
|
0 |
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2
|
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2/src/buffer.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_buffer_h__
#define INCLUDE_buffer_h__
#include "common.h"
#include "git2/strarray.h"
#include "git2/buffer.h"
/* typedef struct {
* char *ptr;
* size_t asize, size;
* } git_buf;
*/
typedef enum {
GIT_BUF_BOM_NONE = 0,
GIT_BUF_BOM_UTF8 = 1,
GIT_BUF_BOM_UTF16_LE = 2,
GIT_BUF_BOM_UTF16_BE = 3,
GIT_BUF_BOM_UTF32_LE = 4,
GIT_BUF_BOM_UTF32_BE = 5
} git_buf_bom_t;
typedef struct {
git_buf_bom_t bom; /* BOM found at head of text */
unsigned int nul, cr, lf, crlf; /* NUL, CR, LF and CRLF counts */
unsigned int printable, nonprintable; /* These are just approximations! */
} git_buf_text_stats;
extern char git_buf__initbuf[];
extern char git_buf__oom[];
/* Use to initialize buffer structure when git_buf is on stack */
#define GIT_BUF_INIT { git_buf__initbuf, 0, 0 }
/**
* Static initializer for git_buf from static buffer
*/
#ifdef GIT_DEPRECATE_HARD
# define GIT_BUF_INIT_CONST(STR,LEN) { (char *)(STR), 0, (size_t)(LEN) }
#endif
GIT_INLINE(bool) git_buf_is_allocated(const git_buf *buf)
{
return (buf->ptr != NULL && buf->asize > 0);
}
/**
* Initialize a git_buf structure.
*
* For the cases where GIT_BUF_INIT cannot be used to do static
* initialization.
*/
extern int git_buf_init(git_buf *buf, size_t initial_size);
#ifdef GIT_DEPRECATE_HARD
/**
* Resize the buffer allocation to make more space.
*
* This will attempt to grow the buffer to accommodate the target size.
*
* If the buffer refers to memory that was not allocated by libgit2 (i.e.
* the `asize` field is zero), then `ptr` will be replaced with a newly
* allocated block of data. Be careful so that memory allocated by the
* caller is not lost. As a special variant, if you pass `target_size` as
* 0 and the memory is not allocated by libgit2, this will allocate a new
* buffer of size `size` and copy the external data into it.
*
* Currently, this will never shrink a buffer, only expand it.
*
* If the allocation fails, this will return an error and the buffer will be
* marked as invalid for future operations, invaliding the contents.
*
* @param buffer The buffer to be resized; may or may not be allocated yet
* @param target_size The desired available size
* @return 0 on success, -1 on allocation failure
*/
int git_buf_grow(git_buf *buffer, size_t target_size);
#endif
/**
* Resize the buffer allocation to make more space.
*
* This will attempt to grow the buffer to accommodate the additional size.
* It is similar to `git_buf_grow`, but performs the new size calculation,
* checking for overflow.
*
* Like `git_buf_grow`, if this is a user-supplied buffer, this will allocate
* a new buffer.
*/
extern int git_buf_grow_by(git_buf *buffer, size_t additional_size);
/**
* Attempt to grow the buffer to hold at least `target_size` bytes.
*
* If the allocation fails, this will return an error. If `mark_oom` is true,
* this will mark the buffer as invalid for future operations; if false,
* existing buffer content will be preserved, but calling code must handle
* that buffer was not expanded. If `preserve_external` is true, then any
* existing data pointed to be `ptr` even if `asize` is zero will be copied
* into the newly allocated buffer.
*/
extern int git_buf_try_grow(
git_buf *buf, size_t target_size, bool mark_oom);
/**
* Sanitizes git_buf structures provided from user input. Users of the
* library, when providing git_buf's, may wish to provide a NULL ptr for
* ease of handling. The buffer routines, however, expect a non-NULL ptr
* always. This helper method simply handles NULL input, converting to a
* git_buf__initbuf. If a buffer with a non-NULL ptr is passed in, this method
* assures that the buffer is '\0'-terminated.
*/
extern int git_buf_sanitize(git_buf *buf);
extern void git_buf_swap(git_buf *buf_a, git_buf *buf_b);
extern char *git_buf_detach(git_buf *buf);
extern int git_buf_attach(git_buf *buf, char *ptr, size_t asize);
/* Populates a `git_buf` where the contents are not "owned" by the
* buffer, and calls to `git_buf_dispose` will not free the given buf.
*/
extern void git_buf_attach_notowned(
git_buf *buf, const char *ptr, size_t size);
/**
* Test if there have been any reallocation failures with this git_buf.
*
* Any function that writes to a git_buf can fail due to memory allocation
* issues. If one fails, the git_buf will be marked with an OOM error and
* further calls to modify the buffer will fail. Check git_buf_oom() at the
* end of your sequence and it will be true if you ran out of memory at any
* point with that buffer.
*
* @return false if no error, true if allocation error
*/
GIT_INLINE(bool) git_buf_oom(const git_buf *buf)
{
return (buf->ptr == git_buf__oom);
}
/*
* Functions below that return int value error codes will return 0 on
* success or -1 on failure (which generally means an allocation failed).
* Using a git_buf where the allocation has failed with result in -1 from
* all further calls using that buffer. As a result, you can ignore the
* return code of these functions and call them in a series then just call
* git_buf_oom at the end.
*/
#ifdef GIT_DEPRECATE_HARD
int git_buf_set(git_buf *buffer, const void *data, size_t datalen);
#endif
int git_buf_sets(git_buf *buf, const char *string);
int git_buf_putc(git_buf *buf, char c);
int git_buf_putcn(git_buf *buf, char c, size_t len);
int git_buf_put(git_buf *buf, const char *data, size_t len);
int git_buf_puts(git_buf *buf, const char *string);
int git_buf_printf(git_buf *buf, const char *format, ...) GIT_FORMAT_PRINTF(2, 3);
int git_buf_vprintf(git_buf *buf, const char *format, va_list ap);
void git_buf_clear(git_buf *buf);
void git_buf_consume_bytes(git_buf *buf, size_t len);
void git_buf_consume(git_buf *buf, const char *end);
void git_buf_truncate(git_buf *buf, size_t len);
void git_buf_shorten(git_buf *buf, size_t amount);
void git_buf_truncate_at_char(git_buf *buf, char separator);
void git_buf_rtruncate_at_char(git_buf *path, char separator);
/** General join with separator */
int git_buf_join_n(git_buf *buf, char separator, int nbuf, ...);
/** Fast join of two strings - first may legally point into `buf` data */
int git_buf_join(git_buf *buf, char separator, const char *str_a, const char *str_b);
/** Fast join of three strings - cannot reference `buf` data */
int git_buf_join3(git_buf *buf, char separator, const char *str_a, const char *str_b, const char *str_c);
/**
* Join two strings as paths, inserting a slash between as needed.
* @return 0 on success, -1 on failure
*/
GIT_INLINE(int) git_buf_joinpath(git_buf *buf, const char *a, const char *b)
{
return git_buf_join(buf, '/', a, b);
}
GIT_INLINE(const char *) git_buf_cstr(const git_buf *buf)
{
return buf->ptr;
}
GIT_INLINE(size_t) git_buf_len(const git_buf *buf)
{
return buf->size;
}
int git_buf_copy_cstr(char *data, size_t datasize, const git_buf *buf);
#define git_buf_PUTS(buf, str) git_buf_put(buf, str, sizeof(str) - 1)
GIT_INLINE(ssize_t) git_buf_rfind_next(const git_buf *buf, char ch)
{
ssize_t idx = (ssize_t)buf->size - 1;
while (idx >= 0 && buf->ptr[idx] == ch) idx--;
while (idx >= 0 && buf->ptr[idx] != ch) idx--;
return idx;
}
GIT_INLINE(ssize_t) git_buf_rfind(const git_buf *buf, char ch)
{
ssize_t idx = (ssize_t)buf->size - 1;
while (idx >= 0 && buf->ptr[idx] != ch) idx--;
return idx;
}
GIT_INLINE(ssize_t) git_buf_find(const git_buf *buf, char ch)
{
void *found = memchr(buf->ptr, ch, buf->size);
return found ? (ssize_t)((const char *)found - buf->ptr) : -1;
}
/* Remove whitespace from the end of the buffer */
void git_buf_rtrim(git_buf *buf);
int git_buf_cmp(const git_buf *a, const git_buf *b);
/* Quote and unquote a buffer as specified in
* http://marc.info/?l=git&m=112927316408690&w=2
*/
int git_buf_quote(git_buf *buf);
int git_buf_unquote(git_buf *buf);
/* Write data as base64 encoded in buffer */
int git_buf_encode_base64(git_buf *buf, const char *data, size_t len);
/* Decode the given bas64 and write the result to the buffer */
int git_buf_decode_base64(git_buf *buf, const char *base64, size_t len);
/* Write data as "base85" encoded in buffer */
int git_buf_encode_base85(git_buf *buf, const char *data, size_t len);
/* Decode the given "base85" and write the result to the buffer */
int git_buf_decode_base85(git_buf *buf, const char *base64, size_t len, size_t output_len);
/* Decode the given percent-encoded string and write the result to the buffer */
int git_buf_decode_percent(git_buf *buf, const char *str, size_t len);
/*
* Insert, remove or replace a portion of the buffer.
*
* @param buf The buffer to work with
*
* @param where The location in the buffer where the transformation
* should be applied.
*
* @param nb_to_remove The number of chars to be removed. 0 to not
* remove any character in the buffer.
*
* @param data A pointer to the data which should be inserted.
*
* @param nb_to_insert The number of chars to be inserted. 0 to not
* insert any character from the buffer.
*
* @return 0 or an error code.
*/
int git_buf_splice(
git_buf *buf,
size_t where,
size_t nb_to_remove,
const char *data,
size_t nb_to_insert);
/**
* Append string to buffer, prefixing each character from `esc_chars` with
* `esc_with` string.
*
* @param buf Buffer to append data to
* @param string String to escape and append
* @param esc_chars Characters to be escaped
* @param esc_with String to insert in from of each found character
* @return 0 on success, <0 on failure (probably allocation problem)
*/
extern int git_buf_puts_escaped(
git_buf *buf,
const char *string,
const char *esc_chars,
const char *esc_with);
/**
* Append string escaping characters that are regex special
*/
GIT_INLINE(int) git_buf_puts_escape_regex(git_buf *buf, const char *string)
{
return git_buf_puts_escaped(buf, string, "^.[]$()|*+?{}\\", "\\");
}
/**
* Unescape all characters in a buffer in place
*
* I.e. remove backslashes
*/
extern void git_buf_unescape(git_buf *buf);
/**
* Replace all \r\n with \n.
*
* @return 0 on success, -1 on memory error
*/
extern int git_buf_crlf_to_lf(git_buf *tgt, const git_buf *src);
/**
* Replace all \n with \r\n. Does not modify existing \r\n.
*
* @return 0 on success, -1 on memory error
*/
extern int git_buf_lf_to_crlf(git_buf *tgt, const git_buf *src);
/**
* Fill buffer with the common prefix of a array of strings
*
* Buffer will be set to empty if there is no common prefix
*/
extern int git_buf_common_prefix(git_buf *buf, char *const *const strings, size_t count);
/**
* Check if a buffer begins with a UTF BOM
*
* @param bom Set to the type of BOM detected or GIT_BOM_NONE
* @param buf Buffer in which to check the first bytes for a BOM
* @return Number of bytes of BOM data (or 0 if no BOM found)
*/
extern int git_buf_detect_bom(git_buf_bom_t *bom, const git_buf *buf);
/**
* Gather stats for a piece of text
*
* Fill the `stats` structure with counts of unreadable characters, carriage
* returns, etc, so it can be used in heuristics. This automatically skips
* a trailing EOF (\032 character). Also it will look for a BOM at the
* start of the text and can be told to skip that as well.
*
* @param stats Structure to be filled in
* @param buf Text to process
* @param skip_bom Exclude leading BOM from stats if true
* @return Does the buffer heuristically look like binary data
*/
extern bool git_buf_gather_text_stats(
git_buf_text_stats *stats, const git_buf *buf, bool skip_bom);
#ifdef GIT_DEPRECATE_HARD
/**
* Check quickly if buffer looks like it contains binary data
*
* @param buf Buffer to check
* @return 1 if buffer looks like non-text data
*/
int git_buf_is_binary(const git_buf *buf);
/**
* Check quickly if buffer contains a NUL byte
*
* @param buf Buffer to check
* @return 1 if buffer contains a NUL byte
*/
int git_buf_contains_nul(const git_buf *buf);
#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/push.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_push_h__
#define INCLUDE_push_h__
#include "common.h"
#include "git2.h"
#include "refspec.h"
#include "remote.h"
typedef struct push_spec {
struct git_refspec refspec;
git_oid loid;
git_oid roid;
} push_spec;
typedef struct push_status {
bool ok;
char *ref;
char *msg;
} push_status;
struct git_push {
git_repository *repo;
git_packbuilder *pb;
git_remote *remote;
git_vector specs;
git_vector updates;
bool report_status;
/* report-status */
bool unpack_ok;
git_vector status;
/* options */
unsigned pb_parallelism;
git_remote_connection_opts connection;
};
/**
* Free the given push status object
*
* @param status The push status object
*/
void git_push_status_free(push_status *status);
/**
* Create a new push object
*
* @param out New push object
* @param remote Remote instance
*
* @return 0 or an error code
*/
int git_push_new(git_push **out, git_remote *remote);
/**
* Set options on a push object
*
* @param push The push object
* @param opts The options to set on the push object
*
* @return 0 or an error code
*/
int git_push_set_options(
git_push *push,
const git_push_options *opts);
/**
* Add a refspec to be pushed
*
* @param push The push object
* @param refspec Refspec string
*
* @return 0 or an error code
*/
int git_push_add_refspec(git_push *push, const char *refspec);
/**
* Update remote tips after a push
*
* @param push The push object
* @param callbacks the callbacks to use for this connection
*
* @return 0 or an error code
*/
int git_push_update_tips(git_push *push, const git_remote_callbacks *callbacks);
/**
* Perform the push
*
* This function will return an error in case of a protocol error or
* the server being unable to unpack the data we sent.
*
* The return value does not reflect whether the server accepted or
* refused any reference updates. Use `git_push_status_foreach()` in
* order to find out which updates were accepted or rejected.
*
* @param push The push object
* @param callbacks the callbacks to use for this connection
*
* @return 0 or an error code
*/
int git_push_finish(git_push *push, const git_remote_callbacks *callbacks);
/**
* Invoke callback `cb' on each status entry
*
* For each of the updated references, we receive a status report in the
* form of `ok refs/heads/master` or `ng refs/heads/master <msg>`.
* `msg != NULL` means the reference has not been updated for the given
* reason.
*
* Return a non-zero value from the callback to stop the loop.
*
* @param push The push object
* @param cb The callback to call on each object
* @param data The payload passed to the callback
*
* @return 0 on success, non-zero callback return value, or error code
*/
int git_push_status_foreach(git_push *push,
int (*cb)(const char *ref, const char *msg, void *data),
void *data);
/**
* Free the given push object
*
* @param push The push object
*/
void git_push_free(git_push *push);
#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.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.h"
#include "repository.h"
#include "sysdir.h"
#include "config.h"
#include "attr_file.h"
#include "ignore.h"
#include "git2/oid.h"
#include <ctype.h>
const char *git_attr__true = "[internal]__TRUE__";
const char *git_attr__false = "[internal]__FALSE__";
const char *git_attr__unset = "[internal]__UNSET__";
git_attr_value_t git_attr_value(const char *attr)
{
if (attr == NULL || attr == git_attr__unset)
return GIT_ATTR_VALUE_UNSPECIFIED;
if (attr == git_attr__true)
return GIT_ATTR_VALUE_TRUE;
if (attr == git_attr__false)
return GIT_ATTR_VALUE_FALSE;
return GIT_ATTR_VALUE_STRING;
}
static int collect_attr_files(
git_repository *repo,
git_attr_session *attr_session,
git_attr_options *opts,
const char *path,
git_vector *files);
static void release_attr_files(git_vector *files);
int git_attr_get_ext(
const char **value,
git_repository *repo,
git_attr_options *opts,
const char *pathname,
const char *name)
{
int error;
git_attr_path path;
git_vector files = GIT_VECTOR_INIT;
size_t i, j;
git_attr_file *file;
git_attr_name attr;
git_attr_rule *rule;
git_dir_flag dir_flag = GIT_DIR_FLAG_UNKNOWN;
GIT_ASSERT_ARG(value);
GIT_ASSERT_ARG(repo);
GIT_ASSERT_ARG(name);
GIT_ERROR_CHECK_VERSION(opts, GIT_ATTR_OPTIONS_VERSION, "git_attr_options");
*value = NULL;
if (git_repository_is_bare(repo))
dir_flag = GIT_DIR_FLAG_FALSE;
if (git_attr_path__init(&path, pathname, git_repository_workdir(repo), dir_flag) < 0)
return -1;
if ((error = collect_attr_files(repo, NULL, opts, pathname, &files)) < 0)
goto cleanup;
memset(&attr, 0, sizeof(attr));
attr.name = name;
attr.name_hash = git_attr_file__name_hash(name);
git_vector_foreach(&files, i, file) {
git_attr_file__foreach_matching_rule(file, &path, j, rule) {
size_t pos;
if (!git_vector_bsearch(&pos, &rule->assigns, &attr)) {
*value = ((git_attr_assignment *)git_vector_get(
&rule->assigns, pos))->value;
goto cleanup;
}
}
}
cleanup:
release_attr_files(&files);
git_attr_path__free(&path);
return error;
}
int git_attr_get(
const char **value,
git_repository *repo,
uint32_t flags,
const char *pathname,
const char *name)
{
git_attr_options opts = GIT_ATTR_OPTIONS_INIT;
opts.flags = flags;
return git_attr_get_ext(value, repo, &opts, pathname, name);
}
typedef struct {
git_attr_name name;
git_attr_assignment *found;
} attr_get_many_info;
int git_attr_get_many_with_session(
const char **values,
git_repository *repo,
git_attr_session *attr_session,
git_attr_options *opts,
const char *pathname,
size_t num_attr,
const char **names)
{
int error;
git_attr_path path;
git_vector files = GIT_VECTOR_INIT;
size_t i, j, k;
git_attr_file *file;
git_attr_rule *rule;
attr_get_many_info *info = NULL;
size_t num_found = 0;
git_dir_flag dir_flag = GIT_DIR_FLAG_UNKNOWN;
if (!num_attr)
return 0;
GIT_ASSERT_ARG(values);
GIT_ASSERT_ARG(repo);
GIT_ASSERT_ARG(pathname);
GIT_ASSERT_ARG(names);
GIT_ERROR_CHECK_VERSION(opts, GIT_ATTR_OPTIONS_VERSION, "git_attr_options");
if (git_repository_is_bare(repo))
dir_flag = GIT_DIR_FLAG_FALSE;
if (git_attr_path__init(&path, pathname, git_repository_workdir(repo), dir_flag) < 0)
return -1;
if ((error = collect_attr_files(repo, attr_session, opts, pathname, &files)) < 0)
goto cleanup;
info = git__calloc(num_attr, sizeof(attr_get_many_info));
GIT_ERROR_CHECK_ALLOC(info);
git_vector_foreach(&files, i, file) {
git_attr_file__foreach_matching_rule(file, &path, j, rule) {
for (k = 0; k < num_attr; k++) {
size_t pos;
if (info[k].found != NULL) /* already found assignment */
continue;
if (!info[k].name.name) {
info[k].name.name = names[k];
info[k].name.name_hash = git_attr_file__name_hash(names[k]);
}
if (!git_vector_bsearch(&pos, &rule->assigns, &info[k].name)) {
info[k].found = (git_attr_assignment *)
git_vector_get(&rule->assigns, pos);
values[k] = info[k].found->value;
if (++num_found == num_attr)
goto cleanup;
}
}
}
}
for (k = 0; k < num_attr; k++) {
if (!info[k].found)
values[k] = NULL;
}
cleanup:
release_attr_files(&files);
git_attr_path__free(&path);
git__free(info);
return error;
}
int git_attr_get_many(
const char **values,
git_repository *repo,
uint32_t flags,
const char *pathname,
size_t num_attr,
const char **names)
{
git_attr_options opts = GIT_ATTR_OPTIONS_INIT;
opts.flags = flags;
return git_attr_get_many_with_session(
values, repo, NULL, &opts, pathname, num_attr, names);
}
int git_attr_get_many_ext(
const char **values,
git_repository *repo,
git_attr_options *opts,
const char *pathname,
size_t num_attr,
const char **names)
{
return git_attr_get_many_with_session(
values, repo, NULL, opts, pathname, num_attr, names);
}
int git_attr_foreach(
git_repository *repo,
uint32_t flags,
const char *pathname,
int (*callback)(const char *name, const char *value, void *payload),
void *payload)
{
git_attr_options opts = GIT_ATTR_OPTIONS_INIT;
opts.flags = flags;
return git_attr_foreach_ext(repo, &opts, pathname, callback, payload);
}
int git_attr_foreach_ext(
git_repository *repo,
git_attr_options *opts,
const char *pathname,
int (*callback)(const char *name, const char *value, void *payload),
void *payload)
{
int error;
git_attr_path path;
git_vector files = GIT_VECTOR_INIT;
size_t i, j, k;
git_attr_file *file;
git_attr_rule *rule;
git_attr_assignment *assign;
git_strmap *seen = NULL;
git_dir_flag dir_flag = GIT_DIR_FLAG_UNKNOWN;
GIT_ASSERT_ARG(repo);
GIT_ASSERT_ARG(callback);
GIT_ERROR_CHECK_VERSION(opts, GIT_ATTR_OPTIONS_VERSION, "git_attr_options");
if (git_repository_is_bare(repo))
dir_flag = GIT_DIR_FLAG_FALSE;
if (git_attr_path__init(&path, pathname, git_repository_workdir(repo), dir_flag) < 0)
return -1;
if ((error = collect_attr_files(repo, NULL, opts, pathname, &files)) < 0 ||
(error = git_strmap_new(&seen)) < 0)
goto cleanup;
git_vector_foreach(&files, i, file) {
git_attr_file__foreach_matching_rule(file, &path, j, rule) {
git_vector_foreach(&rule->assigns, k, assign) {
/* skip if higher priority assignment was already seen */
if (git_strmap_exists(seen, assign->name))
continue;
if ((error = git_strmap_set(seen, assign->name, assign)) < 0)
goto cleanup;
error = callback(assign->name, assign->value, payload);
if (error) {
git_error_set_after_callback(error);
goto cleanup;
}
}
}
}
cleanup:
git_strmap_free(seen);
release_attr_files(&files);
git_attr_path__free(&path);
return error;
}
static int preload_attr_source(
git_repository *repo,
git_attr_session *attr_session,
git_attr_file_source *source)
{
int error;
git_attr_file *preload = NULL;
if (!source)
return 0;
error = git_attr_cache__get(&preload, repo, attr_session, source,
git_attr_file__parse_buffer, true);
if (!error)
git_attr_file__free(preload);
return error;
}
GIT_INLINE(int) preload_attr_file(
git_repository *repo,
git_attr_session *attr_session,
const char *base,
const char *filename)
{
git_attr_file_source source = { GIT_ATTR_FILE_SOURCE_FILE };
if (!filename)
return 0;
source.base = base;
source.filename = filename;
return preload_attr_source(repo, attr_session, &source);
}
static int system_attr_file(
git_buf *out,
git_attr_session *attr_session)
{
int error;
if (!attr_session) {
error = git_sysdir_find_system_file(out, GIT_ATTR_FILE_SYSTEM);
if (error == GIT_ENOTFOUND)
git_error_clear();
return error;
}
if (!attr_session->init_sysdir) {
error = git_sysdir_find_system_file(&attr_session->sysdir, GIT_ATTR_FILE_SYSTEM);
if (error == GIT_ENOTFOUND)
git_error_clear();
else if (error)
return error;
attr_session->init_sysdir = 1;
}
if (attr_session->sysdir.size == 0)
return GIT_ENOTFOUND;
/* We can safely provide a git_buf with no allocation (asize == 0) to
* a consumer. This allows them to treat this as a regular `git_buf`,
* but their call to `git_buf_dispose` will not attempt to free it.
*/
git_buf_attach_notowned(
out, attr_session->sysdir.ptr, attr_session->sysdir.size);
return 0;
}
static int attr_setup(
git_repository *repo,
git_attr_session *attr_session,
git_attr_options *opts)
{
git_buf system = GIT_BUF_INIT, info = GIT_BUF_INIT;
git_attr_file_source index_source = { GIT_ATTR_FILE_SOURCE_INDEX, NULL, GIT_ATTR_FILE, NULL };
git_attr_file_source head_source = { GIT_ATTR_FILE_SOURCE_HEAD, NULL, GIT_ATTR_FILE, NULL };
git_attr_file_source commit_source = { GIT_ATTR_FILE_SOURCE_COMMIT, NULL, GIT_ATTR_FILE, NULL };
git_index *idx = NULL;
const char *workdir;
int error = 0;
if (attr_session && attr_session->init_setup)
return 0;
if ((error = git_attr_cache__init(repo)) < 0)
return error;
/*
* Preload attribute files that could contain macros so the
* definitions will be available for later file parsing.
*/
if ((error = system_attr_file(&system, attr_session)) < 0 ||
(error = preload_attr_file(repo, attr_session, NULL, system.ptr)) < 0) {
if (error != GIT_ENOTFOUND)
goto out;
error = 0;
}
if ((error = preload_attr_file(repo, attr_session, NULL,
git_repository_attr_cache(repo)->cfg_attr_file)) < 0)
goto out;
if ((error = git_repository_item_path(&info, repo, GIT_REPOSITORY_ITEM_INFO)) < 0 ||
(error = preload_attr_file(repo, attr_session, info.ptr, GIT_ATTR_FILE_INREPO)) < 0) {
if (error != GIT_ENOTFOUND)
goto out;
error = 0;
}
if ((workdir = git_repository_workdir(repo)) != NULL &&
(error = preload_attr_file(repo, attr_session, workdir, GIT_ATTR_FILE)) < 0)
goto out;
if ((error = git_repository_index__weakptr(&idx, repo)) < 0 ||
(error = preload_attr_source(repo, attr_session, &index_source)) < 0)
goto out;
if ((opts && (opts->flags & GIT_ATTR_CHECK_INCLUDE_HEAD) != 0) &&
(error = preload_attr_source(repo, attr_session, &head_source)) < 0)
goto out;
if ((opts && (opts->flags & GIT_ATTR_CHECK_INCLUDE_COMMIT) != 0)) {
#ifndef GIT_DEPRECATE_HARD
if (opts->commit_id)
commit_source.commit_id = opts->commit_id;
else
#endif
commit_source.commit_id = &opts->attr_commit_id;
if ((error = preload_attr_source(repo, attr_session, &commit_source)) < 0)
goto out;
}
if (attr_session)
attr_session->init_setup = 1;
out:
git_buf_dispose(&system);
git_buf_dispose(&info);
return error;
}
int git_attr_add_macro(
git_repository *repo,
const char *name,
const char *values)
{
int error;
git_attr_rule *macro = NULL;
git_pool *pool;
GIT_ASSERT_ARG(repo);
GIT_ASSERT_ARG(name);
if ((error = git_attr_cache__init(repo)) < 0)
return error;
macro = git__calloc(1, sizeof(git_attr_rule));
GIT_ERROR_CHECK_ALLOC(macro);
pool = &git_repository_attr_cache(repo)->pool;
macro->match.pattern = git_pool_strdup(pool, name);
GIT_ERROR_CHECK_ALLOC(macro->match.pattern);
macro->match.length = strlen(macro->match.pattern);
macro->match.flags = GIT_ATTR_FNMATCH_MACRO;
error = git_attr_assignment__parse(repo, pool, ¯o->assigns, &values);
if (!error)
error = git_attr_cache__insert_macro(repo, macro);
if (error < 0)
git_attr_rule__free(macro);
return error;
}
typedef struct {
git_repository *repo;
git_attr_session *attr_session;
git_attr_options *opts;
const char *workdir;
git_index *index;
git_vector *files;
} attr_walk_up_info;
static int attr_decide_sources(
uint32_t flags,
bool has_wd,
bool has_index,
git_attr_file_source_t *srcs)
{
int count = 0;
switch (flags & 0x03) {
case GIT_ATTR_CHECK_FILE_THEN_INDEX:
if (has_wd)
srcs[count++] = GIT_ATTR_FILE_SOURCE_FILE;
if (has_index)
srcs[count++] = GIT_ATTR_FILE_SOURCE_INDEX;
break;
case GIT_ATTR_CHECK_INDEX_THEN_FILE:
if (has_index)
srcs[count++] = GIT_ATTR_FILE_SOURCE_INDEX;
if (has_wd)
srcs[count++] = GIT_ATTR_FILE_SOURCE_FILE;
break;
case GIT_ATTR_CHECK_INDEX_ONLY:
if (has_index)
srcs[count++] = GIT_ATTR_FILE_SOURCE_INDEX;
break;
}
if ((flags & GIT_ATTR_CHECK_INCLUDE_HEAD) != 0)
srcs[count++] = GIT_ATTR_FILE_SOURCE_HEAD;
if ((flags & GIT_ATTR_CHECK_INCLUDE_COMMIT) != 0)
srcs[count++] = GIT_ATTR_FILE_SOURCE_COMMIT;
return count;
}
static int push_attr_source(
git_repository *repo,
git_attr_session *attr_session,
git_vector *list,
git_attr_file_source *source,
bool allow_macros)
{
int error = 0;
git_attr_file *file = NULL;
error = git_attr_cache__get(&file, repo, attr_session,
source,
git_attr_file__parse_buffer,
allow_macros);
if (error < 0)
return error;
if (file != NULL) {
if ((error = git_vector_insert(list, file)) < 0)
git_attr_file__free(file);
}
return error;
}
GIT_INLINE(int) push_attr_file(
git_repository *repo,
git_attr_session *attr_session,
git_vector *list,
const char *base,
const char *filename)
{
git_attr_file_source source = { GIT_ATTR_FILE_SOURCE_FILE, base, filename };
return push_attr_source(repo, attr_session, list, &source, true);
}
static int push_one_attr(void *ref, const char *path)
{
attr_walk_up_info *info = (attr_walk_up_info *)ref;
git_attr_file_source_t src[GIT_ATTR_FILE_NUM_SOURCES];
int error = 0, n_src, i;
bool allow_macros;
n_src = attr_decide_sources(info->opts ? info->opts->flags : 0,
info->workdir != NULL,
info->index != NULL,
src);
allow_macros = info->workdir ? !strcmp(info->workdir, path) : false;
for (i = 0; !error && i < n_src; ++i) {
git_attr_file_source source = { src[i], path, GIT_ATTR_FILE };
if (src[i] == GIT_ATTR_FILE_SOURCE_COMMIT && info->opts) {
#ifndef GIT_DEPRECATE_HARD
if (info->opts->commit_id)
source.commit_id = info->opts->commit_id;
else
#endif
source.commit_id = &info->opts->attr_commit_id;
}
error = push_attr_source(info->repo, info->attr_session, info->files,
&source, allow_macros);
}
return error;
}
static void release_attr_files(git_vector *files)
{
size_t i;
git_attr_file *file;
git_vector_foreach(files, i, file) {
git_attr_file__free(file);
files->contents[i] = NULL;
}
git_vector_free(files);
}
static int collect_attr_files(
git_repository *repo,
git_attr_session *attr_session,
git_attr_options *opts,
const char *path,
git_vector *files)
{
int error = 0;
git_buf dir = GIT_BUF_INIT, attrfile = GIT_BUF_INIT;
const char *workdir = git_repository_workdir(repo);
attr_walk_up_info info = { NULL };
GIT_ASSERT(!git_path_is_absolute(path));
if ((error = attr_setup(repo, attr_session, opts)) < 0)
return error;
/* Resolve path in a non-bare repo */
if (workdir != NULL) {
if (!(error = git_repository_workdir_path(&dir, repo, path)))
error = git_path_find_dir(&dir);
}
else {
error = git_path_dirname_r(&dir, path);
}
if (error < 0)
goto cleanup;
/* in precendence order highest to lowest:
* - $GIT_DIR/info/attributes
* - path components with .gitattributes
* - config core.attributesfile
* - $GIT_PREFIX/etc/gitattributes
*/
if ((error = git_repository_item_path(&attrfile, repo, GIT_REPOSITORY_ITEM_INFO)) < 0 ||
(error = push_attr_file(repo, attr_session, files, attrfile.ptr, GIT_ATTR_FILE_INREPO)) < 0) {
if (error != GIT_ENOTFOUND)
goto cleanup;
}
info.repo = repo;
info.attr_session = attr_session;
info.opts = opts;
info.workdir = workdir;
if (git_repository_index__weakptr(&info.index, repo) < 0)
git_error_clear(); /* no error even if there is no index */
info.files = files;
if (!strcmp(dir.ptr, "."))
error = push_one_attr(&info, "");
else
error = git_path_walk_up(&dir, workdir, push_one_attr, &info);
if (error < 0)
goto cleanup;
if (git_repository_attr_cache(repo)->cfg_attr_file != NULL) {
error = push_attr_file(repo, attr_session, files, NULL, git_repository_attr_cache(repo)->cfg_attr_file);
if (error < 0)
goto cleanup;
}
if (!opts || (opts->flags & GIT_ATTR_CHECK_NO_SYSTEM) == 0) {
error = system_attr_file(&dir, attr_session);
if (!error)
error = push_attr_file(repo, attr_session, files, NULL, dir.ptr);
else if (error == GIT_ENOTFOUND)
error = 0;
}
cleanup:
if (error < 0)
release_attr_files(files);
git_buf_dispose(&attrfile);
git_buf_dispose(&dir);
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/oidarray.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_oidarray_h__
#define INCLUDE_oidarray_h__
#include "common.h"
#include "git2/oidarray.h"
#include "array.h"
typedef git_array_t(git_oid) git_array_oid_t;
extern void git_oidarray__reverse(git_oidarray *arr);
extern void git_oidarray__from_array(git_oidarray *arr, git_array_oid_t *array);
#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/reflog.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_reflog_h__
#define INCLUDE_reflog_h__
#include "common.h"
#include "git2/reflog.h"
#include "vector.h"
#define GIT_REFLOG_DIR "logs/"
#define GIT_REFLOG_DIR_MODE 0777
#define GIT_REFLOG_FILE_MODE 0666
#define GIT_REFLOG_SIZE_MIN (2*GIT_OID_HEXSZ+2+17)
struct git_reflog_entry {
git_oid oid_old;
git_oid oid_cur;
git_signature *committer;
char *msg;
};
struct git_reflog {
git_refdb *db;
char *ref_name;
git_vector entries;
};
GIT_INLINE(size_t) reflog_inverse_index(size_t idx, size_t total)
{
return (total - 1) - idx;
}
#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/index.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_index_h__
#define INCLUDE_index_h__
#include "common.h"
#include "futils.h"
#include "filebuf.h"
#include "vector.h"
#include "idxmap.h"
#include "tree-cache.h"
#include "git2/odb.h"
#include "git2/index.h"
#define GIT_INDEX_FILE "index"
#define GIT_INDEX_FILE_MODE 0666
extern bool git_index__enforce_unsaved_safety;
struct git_index {
git_refcount rc;
char *index_file_path;
git_futils_filestamp stamp;
git_oid checksum; /* checksum at the end of the file */
git_vector entries;
git_idxmap *entries_map;
git_vector deleted; /* deleted entries if readers > 0 */
git_atomic32 readers; /* number of active iterators */
unsigned int on_disk:1;
unsigned int ignore_case:1;
unsigned int distrust_filemode:1;
unsigned int no_symlinks:1;
unsigned int dirty:1; /* whether we have unsaved changes */
git_tree_cache *tree;
git_pool tree_pool;
git_vector names;
git_vector reuc;
git_vector_cmp entries_cmp_path;
git_vector_cmp entries_search;
git_vector_cmp entries_search_path;
git_vector_cmp reuc_search;
unsigned int version;
};
struct git_index_iterator {
git_index *index;
git_vector snap;
size_t cur;
};
struct git_index_conflict_iterator {
git_index *index;
size_t cur;
};
extern void git_index_entry__init_from_stat(
git_index_entry *entry, struct stat *st, bool trust_mode);
/* Index entry comparison functions for array sorting */
extern int git_index_entry_cmp(const void *a, const void *b);
extern int git_index_entry_icmp(const void *a, const void *b);
/* Index entry search functions for search using a search spec */
extern int git_index_entry_srch(const void *a, const void *b);
extern int git_index_entry_isrch(const void *a, const void *b);
/* Index time handling functions */
GIT_INLINE(bool) git_index_time_eq(const git_index_time *one, const git_index_time *two)
{
if (one->seconds != two->seconds)
return false;
#ifdef GIT_USE_NSEC
if (one->nanoseconds != two->nanoseconds)
return false;
#endif
return true;
}
/*
* Test if the given index time is newer than the given existing index entry.
* If the timestamps are exactly equivalent, then the given index time is
* considered "racily newer" than the existing index entry.
*/
GIT_INLINE(bool) git_index_entry_newer_than_index(
const git_index_entry *entry, git_index *index)
{
/* If we never read the index, we can't have this race either */
if (!index || index->stamp.mtime.tv_sec == 0)
return false;
/* If the timestamp is the same or newer than the index, it's racy */
#if defined(GIT_USE_NSEC)
if ((int32_t)index->stamp.mtime.tv_sec < entry->mtime.seconds)
return true;
else if ((int32_t)index->stamp.mtime.tv_sec > entry->mtime.seconds)
return false;
else
return (uint32_t)index->stamp.mtime.tv_nsec <= entry->mtime.nanoseconds;
#else
return ((int32_t)index->stamp.mtime.tv_sec) <= entry->mtime.seconds;
#endif
}
/* Search index for `path`, returning GIT_ENOTFOUND if it does not exist
* (but not setting an error message).
*
* `at_pos` is set to the position where it is or would be inserted.
* Pass `path_len` as strlen of path or 0 to call strlen internally.
*/
extern int git_index__find_pos(
size_t *at_pos, git_index *index, const char *path, size_t path_len, int stage);
extern int git_index__fill(git_index *index, const git_vector *source_entries);
extern void git_index__set_ignore_case(git_index *index, bool ignore_case);
extern unsigned int git_index__create_mode(unsigned int mode);
GIT_INLINE(const git_futils_filestamp *) git_index__filestamp(git_index *index)
{
return &index->stamp;
}
extern int git_index__changed_relative_to(git_index *index, const git_oid *checksum);
/* Copy the current entries vector *and* increment the index refcount.
* Call `git_index__release_snapshot` when done.
*/
extern int git_index_snapshot_new(git_vector *snap, git_index *index);
extern void git_index_snapshot_release(git_vector *snap, git_index *index);
/* Allow searching in a snapshot; entries must already be sorted! */
extern int git_index_snapshot_find(
size_t *at_pos, git_vector *snap, git_vector_cmp entry_srch,
const char *path, size_t path_len, int stage);
/* Replace an index with a new index */
int git_index_read_index(git_index *index, const git_index *new_index);
GIT_INLINE(int) git_index_is_dirty(git_index *index)
{
return index->dirty;
}
extern int git_index_read_safely(git_index *index);
typedef struct {
git_index *index;
git_filebuf file;
unsigned int should_write:1;
} git_indexwriter;
#define GIT_INDEXWRITER_INIT { NULL, GIT_FILEBUF_INIT }
/* Lock the index for eventual writing. */
extern int git_indexwriter_init(git_indexwriter *writer, git_index *index);
/* Lock the index for eventual writing by a repository operation: a merge,
* revert, cherry-pick or a rebase. Note that the given checkout strategy
* will be updated for the operation's use so that checkout will not write
* the index.
*/
extern int git_indexwriter_init_for_operation(
git_indexwriter *writer,
git_repository *repo,
unsigned int *checkout_strategy);
/* Write the index and unlock it. */
extern int git_indexwriter_commit(git_indexwriter *writer);
/* Cleanup an index writing session, unlocking the file (if it is still
* locked and freeing any data structures.
*/
extern void git_indexwriter_cleanup(git_indexwriter *writer);
#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/fetch.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 "fetch.h"
#include "git2/oid.h"
#include "git2/refs.h"
#include "git2/revwalk.h"
#include "git2/transport.h"
#include "remote.h"
#include "refspec.h"
#include "pack.h"
#include "netops.h"
#include "repository.h"
#include "refs.h"
static int maybe_want(git_remote *remote, git_remote_head *head, git_odb *odb, git_refspec *tagspec, git_remote_autotag_option_t tagopt)
{
int match = 0, valid;
if (git_reference_name_is_valid(&valid, head->name) < 0)
return -1;
if (!valid)
return 0;
if (tagopt == GIT_REMOTE_DOWNLOAD_TAGS_ALL) {
/*
* If tagopt is --tags, always request tags
* in addition to the remote's refspecs
*/
if (git_refspec_src_matches(tagspec, head->name))
match = 1;
}
if (!match && git_remote__matching_refspec(remote, head->name))
match = 1;
if (!match)
return 0;
/* If we have the object, mark it so we don't ask for it */
if (git_odb_exists(odb, &head->oid)) {
head->local = 1;
}
else
remote->need_pack = 1;
return git_vector_insert(&remote->refs, head);
}
static int filter_wants(git_remote *remote, const git_fetch_options *opts)
{
git_remote_head **heads;
git_refspec tagspec, head;
int error = 0;
git_odb *odb;
size_t i, heads_len;
git_remote_autotag_option_t tagopt = remote->download_tags;
if (opts && opts->download_tags != GIT_REMOTE_DOWNLOAD_TAGS_UNSPECIFIED)
tagopt = opts->download_tags;
git_vector_clear(&remote->refs);
if ((error = git_refspec__parse(&tagspec, GIT_REFSPEC_TAGS, true)) < 0)
return error;
/*
* The fetch refspec can be NULL, and what this means is that the
* user didn't specify one. This is fine, as it means that we're
* not interested in any particular branch but just the remote's
* HEAD, which will be stored in FETCH_HEAD after the fetch.
*/
if (remote->active_refspecs.length == 0) {
if ((error = git_refspec__parse(&head, "HEAD", true)) < 0)
goto cleanup;
error = git_refspec__dwim_one(&remote->active_refspecs, &head, &remote->refs);
git_refspec__dispose(&head);
if (error < 0)
goto cleanup;
}
if (git_repository_odb__weakptr(&odb, remote->repo) < 0)
goto cleanup;
if (git_remote_ls((const git_remote_head ***)&heads, &heads_len, remote) < 0)
goto cleanup;
for (i = 0; i < heads_len; i++) {
if ((error = maybe_want(remote, heads[i], odb, &tagspec, tagopt)) < 0)
break;
}
cleanup:
git_refspec__dispose(&tagspec);
return error;
}
/*
* In this first version, we push all our refs in and start sending
* them out. When we get an ACK we hide that commit and continue
* traversing until we're done
*/
int git_fetch_negotiate(git_remote *remote, const git_fetch_options *opts)
{
git_transport *t = remote->transport;
remote->need_pack = 0;
if (filter_wants(remote, opts) < 0) {
git_error_set(GIT_ERROR_NET, "failed to filter the reference list for wants");
return -1;
}
/* Don't try to negotiate when we don't want anything */
if (!remote->need_pack)
return 0;
/*
* Now we have everything set up so we can start tell the
* server what we want and what we have.
*/
return t->negotiate_fetch(t,
remote->repo,
(const git_remote_head * const *)remote->refs.contents,
remote->refs.length);
}
int git_fetch_download_pack(git_remote *remote, const git_remote_callbacks *callbacks)
{
git_transport *t = remote->transport;
git_indexer_progress_cb progress = NULL;
void *payload = NULL;
if (!remote->need_pack)
return 0;
if (callbacks) {
progress = callbacks->transfer_progress;
payload = callbacks->payload;
}
return t->download_pack(t, remote->repo, &remote->stats, progress, payload);
}
int git_fetch_options_init(git_fetch_options *opts, unsigned int version)
{
GIT_INIT_STRUCTURE_FROM_TEMPLATE(
opts, version, git_fetch_options, GIT_FETCH_OPTIONS_INIT);
return 0;
}
#ifndef GIT_DEPRECATE_HARD
int git_fetch_init_options(git_fetch_options *opts, unsigned int version)
{
return git_fetch_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/proxy.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 "proxy.h"
#include "git2/proxy.h"
int git_proxy_options_init(git_proxy_options *opts, unsigned int version)
{
GIT_INIT_STRUCTURE_FROM_TEMPLATE(
opts, version, git_proxy_options, GIT_PROXY_OPTIONS_INIT);
return 0;
}
#ifndef GIT_DEPRECATE_HARD
int git_proxy_init_options(git_proxy_options *opts, unsigned int version)
{
return git_proxy_options_init(opts, version);
}
#endif
int git_proxy_options_dup(git_proxy_options *tgt, const git_proxy_options *src)
{
if (!src) {
git_proxy_options_init(tgt, GIT_PROXY_OPTIONS_VERSION);
return 0;
}
memcpy(tgt, src, sizeof(git_proxy_options));
if (src->url) {
tgt->url = git__strdup(src->url);
GIT_ERROR_CHECK_ALLOC(tgt->url);
}
return 0;
}
void git_proxy_options_clear(git_proxy_options *opts)
{
git__free((char *) opts->url);
opts->url = 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/mwindow.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 "mwindow.h"
#include "vector.h"
#include "futils.h"
#include "map.h"
#include "runtime.h"
#include "strmap.h"
#include "pack.h"
#define DEFAULT_WINDOW_SIZE \
(sizeof(void*) >= 8 \
? 1 * 1024 * 1024 * 1024 \
: 32 * 1024 * 1024)
#define DEFAULT_MAPPED_LIMIT \
((1024 * 1024) * (sizeof(void*) >= 8 ? UINT64_C(8192) : UINT64_C(256)))
/* default is unlimited */
#define DEFAULT_FILE_LIMIT 0
size_t git_mwindow__window_size = DEFAULT_WINDOW_SIZE;
size_t git_mwindow__mapped_limit = DEFAULT_MAPPED_LIMIT;
size_t git_mwindow__file_limit = DEFAULT_FILE_LIMIT;
/* Mutex to control access to `git_mwindow__mem_ctl` and `git__pack_cache`. */
git_mutex git__mwindow_mutex;
/* Whenever you want to read or modify this, grab `git__mwindow_mutex` */
git_mwindow_ctl git_mwindow__mem_ctl;
/* Global list of mwindow files, to open packs once across repos */
git_strmap *git__pack_cache = NULL;
static void git_mwindow_global_shutdown(void)
{
git_strmap *tmp = git__pack_cache;
git_mutex_free(&git__mwindow_mutex);
git__pack_cache = NULL;
git_strmap_free(tmp);
}
int git_mwindow_global_init(void)
{
int error;
GIT_ASSERT(!git__pack_cache);
if ((error = git_mutex_init(&git__mwindow_mutex)) < 0 ||
(error = git_strmap_new(&git__pack_cache)) < 0)
return error;
return git_runtime_shutdown_register(git_mwindow_global_shutdown);
}
int git_mwindow_get_pack(struct git_pack_file **out, const char *path)
{
struct git_pack_file *pack;
char *packname;
int error;
if ((error = git_packfile__name(&packname, path)) < 0)
return error;
if (git_mutex_lock(&git__mwindow_mutex) < 0) {
git_error_set(GIT_ERROR_OS, "failed to lock mwindow mutex");
return -1;
}
pack = git_strmap_get(git__pack_cache, packname);
git__free(packname);
if (pack != NULL) {
git_atomic32_inc(&pack->refcount);
git_mutex_unlock(&git__mwindow_mutex);
*out = pack;
return 0;
}
/* If we didn't find it, we need to create it */
if ((error = git_packfile_alloc(&pack, path)) < 0) {
git_mutex_unlock(&git__mwindow_mutex);
return error;
}
git_atomic32_inc(&pack->refcount);
error = git_strmap_set(git__pack_cache, pack->pack_name, pack);
git_mutex_unlock(&git__mwindow_mutex);
if (error < 0) {
git_packfile_free(pack, false);
return error;
}
*out = pack;
return 0;
}
int git_mwindow_put_pack(struct git_pack_file *pack)
{
int count, error;
struct git_pack_file *pack_to_delete = NULL;
if ((error = git_mutex_lock(&git__mwindow_mutex)) < 0)
return error;
/* put before get would be a corrupted state */
GIT_ASSERT(git__pack_cache);
/* if we cannot find it, the state is corrupted */
GIT_ASSERT(git_strmap_exists(git__pack_cache, pack->pack_name));
count = git_atomic32_dec(&pack->refcount);
if (count == 0) {
git_strmap_delete(git__pack_cache, pack->pack_name);
pack_to_delete = pack;
}
git_mutex_unlock(&git__mwindow_mutex);
git_packfile_free(pack_to_delete, false);
return 0;
}
/*
* Free all the windows in a sequence, typically because we're done
* with the file. Needs to hold the git__mwindow_mutex.
*/
static int git_mwindow_free_all_locked(git_mwindow_file *mwf)
{
git_mwindow_ctl *ctl = &git_mwindow__mem_ctl;
size_t i;
/*
* Remove these windows from the global list
*/
for (i = 0; i < ctl->windowfiles.length; ++i){
if (git_vector_get(&ctl->windowfiles, i) == mwf) {
git_vector_remove(&ctl->windowfiles, i);
break;
}
}
if (ctl->windowfiles.length == 0) {
git_vector_free(&ctl->windowfiles);
ctl->windowfiles.contents = NULL;
}
while (mwf->windows) {
git_mwindow *w = mwf->windows;
GIT_ASSERT(w->inuse_cnt == 0);
ctl->mapped -= w->window_map.len;
ctl->open_windows--;
git_futils_mmap_free(&w->window_map);
mwf->windows = w->next;
git__free(w);
}
return 0;
}
int git_mwindow_free_all(git_mwindow_file *mwf)
{
int error;
if (git_mutex_lock(&git__mwindow_mutex)) {
git_error_set(GIT_ERROR_THREAD, "unable to lock mwindow mutex");
return -1;
}
error = git_mwindow_free_all_locked(mwf);
git_mutex_unlock(&git__mwindow_mutex);
return error;
}
/*
* Check if a window 'win' contains the address 'offset'
*/
int git_mwindow_contains(git_mwindow *win, off64_t offset)
{
off64_t win_off = win->offset;
return win_off <= offset
&& offset <= (off64_t)(win_off + win->window_map.len);
}
#define GIT_MWINDOW__LRU -1
#define GIT_MWINDOW__MRU 1
/*
* Find the least- or most-recently-used window in a file that is not currently
* being used. The 'only_unused' flag controls whether the caller requires the
* file to only have unused windows. If '*out_window' is non-null, it is used as
* a starting point for the comparison.
*
* Returns whether such a window was found in the file.
*/
static bool git_mwindow_scan_recently_used(
git_mwindow_file *mwf,
git_mwindow **out_window,
git_mwindow **out_last,
bool only_unused,
int comparison_sign)
{
git_mwindow *w, *w_last;
git_mwindow *lru_window = NULL, *lru_last = NULL;
bool found = false;
GIT_ASSERT_ARG(mwf);
GIT_ASSERT_ARG(out_window);
lru_window = *out_window;
if (out_last)
lru_last = *out_last;
for (w_last = NULL, w = mwf->windows; w; w_last = w, w = w->next) {
if (w->inuse_cnt) {
if (only_unused)
return false;
/* This window is currently being used. Skip it. */
continue;
}
/*
* If the current one is more (or less) recent than the last one,
* store it in the output parameter. If lru_window is NULL,
* it's the first loop, so store it as well.
*/
if (!lru_window ||
(comparison_sign == GIT_MWINDOW__LRU && lru_window->last_used > w->last_used) ||
(comparison_sign == GIT_MWINDOW__MRU && lru_window->last_used < w->last_used)) {
lru_window = w;
lru_last = w_last;
found = true;
}
}
if (!found)
return false;
*out_window = lru_window;
if (out_last)
*out_last = lru_last;
return true;
}
/*
* Close the least recently used window (that is currently not being used) out
* of all the files. Called under lock from new_window_locked.
*/
static int git_mwindow_close_lru_window_locked(void)
{
git_mwindow_ctl *ctl = &git_mwindow__mem_ctl;
git_mwindow_file *cur;
size_t i;
git_mwindow *lru_window = NULL, *lru_last = NULL, **list = NULL;
git_vector_foreach(&ctl->windowfiles, i, cur) {
if (git_mwindow_scan_recently_used(
cur, &lru_window, &lru_last, false, GIT_MWINDOW__LRU)) {
list = &cur->windows;
}
}
if (!lru_window) {
git_error_set(GIT_ERROR_OS, "failed to close memory window; couldn't find LRU");
return -1;
}
ctl->mapped -= lru_window->window_map.len;
git_futils_mmap_free(&lru_window->window_map);
if (lru_last)
lru_last->next = lru_window->next;
else
*list = lru_window->next;
git__free(lru_window);
ctl->open_windows--;
return 0;
}
/*
* Finds the file that does not have any open windows AND whose
* most-recently-used window is the least-recently used one across all
* currently open files.
*
* Called under lock from new_window_locked.
*/
static int git_mwindow_find_lru_file_locked(git_mwindow_file **out)
{
git_mwindow_ctl *ctl = &git_mwindow__mem_ctl;
git_mwindow_file *lru_file = NULL, *current_file = NULL;
git_mwindow *lru_window = NULL;
size_t i;
git_vector_foreach(&ctl->windowfiles, i, current_file) {
git_mwindow *mru_window = NULL;
if (!git_mwindow_scan_recently_used(
current_file, &mru_window, NULL, true, GIT_MWINDOW__MRU)) {
continue;
}
if (!lru_window || lru_window->last_used > mru_window->last_used) {
lru_window = mru_window;
lru_file = current_file;
}
}
if (!lru_file) {
git_error_set(GIT_ERROR_OS, "failed to close memory window file; couldn't find LRU");
return -1;
}
*out = lru_file;
return 0;
}
/* This gets called under lock from git_mwindow_open */
static git_mwindow *new_window_locked(
git_file fd,
off64_t size,
off64_t offset)
{
git_mwindow_ctl *ctl = &git_mwindow__mem_ctl;
size_t walign = git_mwindow__window_size / 2;
off64_t len;
git_mwindow *w;
w = git__calloc(1, sizeof(*w));
if (w == NULL)
return NULL;
w->offset = (offset / walign) * walign;
len = size - w->offset;
if (len > (off64_t)git_mwindow__window_size)
len = (off64_t)git_mwindow__window_size;
ctl->mapped += (size_t)len;
while (git_mwindow__mapped_limit < ctl->mapped &&
git_mwindow_close_lru_window_locked() == 0) /* nop */;
/*
* We treat `mapped_limit` as a soft limit. If we can't find a
* window to close and are above the limit, we still mmap the new
* window.
*/
if (git_futils_mmap_ro(&w->window_map, fd, w->offset, (size_t)len) < 0) {
/*
* The first error might be down to memory fragmentation even if
* we're below our soft limits, so free up what we can and try again.
*/
while (git_mwindow_close_lru_window_locked() == 0)
/* nop */;
if (git_futils_mmap_ro(&w->window_map, fd, w->offset, (size_t)len) < 0) {
git__free(w);
return NULL;
}
}
ctl->mmap_calls++;
ctl->open_windows++;
if (ctl->mapped > ctl->peak_mapped)
ctl->peak_mapped = ctl->mapped;
if (ctl->open_windows > ctl->peak_open_windows)
ctl->peak_open_windows = ctl->open_windows;
return w;
}
/*
* Open a new window, closing the least recenty used until we have
* enough space. Don't forget to add it to your list
*/
unsigned char *git_mwindow_open(
git_mwindow_file *mwf,
git_mwindow **cursor,
off64_t offset,
size_t extra,
unsigned int *left)
{
git_mwindow_ctl *ctl = &git_mwindow__mem_ctl;
git_mwindow *w = *cursor;
if (git_mutex_lock(&git__mwindow_mutex)) {
git_error_set(GIT_ERROR_THREAD, "unable to lock mwindow mutex");
return NULL;
}
if (!w || !(git_mwindow_contains(w, offset) && git_mwindow_contains(w, offset + extra))) {
if (w) {
w->inuse_cnt--;
}
for (w = mwf->windows; w; w = w->next) {
if (git_mwindow_contains(w, offset) &&
git_mwindow_contains(w, offset + extra))
break;
}
/*
* If there isn't a suitable window, we need to create a new
* one.
*/
if (!w) {
w = new_window_locked(mwf->fd, mwf->size, offset);
if (w == NULL) {
git_mutex_unlock(&git__mwindow_mutex);
return NULL;
}
w->next = mwf->windows;
mwf->windows = w;
}
}
/* If we changed w, store it in the cursor */
if (w != *cursor) {
w->last_used = ctl->used_ctr++;
w->inuse_cnt++;
*cursor = w;
}
offset -= w->offset;
if (left)
*left = (unsigned int)(w->window_map.len - offset);
git_mutex_unlock(&git__mwindow_mutex);
return (unsigned char *) w->window_map.data + offset;
}
int git_mwindow_file_register(git_mwindow_file *mwf)
{
git_vector closed_files = GIT_VECTOR_INIT;
git_mwindow_ctl *ctl = &git_mwindow__mem_ctl;
int error;
size_t i;
git_mwindow_file *closed_file = NULL;
if (git_mutex_lock(&git__mwindow_mutex)) {
git_error_set(GIT_ERROR_THREAD, "unable to lock mwindow mutex");
return -1;
}
if (ctl->windowfiles.length == 0 &&
(error = git_vector_init(&ctl->windowfiles, 8, NULL)) < 0) {
git_mutex_unlock(&git__mwindow_mutex);
goto cleanup;
}
if (git_mwindow__file_limit) {
git_mwindow_file *lru_file;
while (git_mwindow__file_limit <= ctl->windowfiles.length &&
git_mwindow_find_lru_file_locked(&lru_file) == 0) {
if ((error = git_vector_insert(&closed_files, lru_file)) < 0) {
/*
* Exceeding the file limit seems preferrable to being open to
* data races that can end up corrupting the heap.
*/
break;
}
git_mwindow_free_all_locked(lru_file);
}
}
error = git_vector_insert(&ctl->windowfiles, mwf);
git_mutex_unlock(&git__mwindow_mutex);
if (error < 0)
goto cleanup;
/*
* Once we have released the global windowfiles lock, we can close each
* individual file. Before doing so, acquire that file's lock to avoid
* closing a file that is currently being used.
*/
git_vector_foreach(&closed_files, i, closed_file) {
error = git_mutex_lock(&closed_file->lock);
if (error < 0)
continue;
p_close(closed_file->fd);
closed_file->fd = -1;
git_mutex_unlock(&closed_file->lock);
}
cleanup:
git_vector_free(&closed_files);
return error;
}
void git_mwindow_file_deregister(git_mwindow_file *mwf)
{
git_mwindow_ctl *ctl = &git_mwindow__mem_ctl;
git_mwindow_file *cur;
size_t i;
if (git_mutex_lock(&git__mwindow_mutex))
return;
git_vector_foreach(&ctl->windowfiles, i, cur) {
if (cur == mwf) {
git_vector_remove(&ctl->windowfiles, i);
git_mutex_unlock(&git__mwindow_mutex);
return;
}
}
git_mutex_unlock(&git__mwindow_mutex);
}
void git_mwindow_close(git_mwindow **window)
{
git_mwindow *w = *window;
if (w) {
if (git_mutex_lock(&git__mwindow_mutex)) {
git_error_set(GIT_ERROR_THREAD, "unable to lock mwindow mutex");
return;
}
w->inuse_cnt--;
git_mutex_unlock(&git__mwindow_mutex);
*window = 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/revparse.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 "tree.h"
#include "refdb.h"
#include "regexp.h"
#include "git2.h"
static int maybe_sha_or_abbrev(git_object **out, git_repository *repo, const char *spec, size_t speclen)
{
git_oid oid;
if (git_oid_fromstrn(&oid, spec, speclen) < 0)
return GIT_ENOTFOUND;
return git_object_lookup_prefix(out, repo, &oid, speclen, GIT_OBJECT_ANY);
}
static int maybe_sha(git_object **out, git_repository *repo, const char *spec)
{
size_t speclen = strlen(spec);
if (speclen != GIT_OID_HEXSZ)
return GIT_ENOTFOUND;
return maybe_sha_or_abbrev(out, repo, spec, speclen);
}
static int maybe_abbrev(git_object **out, git_repository *repo, const char *spec)
{
size_t speclen = strlen(spec);
return maybe_sha_or_abbrev(out, repo, spec, speclen);
}
static int build_regex(git_regexp *regex, const char *pattern)
{
int error;
if (*pattern == '\0') {
git_error_set(GIT_ERROR_REGEX, "empty pattern");
return GIT_EINVALIDSPEC;
}
error = git_regexp_compile(regex, pattern, 0);
if (!error)
return 0;
git_regexp_dispose(regex);
return error;
}
static int maybe_describe(git_object**out, git_repository *repo, const char *spec)
{
const char *substr;
int error;
git_regexp regex;
substr = strstr(spec, "-g");
if (substr == NULL)
return GIT_ENOTFOUND;
if (build_regex(®ex, ".+-[0-9]+-g[0-9a-fA-F]+") < 0)
return -1;
error = git_regexp_match(®ex, spec);
git_regexp_dispose(®ex);
if (error)
return GIT_ENOTFOUND;
return maybe_abbrev(out, repo, substr+2);
}
static int revparse_lookup_object(
git_object **object_out,
git_reference **reference_out,
git_repository *repo,
const char *spec)
{
int error;
git_reference *ref;
if ((error = maybe_sha(object_out, repo, spec)) != GIT_ENOTFOUND)
return error;
error = git_reference_dwim(&ref, repo, spec);
if (!error) {
error = git_object_lookup(
object_out, repo, git_reference_target(ref), GIT_OBJECT_ANY);
if (!error)
*reference_out = ref;
return error;
}
if (error != GIT_ENOTFOUND)
return error;
if ((strlen(spec) < GIT_OID_HEXSZ) &&
((error = maybe_abbrev(object_out, repo, spec)) != GIT_ENOTFOUND))
return error;
if ((error = maybe_describe(object_out, repo, spec)) != GIT_ENOTFOUND)
return error;
git_error_set(GIT_ERROR_REFERENCE, "revspec '%s' not found", spec);
return GIT_ENOTFOUND;
}
static int try_parse_numeric(int *n, const char *curly_braces_content)
{
int32_t content;
const char *end_ptr;
if (git__strntol32(&content, curly_braces_content, strlen(curly_braces_content),
&end_ptr, 10) < 0)
return -1;
if (*end_ptr != '\0')
return -1;
*n = (int)content;
return 0;
}
static int retrieve_previously_checked_out_branch_or_revision(git_object **out, git_reference **base_ref, git_repository *repo, const char *identifier, size_t position)
{
git_reference *ref = NULL;
git_reflog *reflog = NULL;
git_regexp preg;
int error = -1;
size_t i, numentries, cur;
const git_reflog_entry *entry;
const char *msg;
git_buf buf = GIT_BUF_INIT;
cur = position;
if (*identifier != '\0' || *base_ref != NULL)
return GIT_EINVALIDSPEC;
if (build_regex(&preg, "checkout: moving from (.*) to .*") < 0)
return -1;
if (git_reference_lookup(&ref, repo, GIT_HEAD_FILE) < 0)
goto cleanup;
if (git_reflog_read(&reflog, repo, GIT_HEAD_FILE) < 0)
goto cleanup;
numentries = git_reflog_entrycount(reflog);
for (i = 0; i < numentries; i++) {
git_regmatch regexmatches[2];
entry = git_reflog_entry_byindex(reflog, i);
msg = git_reflog_entry_message(entry);
if (!msg)
continue;
if (git_regexp_search(&preg, msg, 2, regexmatches) < 0)
continue;
cur--;
if (cur > 0)
continue;
if ((git_buf_put(&buf, msg+regexmatches[1].start, regexmatches[1].end - regexmatches[1].start)) < 0)
goto cleanup;
if ((error = git_reference_dwim(base_ref, repo, git_buf_cstr(&buf))) == 0)
goto cleanup;
if (error < 0 && error != GIT_ENOTFOUND)
goto cleanup;
error = maybe_abbrev(out, repo, git_buf_cstr(&buf));
goto cleanup;
}
error = GIT_ENOTFOUND;
cleanup:
git_reference_free(ref);
git_buf_dispose(&buf);
git_regexp_dispose(&preg);
git_reflog_free(reflog);
return error;
}
static int retrieve_oid_from_reflog(git_oid *oid, git_reference *ref, size_t identifier)
{
git_reflog *reflog;
size_t numentries;
const git_reflog_entry *entry;
bool search_by_pos = (identifier <= 100000000);
if (git_reflog_read(&reflog, git_reference_owner(ref), git_reference_name(ref)) < 0)
return -1;
numentries = git_reflog_entrycount(reflog);
if (search_by_pos) {
if (numentries < identifier + 1)
goto notfound;
entry = git_reflog_entry_byindex(reflog, identifier);
git_oid_cpy(oid, git_reflog_entry_id_new(entry));
} else {
size_t i;
git_time commit_time;
for (i = 0; i < numentries; i++) {
entry = git_reflog_entry_byindex(reflog, i);
commit_time = git_reflog_entry_committer(entry)->when;
if (commit_time.time > (git_time_t)identifier)
continue;
git_oid_cpy(oid, git_reflog_entry_id_new(entry));
break;
}
if (i == numentries)
goto notfound;
}
git_reflog_free(reflog);
return 0;
notfound:
git_error_set(
GIT_ERROR_REFERENCE,
"reflog for '%s' has only %"PRIuZ" entries, asked for %"PRIuZ,
git_reference_name(ref), numentries, identifier);
git_reflog_free(reflog);
return GIT_ENOTFOUND;
}
static int retrieve_revobject_from_reflog(git_object **out, git_reference **base_ref, git_repository *repo, const char *identifier, size_t position)
{
git_reference *ref;
git_oid oid;
int error = -1;
if (*base_ref == NULL) {
if ((error = git_reference_dwim(&ref, repo, identifier)) < 0)
return error;
} else {
ref = *base_ref;
*base_ref = NULL;
}
if (position == 0) {
error = git_object_lookup(out, repo, git_reference_target(ref), GIT_OBJECT_ANY);
goto cleanup;
}
if ((error = retrieve_oid_from_reflog(&oid, ref, position)) < 0)
goto cleanup;
error = git_object_lookup(out, repo, &oid, GIT_OBJECT_ANY);
cleanup:
git_reference_free(ref);
return error;
}
static int retrieve_remote_tracking_reference(git_reference **base_ref, const char *identifier, git_repository *repo)
{
git_reference *tracking, *ref;
int error = -1;
if (*base_ref == NULL) {
if ((error = git_reference_dwim(&ref, repo, identifier)) < 0)
return error;
} else {
ref = *base_ref;
*base_ref = NULL;
}
if (!git_reference_is_branch(ref)) {
error = GIT_EINVALIDSPEC;
goto cleanup;
}
if ((error = git_branch_upstream(&tracking, ref)) < 0)
goto cleanup;
*base_ref = tracking;
cleanup:
git_reference_free(ref);
return error;
}
static int handle_at_syntax(git_object **out, git_reference **ref, const char *spec, size_t identifier_len, git_repository *repo, const char *curly_braces_content)
{
bool is_numeric;
int parsed = 0, error = -1;
git_buf identifier = GIT_BUF_INIT;
git_time_t timestamp;
GIT_ASSERT(*out == NULL);
if (git_buf_put(&identifier, spec, identifier_len) < 0)
return -1;
is_numeric = !try_parse_numeric(&parsed, curly_braces_content);
if (*curly_braces_content == '-' && (!is_numeric || parsed == 0)) {
error = GIT_EINVALIDSPEC;
goto cleanup;
}
if (is_numeric) {
if (parsed < 0)
error = retrieve_previously_checked_out_branch_or_revision(out, ref, repo, git_buf_cstr(&identifier), -parsed);
else
error = retrieve_revobject_from_reflog(out, ref, repo, git_buf_cstr(&identifier), parsed);
goto cleanup;
}
if (!strcmp(curly_braces_content, "u") || !strcmp(curly_braces_content, "upstream")) {
error = retrieve_remote_tracking_reference(ref, git_buf_cstr(&identifier), repo);
goto cleanup;
}
if (git__date_parse(×tamp, curly_braces_content) < 0)
goto cleanup;
error = retrieve_revobject_from_reflog(out, ref, repo, git_buf_cstr(&identifier), (size_t)timestamp);
cleanup:
git_buf_dispose(&identifier);
return error;
}
static git_object_t parse_obj_type(const char *str)
{
if (!strcmp(str, "commit"))
return GIT_OBJECT_COMMIT;
if (!strcmp(str, "tree"))
return GIT_OBJECT_TREE;
if (!strcmp(str, "blob"))
return GIT_OBJECT_BLOB;
if (!strcmp(str, "tag"))
return GIT_OBJECT_TAG;
return GIT_OBJECT_INVALID;
}
static int dereference_to_non_tag(git_object **out, git_object *obj)
{
if (git_object_type(obj) == GIT_OBJECT_TAG)
return git_tag_peel(out, (git_tag *)obj);
return git_object_dup(out, obj);
}
static int handle_caret_parent_syntax(git_object **out, git_object *obj, int n)
{
git_object *temp_commit = NULL;
int error;
if ((error = git_object_peel(&temp_commit, obj, GIT_OBJECT_COMMIT)) < 0)
return (error == GIT_EAMBIGUOUS || error == GIT_ENOTFOUND) ?
GIT_EINVALIDSPEC : error;
if (n == 0) {
*out = temp_commit;
return 0;
}
error = git_commit_parent((git_commit **)out, (git_commit*)temp_commit, n - 1);
git_object_free(temp_commit);
return error;
}
static int handle_linear_syntax(git_object **out, git_object *obj, int n)
{
git_object *temp_commit = NULL;
int error;
if ((error = git_object_peel(&temp_commit, obj, GIT_OBJECT_COMMIT)) < 0)
return (error == GIT_EAMBIGUOUS || error == GIT_ENOTFOUND) ?
GIT_EINVALIDSPEC : error;
error = git_commit_nth_gen_ancestor((git_commit **)out, (git_commit*)temp_commit, n);
git_object_free(temp_commit);
return error;
}
static int handle_colon_syntax(
git_object **out,
git_object *obj,
const char *path)
{
git_object *tree;
int error = -1;
git_tree_entry *entry = NULL;
if ((error = git_object_peel(&tree, obj, GIT_OBJECT_TREE)) < 0)
return error == GIT_ENOTFOUND ? GIT_EINVALIDSPEC : error;
if (*path == '\0') {
*out = tree;
return 0;
}
/*
* TODO: Handle the relative path syntax
* (:./relative/path and :../relative/path)
*/
if ((error = git_tree_entry_bypath(&entry, (git_tree *)tree, path)) < 0)
goto cleanup;
error = git_tree_entry_to_object(out, git_object_owner(tree), entry);
cleanup:
git_tree_entry_free(entry);
git_object_free(tree);
return error;
}
static int walk_and_search(git_object **out, git_revwalk *walk, git_regexp *regex)
{
int error;
git_oid oid;
git_object *obj;
while (!(error = git_revwalk_next(&oid, walk))) {
error = git_object_lookup(&obj, git_revwalk_repository(walk), &oid, GIT_OBJECT_COMMIT);
if ((error < 0) && (error != GIT_ENOTFOUND))
return -1;
if (!git_regexp_match(regex, git_commit_message((git_commit*)obj))) {
*out = obj;
return 0;
}
git_object_free(obj);
}
if (error < 0 && error == GIT_ITEROVER)
error = GIT_ENOTFOUND;
return error;
}
static int handle_grep_syntax(git_object **out, git_repository *repo, const git_oid *spec_oid, const char *pattern)
{
git_regexp preg;
git_revwalk *walk = NULL;
int error;
if ((error = build_regex(&preg, pattern)) < 0)
return error;
if ((error = git_revwalk_new(&walk, repo)) < 0)
goto cleanup;
git_revwalk_sorting(walk, GIT_SORT_TIME);
if (spec_oid == NULL) {
if ((error = git_revwalk_push_glob(walk, "refs/*")) < 0)
goto cleanup;
} else if ((error = git_revwalk_push(walk, spec_oid)) < 0)
goto cleanup;
error = walk_and_search(out, walk, &preg);
cleanup:
git_regexp_dispose(&preg);
git_revwalk_free(walk);
return error;
}
static int handle_caret_curly_syntax(git_object **out, git_object *obj, const char *curly_braces_content)
{
git_object_t expected_type;
if (*curly_braces_content == '\0')
return dereference_to_non_tag(out, obj);
if (*curly_braces_content == '/')
return handle_grep_syntax(out, git_object_owner(obj), git_object_id(obj), curly_braces_content + 1);
expected_type = parse_obj_type(curly_braces_content);
if (expected_type == GIT_OBJECT_INVALID)
return GIT_EINVALIDSPEC;
return git_object_peel(out, obj, expected_type);
}
static int extract_curly_braces_content(git_buf *buf, const char *spec, size_t *pos)
{
git_buf_clear(buf);
GIT_ASSERT_ARG(spec[*pos] == '^' || spec[*pos] == '@');
(*pos)++;
if (spec[*pos] == '\0' || spec[*pos] != '{')
return GIT_EINVALIDSPEC;
(*pos)++;
while (spec[*pos] != '}') {
if (spec[*pos] == '\0')
return GIT_EINVALIDSPEC;
if (git_buf_putc(buf, spec[(*pos)++]) < 0)
return -1;
}
(*pos)++;
return 0;
}
static int extract_path(git_buf *buf, const char *spec, size_t *pos)
{
git_buf_clear(buf);
GIT_ASSERT_ARG(spec[*pos] == ':');
(*pos)++;
if (git_buf_puts(buf, spec + *pos) < 0)
return -1;
*pos += git_buf_len(buf);
return 0;
}
static int extract_how_many(int *n, const char *spec, size_t *pos)
{
const char *end_ptr;
int parsed, accumulated;
char kind = spec[*pos];
GIT_ASSERT_ARG(spec[*pos] == '^' || spec[*pos] == '~');
accumulated = 0;
do {
do {
(*pos)++;
accumulated++;
} while (spec[(*pos)] == kind && kind == '~');
if (git__isdigit(spec[*pos])) {
if (git__strntol32(&parsed, spec + *pos, strlen(spec + *pos), &end_ptr, 10) < 0)
return GIT_EINVALIDSPEC;
accumulated += (parsed - 1);
*pos = end_ptr - spec;
}
} while (spec[(*pos)] == kind && kind == '~');
*n = accumulated;
return 0;
}
static int object_from_reference(git_object **object, git_reference *reference)
{
git_reference *resolved = NULL;
int error;
if (git_reference_resolve(&resolved, reference) < 0)
return -1;
error = git_object_lookup(object, reference->db->repo, git_reference_target(resolved), GIT_OBJECT_ANY);
git_reference_free(resolved);
return error;
}
static int ensure_base_rev_loaded(git_object **object, git_reference **reference, const char *spec, size_t identifier_len, git_repository *repo, bool allow_empty_identifier)
{
int error;
git_buf identifier = GIT_BUF_INIT;
if (*object != NULL)
return 0;
if (*reference != NULL)
return object_from_reference(object, *reference);
if (!allow_empty_identifier && identifier_len == 0)
return GIT_EINVALIDSPEC;
if (git_buf_put(&identifier, spec, identifier_len) < 0)
return -1;
error = revparse_lookup_object(object, reference, repo, git_buf_cstr(&identifier));
git_buf_dispose(&identifier);
return error;
}
static int ensure_base_rev_is_not_known_yet(git_object *object)
{
if (object == NULL)
return 0;
return GIT_EINVALIDSPEC;
}
static bool any_left_hand_identifier(git_object *object, git_reference *reference, size_t identifier_len)
{
if (object != NULL)
return true;
if (reference != NULL)
return true;
if (identifier_len > 0)
return true;
return false;
}
static int ensure_left_hand_identifier_is_not_known_yet(git_object *object, git_reference *reference)
{
if (!ensure_base_rev_is_not_known_yet(object) && reference == NULL)
return 0;
return GIT_EINVALIDSPEC;
}
static int revparse(
git_object **object_out,
git_reference **reference_out,
size_t *identifier_len_out,
git_repository *repo,
const char *spec)
{
size_t pos = 0, identifier_len = 0;
int error = -1, n;
git_buf buf = GIT_BUF_INIT;
git_reference *reference = NULL;
git_object *base_rev = NULL;
bool should_return_reference = true;
GIT_ASSERT_ARG(object_out);
GIT_ASSERT_ARG(reference_out);
GIT_ASSERT_ARG(repo);
GIT_ASSERT_ARG(spec);
*object_out = NULL;
*reference_out = NULL;
while (spec[pos]) {
switch (spec[pos]) {
case '^':
should_return_reference = false;
if ((error = ensure_base_rev_loaded(&base_rev, &reference, spec, identifier_len, repo, false)) < 0)
goto cleanup;
if (spec[pos+1] == '{') {
git_object *temp_object = NULL;
if ((error = extract_curly_braces_content(&buf, spec, &pos)) < 0)
goto cleanup;
if ((error = handle_caret_curly_syntax(&temp_object, base_rev, git_buf_cstr(&buf))) < 0)
goto cleanup;
git_object_free(base_rev);
base_rev = temp_object;
} else {
git_object *temp_object = NULL;
if ((error = extract_how_many(&n, spec, &pos)) < 0)
goto cleanup;
if ((error = handle_caret_parent_syntax(&temp_object, base_rev, n)) < 0)
goto cleanup;
git_object_free(base_rev);
base_rev = temp_object;
}
break;
case '~':
{
git_object *temp_object = NULL;
should_return_reference = false;
if ((error = extract_how_many(&n, spec, &pos)) < 0)
goto cleanup;
if ((error = ensure_base_rev_loaded(&base_rev, &reference, spec, identifier_len, repo, false)) < 0)
goto cleanup;
if ((error = handle_linear_syntax(&temp_object, base_rev, n)) < 0)
goto cleanup;
git_object_free(base_rev);
base_rev = temp_object;
break;
}
case ':':
{
git_object *temp_object = NULL;
should_return_reference = false;
if ((error = extract_path(&buf, spec, &pos)) < 0)
goto cleanup;
if (any_left_hand_identifier(base_rev, reference, identifier_len)) {
if ((error = ensure_base_rev_loaded(&base_rev, &reference, spec, identifier_len, repo, true)) < 0)
goto cleanup;
if ((error = handle_colon_syntax(&temp_object, base_rev, git_buf_cstr(&buf))) < 0)
goto cleanup;
} else {
if (*git_buf_cstr(&buf) == '/') {
if ((error = handle_grep_syntax(&temp_object, repo, NULL, git_buf_cstr(&buf) + 1)) < 0)
goto cleanup;
} else {
/*
* TODO: support merge-stage path lookup (":2:Makefile")
* and plain index blob lookup (:i-am/a/blob)
*/
git_error_set(GIT_ERROR_INVALID, "unimplemented");
error = GIT_ERROR;
goto cleanup;
}
}
git_object_free(base_rev);
base_rev = temp_object;
break;
}
case '@':
if (spec[pos+1] == '{') {
git_object *temp_object = NULL;
if ((error = extract_curly_braces_content(&buf, spec, &pos)) < 0)
goto cleanup;
if ((error = ensure_base_rev_is_not_known_yet(base_rev)) < 0)
goto cleanup;
if ((error = handle_at_syntax(&temp_object, &reference, spec, identifier_len, repo, git_buf_cstr(&buf))) < 0)
goto cleanup;
if (temp_object != NULL)
base_rev = temp_object;
break;
}
/* fall through */
default:
if ((error = ensure_left_hand_identifier_is_not_known_yet(base_rev, reference)) < 0)
goto cleanup;
pos++;
identifier_len++;
}
}
if ((error = ensure_base_rev_loaded(&base_rev, &reference, spec, identifier_len, repo, false)) < 0)
goto cleanup;
if (!should_return_reference) {
git_reference_free(reference);
reference = NULL;
}
*object_out = base_rev;
*reference_out = reference;
*identifier_len_out = identifier_len;
error = 0;
cleanup:
if (error) {
if (error == GIT_EINVALIDSPEC)
git_error_set(GIT_ERROR_INVALID,
"failed to parse revision specifier - Invalid pattern '%s'", spec);
git_object_free(base_rev);
git_reference_free(reference);
}
git_buf_dispose(&buf);
return error;
}
int git_revparse_ext(
git_object **object_out,
git_reference **reference_out,
git_repository *repo,
const char *spec)
{
int error;
size_t identifier_len;
git_object *obj = NULL;
git_reference *ref = NULL;
if ((error = revparse(&obj, &ref, &identifier_len, repo, spec)) < 0)
goto cleanup;
*object_out = obj;
*reference_out = ref;
GIT_UNUSED(identifier_len);
return 0;
cleanup:
git_object_free(obj);
git_reference_free(ref);
return error;
}
int git_revparse_single(git_object **out, git_repository *repo, const char *spec)
{
int error;
git_object *obj = NULL;
git_reference *ref = NULL;
*out = NULL;
if ((error = git_revparse_ext(&obj, &ref, repo, spec)) < 0)
goto cleanup;
git_reference_free(ref);
*out = obj;
return 0;
cleanup:
git_object_free(obj);
git_reference_free(ref);
return error;
}
int git_revparse(
git_revspec *revspec,
git_repository *repo,
const char *spec)
{
const char *dotdot;
int error = 0;
GIT_ASSERT_ARG(revspec);
GIT_ASSERT_ARG(repo);
GIT_ASSERT_ARG(spec);
memset(revspec, 0x0, sizeof(*revspec));
if ((dotdot = strstr(spec, "..")) != NULL) {
char *lstr;
const char *rstr;
revspec->flags = GIT_REVSPEC_RANGE;
/*
* Following git.git, don't allow '..' because it makes command line
* arguments which can be either paths or revisions ambiguous when the
* path is almost certainly intended. The empty range '...' is still
* allowed.
*/
if (!git__strcmp(spec, "..")) {
git_error_set(GIT_ERROR_INVALID, "Invalid pattern '..'");
return GIT_EINVALIDSPEC;
}
lstr = git__substrdup(spec, dotdot - spec);
rstr = dotdot + 2;
if (dotdot[2] == '.') {
revspec->flags |= GIT_REVSPEC_MERGE_BASE;
rstr++;
}
error = git_revparse_single(
&revspec->from,
repo,
*lstr == '\0' ? "HEAD" : lstr);
if (!error) {
error = git_revparse_single(
&revspec->to,
repo,
*rstr == '\0' ? "HEAD" : rstr);
}
git__free((void*)lstr);
} else {
revspec->flags = GIT_REVSPEC_SINGLE;
error = git_revparse_single(&revspec->from, repo, spec);
}
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/config_mem.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 "config_backend.h"
#include "config_parse.h"
#include "config_entries.h"
typedef struct {
git_config_backend parent;
git_config_entries *entries;
git_buf cfg;
} config_memory_backend;
typedef struct {
git_config_entries *entries;
git_config_level_t level;
} config_memory_parse_data;
static int config_error_readonly(void)
{
git_error_set(GIT_ERROR_CONFIG, "this backend is read-only");
return -1;
}
static int read_variable_cb(
git_config_parser *reader,
const char *current_section,
const char *var_name,
const char *var_value,
const char *line,
size_t line_len,
void *payload)
{
config_memory_parse_data *parse_data = (config_memory_parse_data *) payload;
git_buf buf = GIT_BUF_INIT;
git_config_entry *entry;
const char *c;
int result;
GIT_UNUSED(reader);
GIT_UNUSED(line);
GIT_UNUSED(line_len);
if (current_section) {
/* TODO: Once warnings land, 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 = 0;
if ((result = git_config_entries_append(parse_data->entries, entry)) < 0)
return result;
return result;
}
static int config_memory_open(git_config_backend *backend, git_config_level_t level, const git_repository *repo)
{
config_memory_backend *memory_backend = (config_memory_backend *) backend;
git_config_parser parser = GIT_PARSE_CTX_INIT;
config_memory_parse_data parse_data;
int error;
GIT_UNUSED(repo);
if ((error = git_config_parser_init(&parser, "in-memory", memory_backend->cfg.ptr,
memory_backend->cfg.size)) < 0)
goto out;
parse_data.entries = memory_backend->entries;
parse_data.level = level;
if ((error = git_config_parse(&parser, NULL, read_variable_cb, NULL, NULL, &parse_data)) < 0)
goto out;
out:
git_config_parser_dispose(&parser);
return error;
}
static int config_memory_get(git_config_backend *backend, const char *key, git_config_entry **out)
{
config_memory_backend *memory_backend = (config_memory_backend *) backend;
return git_config_entries_get(out, memory_backend->entries, key);
}
static int config_memory_iterator(
git_config_iterator **iter,
git_config_backend *backend)
{
config_memory_backend *memory_backend = (config_memory_backend *) backend;
git_config_entries *entries;
int error;
if ((error = git_config_entries_dup(&entries, memory_backend->entries)) < 0)
goto out;
if ((error = git_config_entries_iterator_new(iter, entries)) < 0)
goto out;
out:
/* Let iterator delete duplicated entries when it's done */
git_config_entries_free(entries);
return error;
}
static int config_memory_set(git_config_backend *backend, const char *name, const char *value)
{
GIT_UNUSED(backend);
GIT_UNUSED(name);
GIT_UNUSED(value);
return config_error_readonly();
}
static int config_memory_set_multivar(
git_config_backend *backend, const char *name, const char *regexp, const char *value)
{
GIT_UNUSED(backend);
GIT_UNUSED(name);
GIT_UNUSED(regexp);
GIT_UNUSED(value);
return config_error_readonly();
}
static int config_memory_delete(git_config_backend *backend, const char *name)
{
GIT_UNUSED(backend);
GIT_UNUSED(name);
return config_error_readonly();
}
static int config_memory_delete_multivar(git_config_backend *backend, const char *name, const char *regexp)
{
GIT_UNUSED(backend);
GIT_UNUSED(name);
GIT_UNUSED(regexp);
return config_error_readonly();
}
static int config_memory_lock(git_config_backend *backend)
{
GIT_UNUSED(backend);
return config_error_readonly();
}
static int config_memory_unlock(git_config_backend *backend, int success)
{
GIT_UNUSED(backend);
GIT_UNUSED(success);
return config_error_readonly();
}
static void config_memory_free(git_config_backend *_backend)
{
config_memory_backend *backend = (config_memory_backend *)_backend;
if (backend == NULL)
return;
git_config_entries_free(backend->entries);
git_buf_dispose(&backend->cfg);
git__free(backend);
}
int git_config_backend_from_string(git_config_backend **out, const char *cfg, size_t len)
{
config_memory_backend *backend;
backend = git__calloc(1, sizeof(config_memory_backend));
GIT_ERROR_CHECK_ALLOC(backend);
if (git_config_entries_new(&backend->entries) < 0) {
git__free(backend);
return -1;
}
if (git_buf_set(&backend->cfg, cfg, len) < 0) {
git_config_entries_free(backend->entries);
git__free(backend);
return -1;
}
backend->parent.version = GIT_CONFIG_BACKEND_VERSION;
backend->parent.readonly = 1;
backend->parent.open = config_memory_open;
backend->parent.get = config_memory_get;
backend->parent.set = config_memory_set;
backend->parent.set_multivar = config_memory_set_multivar;
backend->parent.del = config_memory_delete;
backend->parent.del_multivar = config_memory_delete_multivar;
backend->parent.iterator = config_memory_iterator;
backend->parent.lock = config_memory_lock;
backend->parent.unlock = config_memory_unlock;
backend->parent.snapshot = git_config_backend_snapshot;
backend->parent.free = config_memory_free;
*out = (git_config_backend *)backend;
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/vector.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 "vector.h"
#include "integer.h"
/* In elements, not bytes */
#define MIN_ALLOCSIZE 8
GIT_INLINE(size_t) compute_new_size(git_vector *v)
{
size_t new_size = v->_alloc_size;
/* Use a resize factor of 1.5, which is quick to compute using integer
* instructions and less than the golden ratio (1.618...) */
if (new_size < MIN_ALLOCSIZE)
new_size = MIN_ALLOCSIZE;
else if (new_size <= (SIZE_MAX / 3) * 2)
new_size += new_size / 2;
else
new_size = SIZE_MAX;
return new_size;
}
GIT_INLINE(int) resize_vector(git_vector *v, size_t new_size)
{
void *new_contents;
if (new_size == 0)
return 0;
new_contents = git__reallocarray(v->contents, new_size, sizeof(void *));
GIT_ERROR_CHECK_ALLOC(new_contents);
v->_alloc_size = new_size;
v->contents = new_contents;
return 0;
}
int git_vector_size_hint(git_vector *v, size_t size_hint)
{
if (v->_alloc_size >= size_hint)
return 0;
return resize_vector(v, size_hint);
}
int git_vector_dup(git_vector *v, const git_vector *src, git_vector_cmp cmp)
{
GIT_ASSERT_ARG(v);
GIT_ASSERT_ARG(src);
v->_alloc_size = 0;
v->contents = NULL;
v->_cmp = cmp ? cmp : src->_cmp;
v->length = src->length;
v->flags = src->flags;
if (cmp != src->_cmp)
git_vector_set_sorted(v, 0);
if (src->length) {
size_t bytes;
GIT_ERROR_CHECK_ALLOC_MULTIPLY(&bytes, src->length, sizeof(void *));
v->contents = git__malloc(bytes);
GIT_ERROR_CHECK_ALLOC(v->contents);
v->_alloc_size = src->length;
memcpy(v->contents, src->contents, bytes);
}
return 0;
}
void git_vector_free(git_vector *v)
{
if (!v)
return;
git__free(v->contents);
v->contents = NULL;
v->length = 0;
v->_alloc_size = 0;
}
void git_vector_free_deep(git_vector *v)
{
size_t i;
if (!v)
return;
for (i = 0; i < v->length; ++i) {
git__free(v->contents[i]);
v->contents[i] = NULL;
}
git_vector_free(v);
}
int git_vector_init(git_vector *v, size_t initial_size, git_vector_cmp cmp)
{
GIT_ASSERT_ARG(v);
v->_alloc_size = 0;
v->_cmp = cmp;
v->length = 0;
v->flags = GIT_VECTOR_SORTED;
v->contents = NULL;
return resize_vector(v, max(initial_size, MIN_ALLOCSIZE));
}
void **git_vector_detach(size_t *size, size_t *asize, git_vector *v)
{
void **data = v->contents;
if (size)
*size = v->length;
if (asize)
*asize = v->_alloc_size;
v->_alloc_size = 0;
v->length = 0;
v->contents = NULL;
return data;
}
int git_vector_insert(git_vector *v, void *element)
{
GIT_ASSERT_ARG(v);
if (v->length >= v->_alloc_size &&
resize_vector(v, compute_new_size(v)) < 0)
return -1;
v->contents[v->length++] = element;
git_vector_set_sorted(v, v->length <= 1);
return 0;
}
int git_vector_insert_sorted(
git_vector *v, void *element, int (*on_dup)(void **old, void *new))
{
int result;
size_t pos;
GIT_ASSERT_ARG(v);
GIT_ASSERT(v->_cmp);
if (!git_vector_is_sorted(v))
git_vector_sort(v);
if (v->length >= v->_alloc_size &&
resize_vector(v, compute_new_size(v)) < 0)
return -1;
/* If we find the element and have a duplicate handler callback,
* invoke it. If it returns non-zero, then cancel insert, otherwise
* proceed with normal insert.
*/
if (!git__bsearch(v->contents, v->length, element, v->_cmp, &pos) &&
on_dup && (result = on_dup(&v->contents[pos], element)) < 0)
return result;
/* shift elements to the right */
if (pos < v->length)
memmove(v->contents + pos + 1, v->contents + pos,
(v->length - pos) * sizeof(void *));
v->contents[pos] = element;
v->length++;
return 0;
}
void git_vector_sort(git_vector *v)
{
if (git_vector_is_sorted(v) || !v->_cmp)
return;
if (v->length > 1)
git__tsort(v->contents, v->length, v->_cmp);
git_vector_set_sorted(v, 1);
}
int git_vector_bsearch2(
size_t *at_pos,
git_vector *v,
git_vector_cmp key_lookup,
const void *key)
{
GIT_ASSERT_ARG(v);
GIT_ASSERT_ARG(key);
GIT_ASSERT(key_lookup);
/* need comparison function to sort the vector */
if (!v->_cmp)
return -1;
git_vector_sort(v);
return git__bsearch(v->contents, v->length, key, key_lookup, at_pos);
}
int git_vector_search2(
size_t *at_pos, const git_vector *v, git_vector_cmp key_lookup, const void *key)
{
size_t i;
GIT_ASSERT_ARG(v);
GIT_ASSERT_ARG(key);
GIT_ASSERT(key_lookup);
for (i = 0; i < v->length; ++i) {
if (key_lookup(key, v->contents[i]) == 0) {
if (at_pos)
*at_pos = i;
return 0;
}
}
return GIT_ENOTFOUND;
}
static int strict_comparison(const void *a, const void *b)
{
return (a == b) ? 0 : -1;
}
int git_vector_search(size_t *at_pos, const git_vector *v, const void *entry)
{
return git_vector_search2(at_pos, v, v->_cmp ? v->_cmp : strict_comparison, entry);
}
int git_vector_remove(git_vector *v, size_t idx)
{
size_t shift_count;
GIT_ASSERT_ARG(v);
if (idx >= v->length)
return GIT_ENOTFOUND;
shift_count = v->length - idx - 1;
if (shift_count)
memmove(&v->contents[idx], &v->contents[idx + 1],
shift_count * sizeof(void *));
v->length--;
return 0;
}
void git_vector_pop(git_vector *v)
{
if (v->length > 0)
v->length--;
}
void git_vector_uniq(git_vector *v, void (*git_free_cb)(void *))
{
git_vector_cmp cmp;
size_t i, j;
if (v->length <= 1)
return;
git_vector_sort(v);
cmp = v->_cmp ? v->_cmp : strict_comparison;
for (i = 0, j = 1 ; j < v->length; ++j)
if (!cmp(v->contents[i], v->contents[j])) {
if (git_free_cb)
git_free_cb(v->contents[i]);
v->contents[i] = v->contents[j];
} else
v->contents[++i] = v->contents[j];
v->length -= j - i - 1;
}
void git_vector_remove_matching(
git_vector *v,
int (*match)(const git_vector *v, size_t idx, void *payload),
void *payload)
{
size_t i, j;
for (i = 0, j = 0; j < v->length; ++j) {
v->contents[i] = v->contents[j];
if (!match(v, i, payload))
i++;
}
v->length = i;
}
void git_vector_clear(git_vector *v)
{
v->length = 0;
git_vector_set_sorted(v, 1);
}
void git_vector_swap(git_vector *a, git_vector *b)
{
git_vector t;
if (a != b) {
memcpy(&t, a, sizeof(t));
memcpy(a, b, sizeof(t));
memcpy(b, &t, sizeof(t));
}
}
int git_vector_resize_to(git_vector *v, size_t new_length)
{
if (new_length > v->_alloc_size &&
resize_vector(v, new_length) < 0)
return -1;
if (new_length > v->length)
memset(&v->contents[v->length], 0,
sizeof(void *) * (new_length - v->length));
v->length = new_length;
return 0;
}
int git_vector_insert_null(git_vector *v, size_t idx, size_t insert_len)
{
size_t new_length;
GIT_ASSERT_ARG(insert_len > 0);
GIT_ASSERT_ARG(idx <= v->length);
GIT_ERROR_CHECK_ALLOC_ADD(&new_length, v->length, insert_len);
if (new_length > v->_alloc_size && resize_vector(v, new_length) < 0)
return -1;
memmove(&v->contents[idx + insert_len], &v->contents[idx],
sizeof(void *) * (v->length - idx));
memset(&v->contents[idx], 0, sizeof(void *) * insert_len);
v->length = new_length;
return 0;
}
int git_vector_remove_range(git_vector *v, size_t idx, size_t remove_len)
{
size_t new_length = v->length - remove_len;
size_t end_idx = 0;
GIT_ASSERT_ARG(remove_len > 0);
if (git__add_sizet_overflow(&end_idx, idx, remove_len))
GIT_ASSERT(0);
GIT_ASSERT(end_idx <= v->length);
if (end_idx < v->length)
memmove(&v->contents[idx], &v->contents[end_idx],
sizeof(void *) * (v->length - end_idx));
memset(&v->contents[new_length], 0, sizeof(void *) * remove_len);
v->length = new_length;
return 0;
}
int git_vector_set(void **old, git_vector *v, size_t position, void *value)
{
if (position + 1 > v->length) {
if (git_vector_resize_to(v, position + 1) < 0)
return -1;
}
if (old != NULL)
*old = v->contents[position];
v->contents[position] = value;
return 0;
}
int git_vector_verify_sorted(const git_vector *v)
{
size_t i;
if (!git_vector_is_sorted(v))
return -1;
for (i = 1; i < v->length; ++i) {
if (v->_cmp(v->contents[i - 1], v->contents[i]) > 0)
return -1;
}
return 0;
}
void git_vector_reverse(git_vector *v)
{
size_t a, b;
if (v->length == 0)
return;
a = 0;
b = v->length - 1;
while (a < b) {
void *tmp = v->contents[a];
v->contents[a] = v->contents[b];
v->contents[b] = tmp;
a++;
b--;
}
}
|
0 |
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2
|
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2/src/stream.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_stream_h__
#define INCLUDE_stream_h__
#include "common.h"
#include "git2/sys/stream.h"
GIT_INLINE(int) git_stream_connect(git_stream *st)
{
return st->connect(st);
}
GIT_INLINE(int) git_stream_is_encrypted(git_stream *st)
{
return st->encrypted;
}
GIT_INLINE(int) git_stream_certificate(git_cert **out, git_stream *st)
{
if (!st->encrypted) {
git_error_set(GIT_ERROR_INVALID, "an unencrypted stream does not have a certificate");
return -1;
}
return st->certificate(out, st);
}
GIT_INLINE(int) git_stream_supports_proxy(git_stream *st)
{
return st->proxy_support;
}
GIT_INLINE(int) git_stream_set_proxy(git_stream *st, const git_proxy_options *proxy_opts)
{
if (!st->proxy_support) {
git_error_set(GIT_ERROR_INVALID, "proxy not supported on this stream");
return -1;
}
return st->set_proxy(st, proxy_opts);
}
GIT_INLINE(ssize_t) git_stream_read(git_stream *st, void *data, size_t len)
{
return st->read(st, data, len);
}
GIT_INLINE(ssize_t) git_stream_write(git_stream *st, const char *data, size_t len, int flags)
{
return st->write(st, data, len, flags);
}
GIT_INLINE(int) git_stream__write_full(git_stream *st, const char *data, size_t len, int flags)
{
size_t total_written = 0;
while (total_written < len) {
ssize_t written = git_stream_write(st, data + total_written, len - total_written, flags);
if (written <= 0)
return -1;
total_written += written;
}
return 0;
}
GIT_INLINE(int) git_stream_close(git_stream *st)
{
return st->close(st);
}
GIT_INLINE(void) git_stream_free(git_stream *st)
{
if (!st)
return;
st->free(st);
}
#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/path.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_path_h__
#define INCLUDE_path_h__
#include "common.h"
#include "posix.h"
#include "buffer.h"
#include "vector.h"
#include "git2/sys/path.h"
/**
* Path manipulation utils
*
* These are path utilities that munge paths without actually
* looking at the real filesystem.
*/
/*
* The dirname() function shall take a pointer to a character string
* that contains a pathname, and return a pointer to a string that is a
* pathname of the parent directory of that file. Trailing '/' characters
* in the path are not counted as part of the path.
*
* If path does not contain a '/', then dirname() shall return a pointer to
* the string ".". If path is a null pointer or points to an empty string,
* dirname() shall return a pointer to the string "." .
*
* The `git_path_dirname` implementation is thread safe. The returned
* string must be manually free'd.
*
* The `git_path_dirname_r` implementation writes the dirname to a `git_buf`
* if the buffer pointer is not NULL.
* It returns an error code < 0 if there is an allocation error, otherwise
* the length of the dirname (which will be > 0).
*/
extern char *git_path_dirname(const char *path);
extern int git_path_dirname_r(git_buf *buffer, const char *path);
/*
* This function returns the basename of the file, which is the last
* part of its full name given by fname, with the drive letter and
* leading directories stripped off. For example, the basename of
* c:/foo/bar/file.ext is file.ext, and the basename of a:foo is foo.
*
* Trailing slashes and backslashes are significant: the basename of
* c:/foo/bar/ is an empty string after the rightmost slash.
*
* The `git_path_basename` implementation is thread safe. The returned
* string must be manually free'd.
*
* The `git_path_basename_r` implementation writes the basename to a `git_buf`.
* It returns an error code < 0 if there is an allocation error, otherwise
* the length of the basename (which will be >= 0).
*/
extern char *git_path_basename(const char *path);
extern int git_path_basename_r(git_buf *buffer, const char *path);
/* Return the offset of the start of the basename. Unlike the other
* basename functions, this returns 0 if the path is empty.
*/
extern size_t git_path_basename_offset(git_buf *buffer);
/**
* Find offset to root of path if path has one.
*
* This will return a number >= 0 which is the offset to the start of the
* path, if the path is rooted (i.e. "/rooted/path" returns 0 and
* "c:/windows/rooted/path" returns 2). If the path is not rooted, this
* returns -1.
*/
extern int git_path_root(const char *path);
/**
* Ensure path has a trailing '/'.
*/
extern int git_path_to_dir(git_buf *path);
/**
* Ensure string has a trailing '/' if there is space for it.
*/
extern void git_path_string_to_dir(char *path, size_t size);
/**
* Taken from git.git; returns nonzero if the given path is "." or "..".
*/
GIT_INLINE(int) git_path_is_dot_or_dotdot(const char *name)
{
return (name[0] == '.' &&
(name[1] == '\0' ||
(name[1] == '.' && name[2] == '\0')));
}
#ifdef GIT_WIN32
GIT_INLINE(int) git_path_is_dot_or_dotdotW(const wchar_t *name)
{
return (name[0] == L'.' &&
(name[1] == L'\0' ||
(name[1] == L'.' && name[2] == L'\0')));
}
#define git_path_is_absolute(p) \
(git__isalpha((p)[0]) && (p)[1] == ':' && ((p)[2] == '\\' || (p)[2] == '/'))
#define git_path_is_dirsep(p) \
((p) == '/' || (p) == '\\')
/**
* Convert backslashes in path to forward slashes.
*/
GIT_INLINE(void) git_path_mkposix(char *path)
{
while (*path) {
if (*path == '\\')
*path = '/';
path++;
}
}
#else
# define git_path_mkposix(p) /* blank */
#define git_path_is_absolute(p) \
((p)[0] == '/')
#define git_path_is_dirsep(p) \
((p) == '/')
#endif
/**
* Check if string is a relative path (i.e. starts with "./" or "../")
*/
GIT_INLINE(int) git_path_is_relative(const char *p)
{
return (p[0] == '.' && (p[1] == '/' || (p[1] == '.' && p[2] == '/')));
}
/**
* Check if string is at end of path segment (i.e. looking at '/' or '\0')
*/
GIT_INLINE(int) git_path_at_end_of_segment(const char *p)
{
return !*p || *p == '/';
}
extern int git__percent_decode(git_buf *decoded_out, const char *input);
/**
* Extract path from file:// URL.
*/
extern int git_path_fromurl(git_buf *local_path_out, const char *file_url);
/**
* Path filesystem utils
*
* These are path utilities that actually access the filesystem.
*/
/**
* Check if a file exists and can be accessed.
* @return true or false
*/
extern bool git_path_exists(const char *path);
/**
* Check if the given path points to a directory.
* @return true or false
*/
extern bool git_path_isdir(const char *path);
/**
* Check if the given path points to a regular file.
* @return true or false
*/
extern bool git_path_isfile(const char *path);
/**
* Check if the given path points to a symbolic link.
* @return true or false
*/
extern bool git_path_islink(const char *path);
/**
* Check if the given path is a directory, and is empty.
*/
extern bool git_path_is_empty_dir(const char *path);
/**
* Stat a file and/or link and set error if needed.
*/
extern int git_path_lstat(const char *path, struct stat *st);
/**
* Check if the parent directory contains the item.
*
* @param dir Directory to check.
* @param item Item that might be in the directory.
* @return 0 if item exists in directory, <0 otherwise.
*/
extern bool git_path_contains(git_buf *dir, const char *item);
/**
* Check if the given path contains the given subdirectory.
*
* @param parent Directory path that might contain subdir
* @param subdir Subdirectory name to look for in parent
* @return true if subdirectory exists, false otherwise.
*/
extern bool git_path_contains_dir(git_buf *parent, const char *subdir);
/**
* Determine the common directory length between two paths, including
* the final path separator. For example, given paths 'a/b/c/1.txt
* and 'a/b/c/d/2.txt', the common directory is 'a/b/c/', and this
* will return the length of the string 'a/b/c/', which is 6.
*
* @param one The first path
* @param two The second path
* @return The length of the common directory
*/
extern size_t git_path_common_dirlen(const char *one, const char *two);
/**
* Make the path relative to the given parent path.
*
* @param path The path to make relative
* @param parent The parent path to make path relative to
* @return 0 if path was made relative, GIT_ENOTFOUND
* if there was not common root between the paths,
* or <0.
*/
extern int git_path_make_relative(git_buf *path, const char *parent);
/**
* Check if the given path contains the given file.
*
* @param dir Directory path that might contain file
* @param file File name to look for in parent
* @return true if file exists, false otherwise.
*/
extern bool git_path_contains_file(git_buf *dir, const char *file);
/**
* Prepend base to unrooted path or just copy path over.
*
* This will optionally return the index into the path where the "root"
* is, either the end of the base directory prefix or the path root.
*/
extern int git_path_join_unrooted(
git_buf *path_out, const char *path, const char *base, ssize_t *root_at);
/**
* Removes multiple occurrences of '/' in a row, squashing them into a
* single '/'.
*/
extern void git_path_squash_slashes(git_buf *path);
/**
* Clean up path, prepending base if it is not already rooted.
*/
extern int git_path_prettify(git_buf *path_out, const char *path, const char *base);
/**
* Clean up path, prepending base if it is not already rooted and
* appending a slash.
*/
extern int git_path_prettify_dir(git_buf *path_out, const char *path, const char *base);
/**
* Get a directory from a path.
*
* If path is a directory, this acts like `git_path_prettify_dir`
* (cleaning up path and appending a '/'). If path is a normal file,
* this prettifies it, then removed the filename a la dirname and
* appends the trailing '/'. If the path does not exist, it is
* treated like a regular filename.
*/
extern int git_path_find_dir(git_buf *dir);
/**
* Resolve relative references within a path.
*
* This eliminates "./" and "../" relative references inside a path,
* as well as condensing multiple slashes into single ones. It will
* not touch the path before the "ceiling" length.
*
* Additionally, this will recognize an "c:/" drive prefix or a "xyz://" URL
* prefix and not touch that part of the path.
*/
extern int git_path_resolve_relative(git_buf *path, size_t ceiling);
/**
* Apply a relative path to base path.
*
* Note that the base path could be a filename or a URL and this
* should still work. The relative path is walked segment by segment
* with three rules: series of slashes will be condensed to a single
* slash, "." will be eaten with no change, and ".." will remove a
* segment from the base path.
*/
extern int git_path_apply_relative(git_buf *target, const char *relpath);
enum {
GIT_PATH_DIR_IGNORE_CASE = (1u << 0),
GIT_PATH_DIR_PRECOMPOSE_UNICODE = (1u << 1),
GIT_PATH_DIR_INCLUDE_DOT_AND_DOTDOT = (1u << 2),
};
/**
* Walk each directory entry, except '.' and '..', calling fn(state).
*
* @param pathbuf Buffer the function reads the initial directory
* path from, and updates with each successive entry's name.
* @param flags Combination of GIT_PATH_DIR flags.
* @param callback Callback for each entry. Passed the `payload` and each
* successive path inside the directory as a full path. This may
* safely append text to the pathbuf if needed. Return non-zero to
* cancel iteration (and return value will be propagated back).
* @param payload Passed to callback as first argument.
* @return 0 on success or error code from OS error or from callback
*/
extern int git_path_direach(
git_buf *pathbuf,
uint32_t flags,
int (*callback)(void *payload, git_buf *path),
void *payload);
/**
* Sort function to order two paths
*/
extern int git_path_cmp(
const char *name1, size_t len1, int isdir1,
const char *name2, size_t len2, int isdir2,
int (*compare)(const char *, const char *, size_t));
/**
* Invoke callback up path directory by directory until the ceiling is
* reached (inclusive of a final call at the root_path).
*
* Returning anything other than 0 from the callback function
* will stop the iteration and propagate the error to the caller.
*
* @param pathbuf Buffer the function reads the directory from and
* and updates with each successive name.
* @param ceiling Prefix of path at which to stop walking up. If NULL,
* this will walk all the way up to the root. If not a prefix of
* pathbuf, the callback will be invoked a single time on the
* original input path.
* @param callback Function to invoke on each path. Passed the `payload`
* and the buffer containing the current path. The path should not
* be modified in any way. Return non-zero to stop iteration.
* @param payload Passed to fn as the first ath.
*/
extern int git_path_walk_up(
git_buf *pathbuf,
const char *ceiling,
int (*callback)(void *payload, const char *path),
void *payload);
enum { GIT_PATH_NOTEQUAL = 0, GIT_PATH_EQUAL = 1, GIT_PATH_PREFIX = 2 };
/*
* Determines if a path is equal to or potentially a child of another.
* @param parent The possible parent
* @param child The possible child
*/
GIT_INLINE(int) git_path_equal_or_prefixed(
const char *parent,
const char *child,
ssize_t *prefixlen)
{
const char *p = parent, *c = child;
int lastslash = 0;
while (*p && *c) {
lastslash = (*p == '/');
if (*p++ != *c++)
return GIT_PATH_NOTEQUAL;
}
if (*p != '\0')
return GIT_PATH_NOTEQUAL;
if (*c == '\0') {
if (prefixlen)
*prefixlen = p - parent;
return GIT_PATH_EQUAL;
}
if (*c == '/' || lastslash) {
if (prefixlen)
*prefixlen = (p - parent) - lastslash;
return GIT_PATH_PREFIX;
}
return GIT_PATH_NOTEQUAL;
}
/* translate errno to libgit2 error code and set error message */
extern int git_path_set_error(
int errno_value, const char *path, const char *action);
/* check if non-ascii characters are present in filename */
extern bool git_path_has_non_ascii(const char *path, size_t pathlen);
#define GIT_PATH_REPO_ENCODING "UTF-8"
#ifdef __APPLE__
#define GIT_PATH_NATIVE_ENCODING "UTF-8-MAC"
#else
#define GIT_PATH_NATIVE_ENCODING "UTF-8"
#endif
#ifdef GIT_USE_ICONV
#include <iconv.h>
typedef struct {
iconv_t map;
git_buf buf;
} git_path_iconv_t;
#define GIT_PATH_ICONV_INIT { (iconv_t)-1, GIT_BUF_INIT }
/* Init iconv data for converting decomposed UTF-8 to precomposed */
extern int git_path_iconv_init_precompose(git_path_iconv_t *ic);
/* Clear allocated iconv data */
extern void git_path_iconv_clear(git_path_iconv_t *ic);
/*
* Rewrite `in` buffer using iconv map if necessary, replacing `in`
* pointer internal iconv buffer if rewrite happened. The `in` pointer
* will be left unchanged if no rewrite was needed.
*/
extern int git_path_iconv(git_path_iconv_t *ic, const char **in, size_t *inlen);
#endif /* GIT_USE_ICONV */
extern bool git_path_does_fs_decompose_unicode(const char *root);
typedef struct git_path_diriter git_path_diriter;
#if defined(GIT_WIN32) && !defined(__MINGW32__)
struct git_path_diriter
{
git_win32_path path;
size_t parent_len;
git_buf path_utf8;
size_t parent_utf8_len;
HANDLE handle;
unsigned int flags;
WIN32_FIND_DATAW current;
unsigned int needs_next;
};
#define GIT_PATH_DIRITER_INIT { {0}, 0, GIT_BUF_INIT, 0, INVALID_HANDLE_VALUE }
#else
struct git_path_diriter
{
git_buf path;
size_t parent_len;
unsigned int flags;
DIR *dir;
#ifdef GIT_USE_ICONV
git_path_iconv_t ic;
#endif
};
#define GIT_PATH_DIRITER_INIT { GIT_BUF_INIT }
#endif
/**
* Initialize a directory iterator.
*
* @param diriter Pointer to a diriter structure that will be setup.
* @param path The path that will be iterated over
* @param flags Directory reader flags
* @return 0 or an error code
*/
extern int git_path_diriter_init(
git_path_diriter *diriter,
const char *path,
unsigned int flags);
/**
* Advance the directory iterator. Will return GIT_ITEROVER when
* the iteration has completed successfully.
*
* @param diriter The directory iterator
* @return 0, GIT_ITEROVER, or an error code
*/
extern int git_path_diriter_next(git_path_diriter *diriter);
/**
* Returns the file name of the current item in the iterator.
*
* @param out Pointer to store the path in
* @param out_len Pointer to store the length of the path in
* @param diriter The directory iterator
* @return 0 or an error code
*/
extern int git_path_diriter_filename(
const char **out,
size_t *out_len,
git_path_diriter *diriter);
/**
* Returns the full path of the current item in the iterator; that
* is the current filename plus the path of the directory that the
* iterator was constructed with.
*
* @param out Pointer to store the path in
* @param out_len Pointer to store the length of the path in
* @param diriter The directory iterator
* @return 0 or an error code
*/
extern int git_path_diriter_fullpath(
const char **out,
size_t *out_len,
git_path_diriter *diriter);
/**
* Performs an `lstat` on the current item in the iterator.
*
* @param out Pointer to store the stat data in
* @param diriter The directory iterator
* @return 0 or an error code
*/
extern int git_path_diriter_stat(struct stat *out, git_path_diriter *diriter);
/**
* Closes the directory iterator.
*
* @param diriter The directory iterator
*/
extern void git_path_diriter_free(git_path_diriter *diriter);
/**
* Load all directory entries (except '.' and '..') into a vector.
*
* For cases where `git_path_direach()` is not appropriate, this
* allows you to load the filenames in a directory into a vector
* of strings. That vector can then be sorted, iterated, or whatever.
* Remember to free alloc of the allocated strings when you are done.
*
* @param contents Vector to fill with directory entry names.
* @param path The directory to read from.
* @param prefix_len When inserting entries, the trailing part of path
* will be prefixed after this length. I.e. given path "/a/b" and
* prefix_len 3, the entries will look like "b/e1", "b/e2", etc.
* @param flags Combination of GIT_PATH_DIR flags.
*/
extern int git_path_dirload(
git_vector *contents,
const char *path,
size_t prefix_len,
uint32_t flags);
/* Used for paths to repositories on the filesystem */
extern bool git_path_is_local_file_url(const char *file_url);
extern int git_path_from_url_or_path(git_buf *local_path_out, const char *url_or_path);
/* Flags to determine path validity in `git_path_isvalid` */
#define GIT_PATH_REJECT_TRAVERSAL (1 << 0)
#define GIT_PATH_REJECT_DOT_GIT (1 << 1)
#define GIT_PATH_REJECT_SLASH (1 << 2)
#define GIT_PATH_REJECT_BACKSLASH (1 << 3)
#define GIT_PATH_REJECT_TRAILING_DOT (1 << 4)
#define GIT_PATH_REJECT_TRAILING_SPACE (1 << 5)
#define GIT_PATH_REJECT_TRAILING_COLON (1 << 6)
#define GIT_PATH_REJECT_DOS_PATHS (1 << 7)
#define GIT_PATH_REJECT_NT_CHARS (1 << 8)
#define GIT_PATH_REJECT_DOT_GIT_LITERAL (1 << 9)
#define GIT_PATH_REJECT_DOT_GIT_HFS (1 << 10)
#define GIT_PATH_REJECT_DOT_GIT_NTFS (1 << 11)
/* Default path safety for writing files to disk: since we use the
* Win32 "File Namespace" APIs ("\\?\") we need to protect from
* paths that the normal Win32 APIs would not write.
*/
#ifdef GIT_WIN32
# define GIT_PATH_REJECT_FILESYSTEM_DEFAULTS \
GIT_PATH_REJECT_TRAVERSAL | \
GIT_PATH_REJECT_BACKSLASH | \
GIT_PATH_REJECT_TRAILING_DOT | \
GIT_PATH_REJECT_TRAILING_SPACE | \
GIT_PATH_REJECT_TRAILING_COLON | \
GIT_PATH_REJECT_DOS_PATHS | \
GIT_PATH_REJECT_NT_CHARS
#else
# define GIT_PATH_REJECT_FILESYSTEM_DEFAULTS \
GIT_PATH_REJECT_TRAVERSAL
#endif
/* Paths that should never be written into the working directory. */
#define GIT_PATH_REJECT_WORKDIR_DEFAULTS \
GIT_PATH_REJECT_FILESYSTEM_DEFAULTS | GIT_PATH_REJECT_DOT_GIT
/* Paths that should never be written to the index. */
#define GIT_PATH_REJECT_INDEX_DEFAULTS \
GIT_PATH_REJECT_TRAVERSAL | GIT_PATH_REJECT_DOT_GIT
/**
* Validate a "bare" git path. This ensures that the given path is legal
* to place in the index or a tree. This should be checked by mechanisms
* like `git_index_add` and `git_treebuilder_insert` when taking user
* data, and by `git_checkout` before constructing on-disk paths.
*
* This will ensure that a git path does not contain any "unsafe" components,
* a '.' or '..' component, or a component that is ".git" (in any case).
*
* (Note: if you take or construct an on-disk path -- a workdir path,
* a path to a git repository or a reference name that could be a loose
* ref -- you should _also_ validate that with `git_path_validate_workdir`.)
*
* `repo` is optional. If specified, it will be used to determine the short
* path name to reject (if `GIT_PATH_REJECT_DOS_SHORTNAME` is specified),
* in addition to the default of "git~1".
*/
extern bool git_path_validate(
git_repository *repo,
const char *path,
uint16_t mode,
unsigned int flags);
/**
* Validate an on-disk path, taking into account that it will have a
* suffix appended (eg, `.lock`).
*/
GIT_INLINE(int) git_path_validate_filesystem_with_suffix(
const char *path,
size_t path_len,
size_t suffix_len)
{
#ifdef GIT_WIN32
size_t path_chars, total_chars;
path_chars = git_utf8_char_length(path, path_len);
if (GIT_ADD_SIZET_OVERFLOW(&total_chars, path_chars, suffix_len) ||
total_chars > MAX_PATH) {
git_error_set(GIT_ERROR_FILESYSTEM, "path too long: '%s'", path);
return -1;
}
return 0;
#else
GIT_UNUSED(path);
GIT_UNUSED(path_len);
GIT_UNUSED(suffix_len);
return 0;
#endif
}
/**
* Validate an path on the filesystem. This ensures that the given
* path is valid for the operating system/platform; for example, this
* will ensure that the given absolute path is smaller than MAX_PATH on
* Windows.
*
* For paths within the working directory, you should use ensure that
* `core.longpaths` is obeyed. Use `git_path_validate_workdir`.
*/
GIT_INLINE(int) git_path_validate_filesystem(
const char *path,
size_t path_len)
{
return git_path_validate_filesystem_with_suffix(path, path_len, 0);
}
/**
* Validate a path relative to the repo's worktree. This ensures that
* the given working tree path is valid for the operating system/platform.
* This will ensure that an absolute path is smaller than MAX_PATH on
* Windows, while keeping `core.longpaths` configuration settings in mind.
*
* This should be checked by mechamisms like `git_checkout` after
* contructing on-disk paths and before trying to write them.
*
* If the repository is null, no repository configuration is applied.
*/
extern int git_path_validate_workdir(
git_repository *repo,
const char *path);
extern int git_path_validate_workdir_with_len(
git_repository *repo,
const char *path,
size_t path_len);
extern int git_path_validate_workdir_buf(
git_repository *repo,
git_buf *buf);
/**
* Convert any backslashes into slashes
*/
int git_path_normalize_slashes(git_buf *out, const char *path);
bool git_path_supports_symlinks(const char *dir);
/**
* Validate a system file's ownership
*
* Verify that the file in question is owned by an administrator or system
* account, or at least by the current user.
*
* This function returns 0 if successful. If the file is not owned by any of
* these, or any other if there have been problems determining the file
* ownership, it returns -1.
*/
int git_path_validate_system_file_ownership(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/submodule.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_submodule_h__
#define INCLUDE_submodule_h__
#include "common.h"
#include "git2/submodule.h"
#include "git2/repository.h"
#include "futils.h"
/* Notes:
*
* Submodule information can be in four places: the index, the config files
* (both .git/config and .gitmodules), the HEAD tree, and the working
* directory.
*
* In the index:
* - submodule is found by path
* - may be missing, present, or of the wrong type
* - will have an oid if present
*
* In the HEAD tree:
* - submodule is found by path
* - may be missing, present, or of the wrong type
* - will have an oid if present
*
* In the config files:
* - submodule is found by submodule "name" which is usually the path
* - may be missing or present
* - will have a name, path, url, and other properties
*
* In the working directory:
* - submodule is found by path
* - may be missing, an empty directory, a checked out directory,
* or of the wrong type
* - if checked out, will have a HEAD oid
* - if checked out, will have git history that can be used to compare oids
* - if checked out, may have modified files and/or untracked files
*/
/**
* Description of submodule
*
* This record describes a submodule found in a repository. There should be
* an entry for every submodule found in the HEAD and index, and for every
* submodule described in .gitmodules. The fields are as follows:
*
* - `rc` tracks the refcount of how many hash table entries in the
* git_submodule_cache there are for this submodule. It only comes into
* play if the name and path of the submodule differ.
*
* - `name` is the name of the submodule from .gitmodules.
* - `path` is the path to the submodule from the repo root. It is almost
* always the same as `name`.
* - `url` is the url for the submodule.
* - `update` is a git_submodule_update_t value - see gitmodules(5) update.
* - `update_default` is the update value from the config
* - `ignore` is a git_submodule_ignore_t value - see gitmodules(5) ignore.
* - `ignore_default` is the ignore value from the config
* - `fetch_recurse` is a git_submodule_recurse_t value - see gitmodules(5)
* fetchRecurseSubmodules.
* - `fetch_recurse_default` is the recurse value from the config
*
* - `repo` is the parent repository that contains this submodule.
* - `flags` after for internal use, tracking where this submodule has been
* found (head, index, config, workdir) and known status info, etc.
* - `head_oid` is the SHA1 for the submodule path in the repo HEAD.
* - `index_oid` is the SHA1 for the submodule recorded in the index.
* - `wd_oid` is the SHA1 for the HEAD of the checked out submodule.
*
* If the submodule has been added to .gitmodules but not yet git added,
* then the `index_oid` will be zero but still marked valid. If the
* submodule has been deleted, but the delete has not been committed yet,
* then the `index_oid` will be set, but the `url` will be NULL.
*/
struct git_submodule {
git_refcount rc;
/* information from config */
char *name;
char *path; /* important: may just point to "name" string */
char *url;
char *branch;
git_submodule_update_t update;
git_submodule_update_t update_default;
git_submodule_ignore_t ignore;
git_submodule_ignore_t ignore_default;
git_submodule_recurse_t fetch_recurse;
git_submodule_recurse_t fetch_recurse_default;
/* internal information */
git_repository *repo;
uint32_t flags;
git_oid head_oid;
git_oid index_oid;
git_oid wd_oid;
};
/* Additional flags on top of public GIT_SUBMODULE_STATUS values */
enum {
GIT_SUBMODULE_STATUS__WD_SCANNED = (1u << 20),
GIT_SUBMODULE_STATUS__HEAD_OID_VALID = (1u << 21),
GIT_SUBMODULE_STATUS__INDEX_OID_VALID = (1u << 22),
GIT_SUBMODULE_STATUS__WD_OID_VALID = (1u << 23),
GIT_SUBMODULE_STATUS__HEAD_NOT_SUBMODULE = (1u << 24),
GIT_SUBMODULE_STATUS__INDEX_NOT_SUBMODULE = (1u << 25),
GIT_SUBMODULE_STATUS__WD_NOT_SUBMODULE = (1u << 26),
GIT_SUBMODULE_STATUS__INDEX_MULTIPLE_ENTRIES = (1u << 27),
};
#define GIT_SUBMODULE_STATUS__CLEAR_INTERNAL(S) \
((S) & ~(0xFFFFFFFFu << 20))
/* Initialize an external submodule cache for the provided repo. */
extern int git_submodule_cache_init(git_strmap **out, git_repository *repo);
/* Release the resources of the submodule cache. */
extern int git_submodule_cache_free(git_strmap *cache);
/* Submodule lookup with an explicit cache */
extern int git_submodule__lookup_with_cache(
git_submodule **out, git_repository *repo, const char *path, git_strmap *cache);
/* Internal status fn returns status and optionally the various OIDs */
extern int git_submodule__status(
unsigned int *out_status,
git_oid *out_head_id,
git_oid *out_index_id,
git_oid *out_wd_id,
git_submodule *sm,
git_submodule_ignore_t ign);
/* Open submodule repository as bare repo for quick HEAD check, etc. */
extern int git_submodule_open_bare(
git_repository **repo,
git_submodule *submodule);
extern int git_submodule_parse_ignore(
git_submodule_ignore_t *out, const char *value);
extern int git_submodule_parse_update(
git_submodule_update_t *out, const char *value);
extern int git_submodule__map(
git_repository *repo,
git_strmap *map);
/**
* Check whether a submodule's name is valid.
*
* Check the path against the path validity rules, either the filesystem
* defaults (like checkout does) or whichever you want to compare against.
*
* @param repo the repository which contains the submodule
* @param name the name to check
* @param flags the `GIT_PATH` flags to use for the check (0 to use filesystem defaults)
*/
extern int git_submodule_name_is_valid(git_repository *repo, const char *name, 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/regexp.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_regexp_h__
#define INCLUDE_regexp_h__
#include "common.h"
#if defined(GIT_REGEX_BUILTIN) || defined(GIT_REGEX_PCRE)
# include "pcre.h"
typedef pcre *git_regexp;
# define GIT_REGEX_INIT NULL
#elif defined(GIT_REGEX_PCRE2)
# define PCRE2_CODE_UNIT_WIDTH 8
# include <pcre2.h>
typedef pcre2_code *git_regexp;
# define GIT_REGEX_INIT NULL
#elif defined(GIT_REGEX_REGCOMP) || defined(GIT_REGEX_REGCOMP_L)
# include <regex.h>
typedef regex_t git_regexp;
# define GIT_REGEX_INIT { 0 }
#else
# error "No regex backend"
#endif
/** Options supported by @git_regexp_compile. */
typedef enum {
/** Enable case-insensitive matching */
GIT_REGEXP_ICASE = (1 << 0)
} git_regexp_flags_t;
/** Structure containing information about regular expression matching groups */
typedef struct {
/** Start of the given match. -1 if the group didn't match anything */
ssize_t start;
/** End of the given match. -1 if the group didn't match anything */
ssize_t end;
} git_regmatch;
/**
* Compile a regular expression. The compiled expression needs to
* be cleaned up afterwards with `git_regexp_dispose`.
*
* @param r Pointer to the storage where to initialize the regular expression.
* @param pattern The pattern that shall be compiled.
* @param flags Flags to alter how the pattern shall be handled.
* 0 for defaults, otherwise see @git_regexp_flags_t.
* @return 0 on success, otherwise a negative return value.
*/
int git_regexp_compile(git_regexp *r, const char *pattern, int flags);
/**
* Free memory associated with the regular expression
*
* @param r The regular expression structure to dispose.
*/
void git_regexp_dispose(git_regexp *r);
/**
* Test whether a given string matches a compiled regular
* expression.
*
* @param r Compiled regular expression.
* @param string String to match against the regular expression.
* @return 0 if the string matches, a negative error code
* otherwise. GIT_ENOTFOUND if no match was found,
* GIT_EINVALIDSPEC if the regular expression matching
* was invalid.
*/
int git_regexp_match(const git_regexp *r, const char *string);
/**
* Search for matches inside of a given string.
*
* Given a regular expression with capturing groups, this
* function will populate provided @git_regmatch structures with
* offsets for each of the given matches. Non-matching groups
* will have start and end values of the respective @git_regmatch
* structure set to -1.
*
* @param r Compiled regular expression.
* @param string String to match against the regular expression.
* @param nmatches Number of @git_regmatch structures provided by
* the user.
* @param matches Pointer to an array of @git_regmatch structures.
* @return 0 if the string matches, a negative error code
* otherwise. GIT_ENOTFOUND if no match was found,
* GIT_EINVALIDSPEC if the regular expression matching
* was invalid.
*/
int git_regexp_search(const git_regexp *r, const char *string, size_t nmatches, git_regmatch *matches);
#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/attrcache.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 "attrcache.h"
#include "repository.h"
#include "attr_file.h"
#include "config.h"
#include "sysdir.h"
#include "ignore.h"
GIT_INLINE(int) attr_cache_lock(git_attr_cache *cache)
{
GIT_UNUSED(cache); /* avoid warning if threading is off */
if (git_mutex_lock(&cache->lock) < 0) {
git_error_set(GIT_ERROR_OS, "unable to get attr cache lock");
return -1;
}
return 0;
}
GIT_INLINE(void) attr_cache_unlock(git_attr_cache *cache)
{
GIT_UNUSED(cache); /* avoid warning if threading is off */
git_mutex_unlock(&cache->lock);
}
GIT_INLINE(git_attr_file_entry *) attr_cache_lookup_entry(
git_attr_cache *cache, const char *path)
{
return git_strmap_get(cache->files, path);
}
int git_attr_cache__alloc_file_entry(
git_attr_file_entry **out,
git_repository *repo,
const char *base,
const char *path,
git_pool *pool)
{
size_t baselen = 0, pathlen = strlen(path);
size_t cachesize = sizeof(git_attr_file_entry) + pathlen + 1;
git_attr_file_entry *ce;
if (base != NULL && git_path_root(path) < 0) {
baselen = strlen(base);
cachesize += baselen;
if (baselen && base[baselen - 1] != '/')
cachesize++;
}
ce = git_pool_mallocz(pool, cachesize);
GIT_ERROR_CHECK_ALLOC(ce);
if (baselen) {
memcpy(ce->fullpath, base, baselen);
if (base[baselen - 1] != '/')
ce->fullpath[baselen++] = '/';
}
memcpy(&ce->fullpath[baselen], path, pathlen);
if (git_path_validate_workdir_with_len(repo, ce->fullpath, pathlen + baselen) < 0)
return -1;
ce->path = &ce->fullpath[baselen];
*out = ce;
return 0;
}
/* call with attrcache locked */
static int attr_cache_make_entry(
git_attr_file_entry **out, git_repository *repo, const char *path)
{
git_attr_cache *cache = git_repository_attr_cache(repo);
git_attr_file_entry *entry = NULL;
int error;
if ((error = git_attr_cache__alloc_file_entry(&entry, repo,
git_repository_workdir(repo), path, &cache->pool)) < 0)
return error;
if ((error = git_strmap_set(cache->files, entry->path, entry)) < 0)
return error;
*out = entry;
return error;
}
/* insert entry or replace existing if we raced with another thread */
static int attr_cache_upsert(git_attr_cache *cache, git_attr_file *file)
{
git_attr_file_entry *entry;
git_attr_file *old;
if (attr_cache_lock(cache) < 0)
return -1;
entry = attr_cache_lookup_entry(cache, file->entry->path);
GIT_REFCOUNT_OWN(file, entry);
GIT_REFCOUNT_INC(file);
/*
* Replace the existing value if another thread has
* created it in the meantime.
*/
old = git_atomic_swap(entry->file[file->source.type], file);
if (old) {
GIT_REFCOUNT_OWN(old, NULL);
git_attr_file__free(old);
}
attr_cache_unlock(cache);
return 0;
}
static int attr_cache_remove(git_attr_cache *cache, git_attr_file *file)
{
int error = 0;
git_attr_file_entry *entry;
git_attr_file *oldfile = NULL;
if (!file)
return 0;
if ((error = attr_cache_lock(cache)) < 0)
return error;
if ((entry = attr_cache_lookup_entry(cache, file->entry->path)) != NULL)
oldfile = git_atomic_compare_and_swap(&entry->file[file->source.type], file, NULL);
attr_cache_unlock(cache);
if (oldfile == file) {
GIT_REFCOUNT_OWN(file, NULL);
git_attr_file__free(file);
}
return error;
}
/* Look up cache entry and file.
* - If entry is not present, create it while the cache is locked.
* - If file is present, increment refcount before returning it, so the
* cache can be unlocked and it won't go away.
*/
static int attr_cache_lookup(
git_attr_file **out_file,
git_attr_file_entry **out_entry,
git_repository *repo,
git_attr_session *attr_session,
git_attr_file_source *source)
{
int error = 0;
git_buf path = GIT_BUF_INIT;
const char *wd = git_repository_workdir(repo);
const char *filename;
git_attr_cache *cache = git_repository_attr_cache(repo);
git_attr_file_entry *entry = NULL;
git_attr_file *file = NULL;
/* join base and path as needed */
if (source->base != NULL && git_path_root(source->filename) < 0) {
git_buf *p = attr_session ? &attr_session->tmp : &path;
if (git_buf_joinpath(p, source->base, source->filename) < 0 ||
git_path_validate_workdir_buf(repo, p) < 0)
return -1;
filename = p->ptr;
} else {
filename = source->filename;
}
if (wd && !git__prefixcmp(filename, wd))
filename += strlen(wd);
/* check cache for existing entry */
if ((error = attr_cache_lock(cache)) < 0)
goto cleanup;
entry = attr_cache_lookup_entry(cache, filename);
if (!entry) {
error = attr_cache_make_entry(&entry, repo, filename);
} else if (entry->file[source->type] != NULL) {
file = entry->file[source->type];
GIT_REFCOUNT_INC(file);
}
attr_cache_unlock(cache);
cleanup:
*out_file = file;
*out_entry = entry;
git_buf_dispose(&path);
return error;
}
int git_attr_cache__get(
git_attr_file **out,
git_repository *repo,
git_attr_session *attr_session,
git_attr_file_source *source,
git_attr_file_parser parser,
bool allow_macros)
{
int error = 0;
git_attr_cache *cache = git_repository_attr_cache(repo);
git_attr_file_entry *entry = NULL;
git_attr_file *file = NULL, *updated = NULL;
if ((error = attr_cache_lookup(&file, &entry, repo, attr_session, source)) < 0)
return error;
/* load file if we don't have one or if existing one is out of date */
if (!file ||
(error = git_attr_file__out_of_date(repo, attr_session, file, source)) > 0)
error = git_attr_file__load(&updated, repo, attr_session,
entry, source, parser,
allow_macros);
/* if we loaded the file, insert into and/or update cache */
if (updated) {
if ((error = attr_cache_upsert(cache, updated)) < 0) {
git_attr_file__free(updated);
} else {
git_attr_file__free(file); /* offset incref from lookup */
file = updated;
}
}
/* if file could not be loaded */
if (error < 0) {
/* remove existing entry */
if (file) {
attr_cache_remove(cache, file);
git_attr_file__free(file); /* offset incref from lookup */
file = NULL;
}
/* no error if file simply doesn't exist */
if (error == GIT_ENOTFOUND) {
git_error_clear();
error = 0;
}
}
*out = file;
return error;
}
bool git_attr_cache__is_cached(
git_repository *repo,
git_attr_file_source_t source_type,
const char *filename)
{
git_attr_cache *cache = git_repository_attr_cache(repo);
git_attr_file_entry *entry;
git_strmap *files;
if (!cache || !(files = cache->files))
return false;
if ((entry = git_strmap_get(files, filename)) == NULL)
return false;
return entry && (entry->file[source_type] != NULL);
}
static int attr_cache__lookup_path(
char **out, git_config *cfg, const char *key, const char *fallback)
{
git_buf buf = GIT_BUF_INIT;
int error;
git_config_entry *entry = NULL;
*out = NULL;
if ((error = git_config__lookup_entry(&entry, cfg, key, false)) < 0)
return error;
if (entry) {
const char *cfgval = entry->value;
/* expand leading ~/ as needed */
if (cfgval && cfgval[0] == '~' && cfgval[1] == '/') {
if (! (error = git_sysdir_expand_global_file(&buf, &cfgval[2])))
*out = git_buf_detach(&buf);
} else if (cfgval) {
*out = git__strdup(cfgval);
}
}
else if (!git_sysdir_find_xdg_file(&buf, fallback)) {
*out = git_buf_detach(&buf);
}
git_config_entry_free(entry);
git_buf_dispose(&buf);
return error;
}
static void attr_cache__free(git_attr_cache *cache)
{
bool unlock;
if (!cache)
return;
unlock = (attr_cache_lock(cache) == 0);
if (cache->files != NULL) {
git_attr_file_entry *entry;
git_attr_file *file;
int i;
git_strmap_foreach_value(cache->files, entry, {
for (i = 0; i < GIT_ATTR_FILE_NUM_SOURCES; ++i) {
if ((file = git_atomic_swap(entry->file[i], NULL)) != NULL) {
GIT_REFCOUNT_OWN(file, NULL);
git_attr_file__free(file);
}
}
});
git_strmap_free(cache->files);
}
if (cache->macros != NULL) {
git_attr_rule *rule;
git_strmap_foreach_value(cache->macros, rule, {
git_attr_rule__free(rule);
});
git_strmap_free(cache->macros);
}
git_pool_clear(&cache->pool);
git__free(cache->cfg_attr_file);
cache->cfg_attr_file = NULL;
git__free(cache->cfg_excl_file);
cache->cfg_excl_file = NULL;
if (unlock)
attr_cache_unlock(cache);
git_mutex_free(&cache->lock);
git__free(cache);
}
int git_attr_cache__init(git_repository *repo)
{
int ret = 0;
git_attr_cache *cache = git_repository_attr_cache(repo);
git_config *cfg = NULL;
if (cache)
return 0;
cache = git__calloc(1, sizeof(git_attr_cache));
GIT_ERROR_CHECK_ALLOC(cache);
/* set up lock */
if (git_mutex_init(&cache->lock) < 0) {
git_error_set(GIT_ERROR_OS, "unable to initialize lock for attr cache");
git__free(cache);
return -1;
}
if ((ret = git_repository_config_snapshot(&cfg, repo)) < 0)
goto cancel;
/* cache config settings for attributes and ignores */
ret = attr_cache__lookup_path(
&cache->cfg_attr_file, cfg, GIT_ATTR_CONFIG, GIT_ATTR_FILE_XDG);
if (ret < 0)
goto cancel;
ret = attr_cache__lookup_path(
&cache->cfg_excl_file, cfg, GIT_IGNORE_CONFIG, GIT_IGNORE_FILE_XDG);
if (ret < 0)
goto cancel;
/* allocate hashtable for attribute and ignore file contents,
* hashtable for attribute macros, and string pool
*/
if ((ret = git_strmap_new(&cache->files)) < 0 ||
(ret = git_strmap_new(&cache->macros)) < 0 ||
(ret = git_pool_init(&cache->pool, 1)) < 0)
goto cancel;
if (git_atomic_compare_and_swap(&repo->attrcache, NULL, cache) != NULL)
goto cancel; /* raced with another thread, free this but no error */
git_config_free(cfg);
/* insert default macros */
return git_attr_add_macro(repo, "binary", "-diff -merge -text -crlf");
cancel:
attr_cache__free(cache);
git_config_free(cfg);
return ret;
}
int git_attr_cache_flush(git_repository *repo)
{
git_attr_cache *cache;
/* this could be done less expensively, but for now, we'll just free
* the entire attrcache and let the next use reinitialize it...
*/
if (repo && (cache = git_atomic_swap(repo->attrcache, NULL)) != NULL)
attr_cache__free(cache);
return 0;
}
int git_attr_cache__insert_macro(git_repository *repo, git_attr_rule *macro)
{
git_attr_cache *cache = git_repository_attr_cache(repo);
git_attr_rule *preexisting;
bool locked = false;
int error = 0;
/*
* Callers assume that if we return success, that the
* macro will have been adopted by the attributes cache.
* Thus, we have to free the macro here if it's not being
* added to the cache.
*
* TODO: generate warning log if (macro->assigns.length == 0)
*/
if (macro->assigns.length == 0) {
git_attr_rule__free(macro);
goto out;
}
if ((error = attr_cache_lock(cache)) < 0)
goto out;
locked = true;
if ((preexisting = git_strmap_get(cache->macros, macro->match.pattern)) != NULL)
git_attr_rule__free(preexisting);
if ((error = git_strmap_set(cache->macros, macro->match.pattern, macro)) < 0)
goto out;
out:
if (locked)
attr_cache_unlock(cache);
return error;
}
git_attr_rule *git_attr_cache__lookup_macro(
git_repository *repo, const char *name)
{
git_strmap *macros = git_repository_attr_cache(repo)->macros;
return git_strmap_get(macros, name);
}
|
0 |
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2
|
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2/src/date.c
|
/*
* GIT - The information manager from hell
*
* Copyright (C) Linus Torvalds, 2005
*/
#include "common.h"
#ifndef GIT_WIN32
#include <sys/time.h>
#endif
#include "util.h"
#include "cache.h"
#include "posix.h"
#include <ctype.h>
#include <time.h>
typedef enum {
DATE_NORMAL = 0,
DATE_RELATIVE,
DATE_SHORT,
DATE_LOCAL,
DATE_ISO8601,
DATE_RFC2822,
DATE_RAW
} date_mode;
/*
* This is like mktime, but without normalization of tm_wday and tm_yday.
*/
static git_time_t tm_to_time_t(const struct tm *tm)
{
static const int mdays[] = {
0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334
};
int year = tm->tm_year - 70;
int month = tm->tm_mon;
int day = tm->tm_mday;
if (year < 0 || year > 129) /* algo only works for 1970-2099 */
return -1;
if (month < 0 || month > 11) /* array bounds */
return -1;
if (month < 2 || (year + 2) % 4)
day--;
if (tm->tm_hour < 0 || tm->tm_min < 0 || tm->tm_sec < 0)
return -1;
return (year * 365 + (year + 1) / 4 + mdays[month] + day) * 24*60*60UL +
tm->tm_hour * 60*60 + tm->tm_min * 60 + tm->tm_sec;
}
static const char *month_names[] = {
"January", "February", "March", "April", "May", "June",
"July", "August", "September", "October", "November", "December"
};
static const char *weekday_names[] = {
"Sundays", "Mondays", "Tuesdays", "Wednesdays", "Thursdays", "Fridays", "Saturdays"
};
/*
* Check these. And note how it doesn't do the summer-time conversion.
*
* In my world, it's always summer, and things are probably a bit off
* in other ways too.
*/
static const struct {
const char *name;
int offset;
int dst;
} timezone_names[] = {
{ "IDLW", -12, 0, }, /* International Date Line West */
{ "NT", -11, 0, }, /* Nome */
{ "CAT", -10, 0, }, /* Central Alaska */
{ "HST", -10, 0, }, /* Hawaii Standard */
{ "HDT", -10, 1, }, /* Hawaii Daylight */
{ "YST", -9, 0, }, /* Yukon Standard */
{ "YDT", -9, 1, }, /* Yukon Daylight */
{ "PST", -8, 0, }, /* Pacific Standard */
{ "PDT", -8, 1, }, /* Pacific Daylight */
{ "MST", -7, 0, }, /* Mountain Standard */
{ "MDT", -7, 1, }, /* Mountain Daylight */
{ "CST", -6, 0, }, /* Central Standard */
{ "CDT", -6, 1, }, /* Central Daylight */
{ "EST", -5, 0, }, /* Eastern Standard */
{ "EDT", -5, 1, }, /* Eastern Daylight */
{ "AST", -3, 0, }, /* Atlantic Standard */
{ "ADT", -3, 1, }, /* Atlantic Daylight */
{ "WAT", -1, 0, }, /* West Africa */
{ "GMT", 0, 0, }, /* Greenwich Mean */
{ "UTC", 0, 0, }, /* Universal (Coordinated) */
{ "Z", 0, 0, }, /* Zulu, alias for UTC */
{ "WET", 0, 0, }, /* Western European */
{ "BST", 0, 1, }, /* British Summer */
{ "CET", +1, 0, }, /* Central European */
{ "MET", +1, 0, }, /* Middle European */
{ "MEWT", +1, 0, }, /* Middle European Winter */
{ "MEST", +1, 1, }, /* Middle European Summer */
{ "CEST", +1, 1, }, /* Central European Summer */
{ "MESZ", +1, 1, }, /* Middle European Summer */
{ "FWT", +1, 0, }, /* French Winter */
{ "FST", +1, 1, }, /* French Summer */
{ "EET", +2, 0, }, /* Eastern Europe */
{ "EEST", +2, 1, }, /* Eastern European Daylight */
{ "WAST", +7, 0, }, /* West Australian Standard */
{ "WADT", +7, 1, }, /* West Australian Daylight */
{ "CCT", +8, 0, }, /* China Coast */
{ "JST", +9, 0, }, /* Japan Standard */
{ "EAST", +10, 0, }, /* Eastern Australian Standard */
{ "EADT", +10, 1, }, /* Eastern Australian Daylight */
{ "GST", +10, 0, }, /* Guam Standard */
{ "NZT", +12, 0, }, /* New Zealand */
{ "NZST", +12, 0, }, /* New Zealand Standard */
{ "NZDT", +12, 1, }, /* New Zealand Daylight */
{ "IDLE", +12, 0, }, /* International Date Line East */
};
static size_t match_string(const char *date, const char *str)
{
size_t i = 0;
for (i = 0; *date; date++, str++, i++) {
if (*date == *str)
continue;
if (toupper(*date) == toupper(*str))
continue;
if (!isalnum(*date))
break;
return 0;
}
return i;
}
static int skip_alpha(const char *date)
{
int i = 0;
do {
i++;
} while (isalpha(date[i]));
return i;
}
/*
* Parse month, weekday, or timezone name
*/
static size_t match_alpha(const char *date, struct tm *tm, int *offset)
{
unsigned int i;
for (i = 0; i < 12; i++) {
size_t match = match_string(date, month_names[i]);
if (match >= 3) {
tm->tm_mon = i;
return match;
}
}
for (i = 0; i < 7; i++) {
size_t match = match_string(date, weekday_names[i]);
if (match >= 3) {
tm->tm_wday = i;
return match;
}
}
for (i = 0; i < ARRAY_SIZE(timezone_names); i++) {
size_t match = match_string(date, timezone_names[i].name);
if (match >= 3 || match == strlen(timezone_names[i].name)) {
int off = timezone_names[i].offset;
/* This is bogus, but we like summer */
off += timezone_names[i].dst;
/* Only use the tz name offset if we don't have anything better */
if (*offset == -1)
*offset = 60*off;
return match;
}
}
if (match_string(date, "PM") == 2) {
tm->tm_hour = (tm->tm_hour % 12) + 12;
return 2;
}
if (match_string(date, "AM") == 2) {
tm->tm_hour = (tm->tm_hour % 12) + 0;
return 2;
}
/* BAD */
return skip_alpha(date);
}
static int is_date(int year, int month, int day, struct tm *now_tm, time_t now, struct tm *tm)
{
if (month > 0 && month < 13 && day > 0 && day < 32) {
struct tm check = *tm;
struct tm *r = (now_tm ? &check : tm);
git_time_t specified;
r->tm_mon = month - 1;
r->tm_mday = day;
if (year == -1) {
if (!now_tm)
return 1;
r->tm_year = now_tm->tm_year;
}
else if (year >= 1970 && year < 2100)
r->tm_year = year - 1900;
else if (year > 70 && year < 100)
r->tm_year = year;
else if (year < 38)
r->tm_year = year + 100;
else
return 0;
if (!now_tm)
return 1;
specified = tm_to_time_t(r);
/* Be it commit time or author time, it does not make
* sense to specify timestamp way into the future. Make
* sure it is not later than ten days from now...
*/
if (now + 10*24*3600 < specified)
return 0;
tm->tm_mon = r->tm_mon;
tm->tm_mday = r->tm_mday;
if (year != -1)
tm->tm_year = r->tm_year;
return 1;
}
return 0;
}
static size_t match_multi_number(unsigned long num, char c, const char *date, char *end, struct tm *tm)
{
time_t now;
struct tm now_tm;
struct tm *refuse_future;
long num2, num3;
num2 = strtol(end+1, &end, 10);
num3 = -1;
if (*end == c && isdigit(end[1]))
num3 = strtol(end+1, &end, 10);
/* Time? Date? */
switch (c) {
case ':':
if (num3 < 0)
num3 = 0;
if (num < 25 && num2 >= 0 && num2 < 60 && num3 >= 0 && num3 <= 60) {
tm->tm_hour = num;
tm->tm_min = num2;
tm->tm_sec = num3;
break;
}
return 0;
case '-':
case '/':
case '.':
now = time(NULL);
refuse_future = NULL;
if (p_gmtime_r(&now, &now_tm))
refuse_future = &now_tm;
if (num > 70) {
/* yyyy-mm-dd? */
if (is_date(num, num2, num3, refuse_future, now, tm))
break;
/* yyyy-dd-mm? */
if (is_date(num, num3, num2, refuse_future, now, tm))
break;
}
/* Our eastern European friends say dd.mm.yy[yy]
* is the norm there, so giving precedence to
* mm/dd/yy[yy] form only when separator is not '.'
*/
if (c != '.' &&
is_date(num3, num, num2, refuse_future, now, tm))
break;
/* European dd.mm.yy[yy] or funny US dd/mm/yy[yy] */
if (is_date(num3, num2, num, refuse_future, now, tm))
break;
/* Funny European mm.dd.yy */
if (c == '.' &&
is_date(num3, num, num2, refuse_future, now, tm))
break;
return 0;
}
return end - date;
}
/*
* Have we filled in any part of the time/date yet?
* We just do a binary 'and' to see if the sign bit
* is set in all the values.
*/
static int nodate(struct tm *tm)
{
return (tm->tm_year &
tm->tm_mon &
tm->tm_mday &
tm->tm_hour &
tm->tm_min &
tm->tm_sec) < 0;
}
/*
* We've seen a digit. Time? Year? Date?
*/
static size_t match_digit(const char *date, struct tm *tm, int *offset, int *tm_gmt)
{
size_t n;
char *end;
unsigned long num;
num = strtoul(date, &end, 10);
/*
* Seconds since 1970? We trigger on that for any numbers with
* more than 8 digits. This is because we don't want to rule out
* numbers like 20070606 as a YYYYMMDD date.
*/
if (num >= 100000000 && nodate(tm)) {
time_t time = num;
if (p_gmtime_r(&time, tm)) {
*tm_gmt = 1;
return end - date;
}
}
/*
* Check for special formats: num[-.:/]num[same]num
*/
switch (*end) {
case ':':
case '.':
case '/':
case '-':
if (isdigit(end[1])) {
size_t match = match_multi_number(num, *end, date, end, tm);
if (match)
return match;
}
}
/*
* None of the special formats? Try to guess what
* the number meant. We use the number of digits
* to make a more educated guess..
*/
n = 0;
do {
n++;
} while (isdigit(date[n]));
/* Four-digit year or a timezone? */
if (n == 4) {
if (num <= 1400 && *offset == -1) {
unsigned int minutes = num % 100;
unsigned int hours = num / 100;
*offset = hours*60 + minutes;
} else if (num > 1900 && num < 2100)
tm->tm_year = num - 1900;
return n;
}
/*
* Ignore lots of numerals. We took care of 4-digit years above.
* Days or months must be one or two digits.
*/
if (n > 2)
return n;
/*
* NOTE! We will give precedence to day-of-month over month or
* year numbers in the 1-12 range. So 05 is always "mday 5",
* unless we already have a mday..
*
* IOW, 01 Apr 05 parses as "April 1st, 2005".
*/
if (num > 0 && num < 32 && tm->tm_mday < 0) {
tm->tm_mday = num;
return n;
}
/* Two-digit year? */
if (n == 2 && tm->tm_year < 0) {
if (num < 10 && tm->tm_mday >= 0) {
tm->tm_year = num + 100;
return n;
}
if (num >= 70) {
tm->tm_year = num;
return n;
}
}
if (num > 0 && num < 13 && tm->tm_mon < 0)
tm->tm_mon = num-1;
return n;
}
static size_t match_tz(const char *date, int *offp)
{
char *end;
int hour = strtoul(date + 1, &end, 10);
size_t n = end - (date + 1);
int min = 0;
if (n == 4) {
/* hhmm */
min = hour % 100;
hour = hour / 100;
} else if (n != 2) {
min = 99; /* random stuff */
} else if (*end == ':') {
/* hh:mm? */
min = strtoul(end + 1, &end, 10);
if (end - (date + 1) != 5)
min = 99; /* random stuff */
} /* otherwise we parsed "hh" */
/*
* Don't accept any random stuff. Even though some places have
* offset larger than 12 hours (e.g. Pacific/Kiritimati is at
* UTC+14), there is something wrong if hour part is much
* larger than that. We might also want to check that the
* minutes are divisible by 15 or something too. (Offset of
* Kathmandu, Nepal is UTC+5:45)
*/
if (min < 60 && hour < 24) {
int offset = hour * 60 + min;
if (*date == '-')
offset = -offset;
*offp = offset;
}
return end - date;
}
/*
* Parse a string like "0 +0000" as ancient timestamp near epoch, but
* only when it appears not as part of any other string.
*/
static int match_object_header_date(const char *date, git_time_t *timestamp, int *offset)
{
char *end;
unsigned long stamp;
int ofs;
if (*date < '0' || '9' <= *date)
return -1;
stamp = strtoul(date, &end, 10);
if (*end != ' ' || stamp == ULONG_MAX || (end[1] != '+' && end[1] != '-'))
return -1;
date = end + 2;
ofs = strtol(date, &end, 10);
if ((*end != '\0' && (*end != '\n')) || end != date + 4)
return -1;
ofs = (ofs / 100) * 60 + (ofs % 100);
if (date[-1] == '-')
ofs = -ofs;
*timestamp = stamp;
*offset = ofs;
return 0;
}
/* Gr. strptime is crap for this; it doesn't have a way to require RFC2822
(i.e. English) day/month names, and it doesn't work correctly with %z. */
static int parse_date_basic(const char *date, git_time_t *timestamp, int *offset)
{
struct tm tm;
int tm_gmt;
git_time_t dummy_timestamp;
int dummy_offset;
if (!timestamp)
timestamp = &dummy_timestamp;
if (!offset)
offset = &dummy_offset;
memset(&tm, 0, sizeof(tm));
tm.tm_year = -1;
tm.tm_mon = -1;
tm.tm_mday = -1;
tm.tm_isdst = -1;
tm.tm_hour = -1;
tm.tm_min = -1;
tm.tm_sec = -1;
*offset = -1;
tm_gmt = 0;
if (*date == '@' &&
!match_object_header_date(date + 1, timestamp, offset))
return 0; /* success */
for (;;) {
size_t match = 0;
unsigned char c = *date;
/* Stop at end of string or newline */
if (!c || c == '\n')
break;
if (isalpha(c))
match = match_alpha(date, &tm, offset);
else if (isdigit(c))
match = match_digit(date, &tm, offset, &tm_gmt);
else if ((c == '-' || c == '+') && isdigit(date[1]))
match = match_tz(date, offset);
if (!match) {
/* BAD */
match = 1;
}
date += match;
}
/* mktime uses local timezone */
*timestamp = tm_to_time_t(&tm);
if (*offset == -1)
*offset = (int)((time_t)*timestamp - mktime(&tm)) / 60;
if (*timestamp == (git_time_t)-1)
return -1;
if (!tm_gmt)
*timestamp -= *offset * 60;
return 0; /* success */
}
/*
* Relative time update (eg "2 days ago"). If we haven't set the time
* yet, we need to set it from current time.
*/
static git_time_t update_tm(struct tm *tm, struct tm *now, unsigned long sec)
{
time_t n;
if (tm->tm_mday < 0)
tm->tm_mday = now->tm_mday;
if (tm->tm_mon < 0)
tm->tm_mon = now->tm_mon;
if (tm->tm_year < 0) {
tm->tm_year = now->tm_year;
if (tm->tm_mon > now->tm_mon)
tm->tm_year--;
}
n = mktime(tm) - sec;
p_localtime_r(&n, tm);
return n;
}
static void date_now(struct tm *tm, struct tm *now, int *num)
{
GIT_UNUSED(num);
update_tm(tm, now, 0);
}
static void date_yesterday(struct tm *tm, struct tm *now, int *num)
{
GIT_UNUSED(num);
update_tm(tm, now, 24*60*60);
}
static void date_time(struct tm *tm, struct tm *now, int hour)
{
if (tm->tm_hour < hour)
date_yesterday(tm, now, NULL);
tm->tm_hour = hour;
tm->tm_min = 0;
tm->tm_sec = 0;
}
static void date_midnight(struct tm *tm, struct tm *now, int *num)
{
GIT_UNUSED(num);
date_time(tm, now, 0);
}
static void date_noon(struct tm *tm, struct tm *now, int *num)
{
GIT_UNUSED(num);
date_time(tm, now, 12);
}
static void date_tea(struct tm *tm, struct tm *now, int *num)
{
GIT_UNUSED(num);
date_time(tm, now, 17);
}
static void date_pm(struct tm *tm, struct tm *now, int *num)
{
int hour, n = *num;
*num = 0;
GIT_UNUSED(now);
hour = tm->tm_hour;
if (n) {
hour = n;
tm->tm_min = 0;
tm->tm_sec = 0;
}
tm->tm_hour = (hour % 12) + 12;
}
static void date_am(struct tm *tm, struct tm *now, int *num)
{
int hour, n = *num;
*num = 0;
GIT_UNUSED(now);
hour = tm->tm_hour;
if (n) {
hour = n;
tm->tm_min = 0;
tm->tm_sec = 0;
}
tm->tm_hour = (hour % 12);
}
static void date_never(struct tm *tm, struct tm *now, int *num)
{
time_t n = 0;
GIT_UNUSED(now);
GIT_UNUSED(num);
p_localtime_r(&n, tm);
}
static const struct special {
const char *name;
void (*fn)(struct tm *, struct tm *, int *);
} special[] = {
{ "yesterday", date_yesterday },
{ "noon", date_noon },
{ "midnight", date_midnight },
{ "tea", date_tea },
{ "PM", date_pm },
{ "AM", date_am },
{ "never", date_never },
{ "now", date_now },
{ NULL }
};
static const char *number_name[] = {
"zero", "one", "two", "three", "four",
"five", "six", "seven", "eight", "nine", "ten",
};
static const struct typelen {
const char *type;
int length;
} typelen[] = {
{ "seconds", 1 },
{ "minutes", 60 },
{ "hours", 60*60 },
{ "days", 24*60*60 },
{ "weeks", 7*24*60*60 },
{ NULL }
};
static const char *approxidate_alpha(const char *date, struct tm *tm, struct tm *now, int *num, int *touched)
{
const struct typelen *tl;
const struct special *s;
const char *end = date;
int i;
while (isalpha(*++end))
/* scan to non-alpha */;
for (i = 0; i < 12; i++) {
size_t match = match_string(date, month_names[i]);
if (match >= 3) {
tm->tm_mon = i;
*touched = 1;
return end;
}
}
for (s = special; s->name; s++) {
size_t len = strlen(s->name);
if (match_string(date, s->name) == len) {
s->fn(tm, now, num);
*touched = 1;
return end;
}
}
if (!*num) {
for (i = 1; i < 11; i++) {
size_t len = strlen(number_name[i]);
if (match_string(date, number_name[i]) == len) {
*num = i;
*touched = 1;
return end;
}
}
if (match_string(date, "last") == 4) {
*num = 1;
*touched = 1;
}
return end;
}
tl = typelen;
while (tl->type) {
size_t len = strlen(tl->type);
if (match_string(date, tl->type) >= len-1) {
update_tm(tm, now, tl->length * (unsigned long)*num);
*num = 0;
*touched = 1;
return end;
}
tl++;
}
for (i = 0; i < 7; i++) {
size_t match = match_string(date, weekday_names[i]);
if (match >= 3) {
int diff, n = *num -1;
*num = 0;
diff = tm->tm_wday - i;
if (diff <= 0)
n++;
diff += 7*n;
update_tm(tm, now, diff * 24 * 60 * 60);
*touched = 1;
return end;
}
}
if (match_string(date, "months") >= 5) {
int n;
update_tm(tm, now, 0); /* fill in date fields if needed */
n = tm->tm_mon - *num;
*num = 0;
while (n < 0) {
n += 12;
tm->tm_year--;
}
tm->tm_mon = n;
*touched = 1;
return end;
}
if (match_string(date, "years") >= 4) {
update_tm(tm, now, 0); /* fill in date fields if needed */
tm->tm_year -= *num;
*num = 0;
*touched = 1;
return end;
}
return end;
}
static const char *approxidate_digit(const char *date, struct tm *tm, int *num)
{
char *end;
unsigned long number = strtoul(date, &end, 10);
switch (*end) {
case ':':
case '.':
case '/':
case '-':
if (isdigit(end[1])) {
size_t match = match_multi_number(number, *end, date, end, tm);
if (match)
return date + match;
}
}
/* Accept zero-padding only for small numbers ("Dec 02", never "Dec 0002") */
if (date[0] != '0' || end - date <= 2)
*num = number;
return end;
}
/*
* Do we have a pending number at the end, or when
* we see a new one? Let's assume it's a month day,
* as in "Dec 6, 1992"
*/
static void pending_number(struct tm *tm, int *num)
{
int number = *num;
if (number) {
*num = 0;
if (tm->tm_mday < 0 && number < 32)
tm->tm_mday = number;
else if (tm->tm_mon < 0 && number < 13)
tm->tm_mon = number-1;
else if (tm->tm_year < 0) {
if (number > 1969 && number < 2100)
tm->tm_year = number - 1900;
else if (number > 69 && number < 100)
tm->tm_year = number;
else if (number < 38)
tm->tm_year = 100 + number;
/* We mess up for number = 00 ? */
}
}
}
static git_time_t approxidate_str(const char *date,
time_t time_sec,
int *error_ret)
{
int number = 0;
int touched = 0;
struct tm tm = {0}, now;
p_localtime_r(&time_sec, &tm);
now = tm;
tm.tm_year = -1;
tm.tm_mon = -1;
tm.tm_mday = -1;
for (;;) {
unsigned char c = *date;
if (!c)
break;
date++;
if (isdigit(c)) {
pending_number(&tm, &number);
date = approxidate_digit(date-1, &tm, &number);
touched = 1;
continue;
}
if (isalpha(c))
date = approxidate_alpha(date-1, &tm, &now, &number, &touched);
}
pending_number(&tm, &number);
if (!touched)
*error_ret = 1;
return update_tm(&tm, &now, 0);
}
int git__date_parse(git_time_t *out, const char *date)
{
time_t time_sec;
git_time_t timestamp;
int offset, error_ret=0;
if (!parse_date_basic(date, ×tamp, &offset)) {
*out = timestamp;
return 0;
}
if (time(&time_sec) == -1)
return -1;
*out = approxidate_str(date, time_sec, &error_ret);
return error_ret;
}
int git__date_rfc2822_fmt(char *out, size_t len, const git_time *date)
{
int written;
struct tm gmt;
time_t t;
GIT_ASSERT_ARG(out);
GIT_ASSERT_ARG(date);
t = (time_t) (date->time + date->offset * 60);
if (p_gmtime_r (&t, &gmt) == NULL)
return -1;
written = p_snprintf(out, len, "%.3s, %u %.3s %.4u %02u:%02u:%02u %+03d%02d",
weekday_names[gmt.tm_wday],
gmt.tm_mday,
month_names[gmt.tm_mon],
gmt.tm_year + 1900,
gmt.tm_hour, gmt.tm_min, gmt.tm_sec,
date->offset / 60, date->offset % 60);
if (written < 0 || (written > (int) len - 1))
return -1;
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/refspec.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 "refspec.h"
#include "git2/errors.h"
#include "refs.h"
#include "util.h"
#include "vector.h"
#include "wildmatch.h"
int git_refspec__parse(git_refspec *refspec, const char *input, bool is_fetch)
{
/* Ported from https://github.com/git/git/blob/f06d47e7e0d9db709ee204ed13a8a7486149f494/remote.c#L518-636 */
size_t llen;
int is_glob = 0;
const char *lhs, *rhs;
int valid = 0;
unsigned int flags;
GIT_ASSERT_ARG(refspec);
GIT_ASSERT_ARG(input);
memset(refspec, 0x0, sizeof(git_refspec));
refspec->push = !is_fetch;
lhs = input;
if (*lhs == '+') {
refspec->force = 1;
lhs++;
}
rhs = strrchr(lhs, ':');
/*
* Before going on, special case ":" (or "+:") as a refspec
* for matching refs.
*/
if (!is_fetch && rhs == lhs && rhs[1] == '\0') {
refspec->matching = 1;
refspec->string = git__strdup(input);
GIT_ERROR_CHECK_ALLOC(refspec->string);
refspec->src = git__strdup("");
GIT_ERROR_CHECK_ALLOC(refspec->src);
refspec->dst = git__strdup("");
GIT_ERROR_CHECK_ALLOC(refspec->dst);
return 0;
}
if (rhs) {
size_t rlen = strlen(++rhs);
if (rlen || !is_fetch) {
is_glob = (1 <= rlen && strchr(rhs, '*'));
refspec->dst = git__strndup(rhs, rlen);
}
}
llen = (rhs ? (size_t)(rhs - lhs - 1) : strlen(lhs));
if (1 <= llen && memchr(lhs, '*', llen)) {
if ((rhs && !is_glob) || (!rhs && is_fetch))
goto invalid;
is_glob = 1;
} else if (rhs && is_glob)
goto invalid;
refspec->pattern = is_glob;
refspec->src = git__strndup(lhs, llen);
flags = GIT_REFERENCE_FORMAT_ALLOW_ONELEVEL |
GIT_REFERENCE_FORMAT_REFSPEC_SHORTHAND |
(is_glob ? GIT_REFERENCE_FORMAT_REFSPEC_PATTERN : 0);
if (is_fetch) {
/*
* LHS
* - empty is allowed; it means HEAD.
* - otherwise it must be a valid looking ref.
*/
if (!*refspec->src)
; /* empty is ok */
else if (git_reference__name_is_valid(&valid, refspec->src, flags) < 0)
goto on_error;
else if (!valid)
goto invalid;
/*
* RHS
* - missing is ok, and is same as empty.
* - empty is ok; it means not to store.
* - otherwise it must be a valid looking ref.
*/
if (!refspec->dst)
; /* ok */
else if (!*refspec->dst)
; /* ok */
else if (git_reference__name_is_valid(&valid, refspec->dst, flags) < 0)
goto on_error;
else if (!valid)
goto invalid;
} else {
/*
* LHS
* - empty is allowed; it means delete.
* - when wildcarded, it must be a valid looking ref.
* - otherwise, it must be an extended SHA-1, but
* there is no existing way to validate this.
*/
if (!*refspec->src)
; /* empty is ok */
else if (is_glob) {
if (git_reference__name_is_valid(&valid, refspec->src, flags) < 0)
goto on_error;
else if (!valid)
goto invalid;
}
else {
; /* anything goes, for now */
}
/*
* RHS
* - missing is allowed, but LHS then must be a
* valid looking ref.
* - empty is not allowed.
* - otherwise it must be a valid looking ref.
*/
if (!refspec->dst) {
if (git_reference__name_is_valid(&valid, refspec->src, flags) < 0)
goto on_error;
else if (!valid)
goto invalid;
} else if (!*refspec->dst) {
goto invalid;
} else {
if (git_reference__name_is_valid(&valid, refspec->dst, flags) < 0)
goto on_error;
else if (!valid)
goto invalid;
}
/* if the RHS is empty, then it's a copy of the LHS */
if (!refspec->dst) {
refspec->dst = git__strdup(refspec->src);
GIT_ERROR_CHECK_ALLOC(refspec->dst);
}
}
refspec->string = git__strdup(input);
GIT_ERROR_CHECK_ALLOC(refspec->string);
return 0;
invalid:
git_error_set(GIT_ERROR_INVALID,
"'%s' is not a valid refspec.", input);
git_refspec__dispose(refspec);
return GIT_EINVALIDSPEC;
on_error:
git_refspec__dispose(refspec);
return -1;
}
void git_refspec__dispose(git_refspec *refspec)
{
if (refspec == NULL)
return;
git__free(refspec->src);
git__free(refspec->dst);
git__free(refspec->string);
memset(refspec, 0x0, sizeof(git_refspec));
}
int git_refspec_parse(git_refspec **out_refspec, const char *input, int is_fetch)
{
git_refspec *refspec;
GIT_ASSERT_ARG(out_refspec);
GIT_ASSERT_ARG(input);
*out_refspec = NULL;
refspec = git__malloc(sizeof(git_refspec));
GIT_ERROR_CHECK_ALLOC(refspec);
if (git_refspec__parse(refspec, input, !!is_fetch) != 0) {
git__free(refspec);
return -1;
}
*out_refspec = refspec;
return 0;
}
void git_refspec_free(git_refspec *refspec)
{
git_refspec__dispose(refspec);
git__free(refspec);
}
const char *git_refspec_src(const git_refspec *refspec)
{
return refspec == NULL ? NULL : refspec->src;
}
const char *git_refspec_dst(const git_refspec *refspec)
{
return refspec == NULL ? NULL : refspec->dst;
}
const char *git_refspec_string(const git_refspec *refspec)
{
return refspec == NULL ? NULL : refspec->string;
}
int git_refspec_force(const git_refspec *refspec)
{
GIT_ASSERT_ARG(refspec);
return refspec->force;
}
int git_refspec_src_matches(const git_refspec *refspec, const char *refname)
{
if (refspec == NULL || refspec->src == NULL)
return false;
return (wildmatch(refspec->src, refname, 0) == 0);
}
int git_refspec_dst_matches(const git_refspec *refspec, const char *refname)
{
if (refspec == NULL || refspec->dst == NULL)
return false;
return (wildmatch(refspec->dst, refname, 0) == 0);
}
static int refspec_transform(
git_buf *out, const char *from, const char *to, const char *name)
{
const char *from_star, *to_star;
size_t replacement_len, star_offset;
int error;
if ((error = git_buf_sanitize(out)) < 0)
return error;
git_buf_clear(out);
/*
* There are two parts to each side of a refspec, the bit
* before the star and the bit after it. The star can be in
* the middle of the pattern, so we need to look at each bit
* individually.
*/
from_star = strchr(from, '*');
to_star = strchr(to, '*');
GIT_ASSERT(from_star && to_star);
/* star offset, both in 'from' and in 'name' */
star_offset = from_star - from;
/* the first half is copied over */
git_buf_put(out, to, to_star - to);
/*
* Copy over the name, but exclude the trailing part in "from" starting
* after the glob
*/
replacement_len = strlen(name + star_offset) - strlen(from_star + 1);
git_buf_put(out, name + star_offset, replacement_len);
return git_buf_puts(out, to_star + 1);
}
int git_refspec_transform(git_buf *out, const git_refspec *spec, const char *name)
{
int error;
GIT_ASSERT_ARG(out);
GIT_ASSERT_ARG(spec);
GIT_ASSERT_ARG(name);
if ((error = git_buf_sanitize(out)) < 0)
return error;
if (!git_refspec_src_matches(spec, name)) {
git_error_set(GIT_ERROR_INVALID, "ref '%s' doesn't match the source", name);
return -1;
}
if (!spec->pattern)
return git_buf_puts(out, spec->dst ? spec->dst : "");
return refspec_transform(out, spec->src, spec->dst, name);
}
int git_refspec_rtransform(git_buf *out, const git_refspec *spec, const char *name)
{
int error;
GIT_ASSERT_ARG(out);
GIT_ASSERT_ARG(spec);
GIT_ASSERT_ARG(name);
if ((error = git_buf_sanitize(out)) < 0)
return error;
if (!git_refspec_dst_matches(spec, name)) {
git_error_set(GIT_ERROR_INVALID, "ref '%s' doesn't match the destination", name);
return -1;
}
if (!spec->pattern)
return git_buf_puts(out, spec->src);
return refspec_transform(out, spec->dst, spec->src, name);
}
int git_refspec__serialize(git_buf *out, const git_refspec *refspec)
{
if (refspec->force)
git_buf_putc(out, '+');
git_buf_printf(out, "%s:%s",
refspec->src != NULL ? refspec->src : "",
refspec->dst != NULL ? refspec->dst : "");
return git_buf_oom(out) == false;
}
int git_refspec_is_wildcard(const git_refspec *spec)
{
GIT_ASSERT_ARG(spec);
GIT_ASSERT_ARG(spec->src);
return (spec->src[strlen(spec->src) - 1] == '*');
}
git_direction git_refspec_direction(const git_refspec *spec)
{
GIT_ASSERT_ARG(spec);
return spec->push;
}
int git_refspec__dwim_one(git_vector *out, git_refspec *spec, git_vector *refs)
{
git_buf buf = GIT_BUF_INIT;
size_t j, pos;
git_remote_head key;
git_refspec *cur;
const char *formatters[] = {
GIT_REFS_DIR "%s",
GIT_REFS_TAGS_DIR "%s",
GIT_REFS_HEADS_DIR "%s",
NULL
};
GIT_ASSERT_ARG(out);
GIT_ASSERT_ARG(spec);
GIT_ASSERT_ARG(refs);
cur = git__calloc(1, sizeof(git_refspec));
GIT_ERROR_CHECK_ALLOC(cur);
cur->force = spec->force;
cur->push = spec->push;
cur->pattern = spec->pattern;
cur->matching = spec->matching;
cur->string = git__strdup(spec->string);
/* shorthand on the lhs */
if (git__prefixcmp(spec->src, GIT_REFS_DIR)) {
for (j = 0; formatters[j]; j++) {
git_buf_clear(&buf);
git_buf_printf(&buf, formatters[j], spec->src);
GIT_ERROR_CHECK_ALLOC_BUF(&buf);
key.name = (char *) git_buf_cstr(&buf);
if (!git_vector_search(&pos, refs, &key)) {
/* we found something to match the shorthand, set src to that */
cur->src = git_buf_detach(&buf);
}
}
}
/* No shorthands found, copy over the name */
if (cur->src == NULL && spec->src != NULL) {
cur->src = git__strdup(spec->src);
GIT_ERROR_CHECK_ALLOC(cur->src);
}
if (spec->dst && git__prefixcmp(spec->dst, GIT_REFS_DIR)) {
/* if it starts with "remotes" then we just prepend "refs/" */
if (!git__prefixcmp(spec->dst, "remotes/")) {
git_buf_puts(&buf, GIT_REFS_DIR);
} else {
git_buf_puts(&buf, GIT_REFS_HEADS_DIR);
}
git_buf_puts(&buf, spec->dst);
GIT_ERROR_CHECK_ALLOC_BUF(&buf);
cur->dst = git_buf_detach(&buf);
}
git_buf_dispose(&buf);
if (cur->dst == NULL && spec->dst != NULL) {
cur->dst = git__strdup(spec->dst);
GIT_ERROR_CHECK_ALLOC(cur->dst);
}
return git_vector_insert(out, cur);
}
|
0 |
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2
|
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2/src/status.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_status_h__
#define INCLUDE_status_h__
#include "common.h"
#include "diff.h"
#include "git2/status.h"
#include "git2/diff.h"
struct git_status_list {
git_status_options opts;
git_diff *head2idx;
git_diff *idx2wd;
git_vector paired;
};
#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/mailmap.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_mailmap_h__
#define INCLUDE_mailmap_h__
#include "git2/mailmap.h"
#include "vector.h"
/*
* A mailmap is stored as a sorted vector of 'git_mailmap_entry's. These entries
* are sorted first by 'replace_email', and then by 'replace_name'. NULL
* replace_names are ordered first.
*
* Looking up a name and email in the mailmap is done with a binary search.
*/
struct git_mailmap {
git_vector entries;
};
/* Single entry parsed from a mailmap */
typedef struct git_mailmap_entry {
char *real_name; /**< the real name (may be NULL) */
char *real_email; /**< the real email (may be NULL) */
char *replace_name; /**< the name to replace (may be NULL) */
char *replace_email; /**< the email to replace */
} git_mailmap_entry;
const git_mailmap_entry *git_mailmap_entry_lookup(
const git_mailmap *mm, const char *name, const char *email);
#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/runtime.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 "runtime.h"
static git_runtime_shutdown_fn shutdown_callback[32];
static git_atomic32 shutdown_callback_count;
static git_atomic32 init_count;
static int init_common(git_runtime_init_fn init_fns[], size_t cnt)
{
size_t i;
int ret;
/* Initialize subsystems that have global state */
for (i = 0; i < cnt; i++) {
if ((ret = init_fns[i]()) != 0)
break;
}
GIT_MEMORY_BARRIER;
return ret;
}
static void shutdown_common(void)
{
git_runtime_shutdown_fn cb;
int pos;
for (pos = git_atomic32_get(&shutdown_callback_count);
pos > 0;
pos = git_atomic32_dec(&shutdown_callback_count)) {
cb = git_atomic_swap(shutdown_callback[pos - 1], NULL);
if (cb != NULL)
cb();
}
}
int git_runtime_shutdown_register(git_runtime_shutdown_fn callback)
{
int count = git_atomic32_inc(&shutdown_callback_count);
if (count > (int)ARRAY_SIZE(shutdown_callback) || count == 0) {
git_error_set(GIT_ERROR_INVALID,
"too many shutdown callbacks registered");
git_atomic32_dec(&shutdown_callback_count);
return -1;
}
shutdown_callback[count - 1] = callback;
return 0;
}
#if defined(GIT_THREADS) && defined(GIT_WIN32)
/*
* On Win32, we use a spinlock to provide locking semantics. This is
* lighter-weight than a proper critical section.
*/
static volatile LONG init_spinlock = 0;
GIT_INLINE(int) init_lock(void)
{
while (InterlockedCompareExchange(&init_spinlock, 1, 0)) { Sleep(0); }
return 0;
}
GIT_INLINE(int) init_unlock(void)
{
InterlockedExchange(&init_spinlock, 0);
return 0;
}
#elif defined(GIT_THREADS) && defined(_POSIX_THREADS)
/*
* On POSIX, we need to use a proper mutex for locking. We might prefer
* a spinlock here, too, but there's no static initializer for a
* pthread_spinlock_t.
*/
static pthread_mutex_t init_mutex = PTHREAD_MUTEX_INITIALIZER;
GIT_INLINE(int) init_lock(void)
{
return pthread_mutex_lock(&init_mutex) == 0 ? 0 : -1;
}
GIT_INLINE(int) init_unlock(void)
{
return pthread_mutex_unlock(&init_mutex) == 0 ? 0 : -1;
}
#elif defined(GIT_THREADS)
# error unknown threading model
#else
# define init_lock() git__noop()
# define init_unlock() git__noop()
#endif
int git_runtime_init(git_runtime_init_fn init_fns[], size_t cnt)
{
int ret;
if (init_lock() < 0)
return -1;
/* Only do work on a 0 -> 1 transition of the refcount */
if ((ret = git_atomic32_inc(&init_count)) == 1) {
if (init_common(init_fns, cnt) < 0)
ret = -1;
}
if (init_unlock() < 0)
return -1;
return ret;
}
int git_runtime_init_count(void)
{
int ret;
if (init_lock() < 0)
return -1;
ret = git_atomic32_get(&init_count);
if (init_unlock() < 0)
return -1;
return ret;
}
int git_runtime_shutdown(void)
{
int ret;
/* Enter the lock */
if (init_lock() < 0)
return -1;
/* Only do work on a 1 -> 0 transition of the refcount */
if ((ret = git_atomic32_dec(&init_count)) == 0)
shutdown_common();
/* Exit the lock */
if (init_unlock() < 0)
return -1;
return ret;
}
|
0 |
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2
|
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2/src/errors.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_errors_h__
#define INCLUDE_errors_h__
#include "common.h"
/*
* Set the error message for this thread, formatting as needed.
*/
void git_error_set(int error_class, const char *fmt, ...) GIT_FORMAT_PRINTF(2, 3);
void git_error_vset(int error_class, const char *fmt, va_list ap);
/**
* Set error message for user callback if needed.
*
* If the error code in non-zero and no error message is set, this
* sets a generic error message.
*
* @return This always returns the `error_code` parameter.
*/
GIT_INLINE(int) git_error_set_after_callback_function(
int error_code, const char *action)
{
if (error_code) {
const git_error *e = git_error_last();
if (!e || !e->message)
git_error_set(e ? e->klass : GIT_ERROR_CALLBACK,
"%s callback returned %d", action, error_code);
}
return error_code;
}
#ifdef GIT_WIN32
#define git_error_set_after_callback(code) \
git_error_set_after_callback_function((code), __FUNCTION__)
#else
#define git_error_set_after_callback(code) \
git_error_set_after_callback_function((code), __func__)
#endif
/**
* Gets the system error code for this thread.
*/
int git_error_system_last(void);
/**
* Sets the system error code for this thread.
*/
void git_error_system_set(int code);
/**
* Structure to preserve libgit2 error state
*/
typedef struct {
int error_code;
unsigned int oom : 1;
git_error error_msg;
} git_error_state;
/**
* Capture current error state to restore later, returning error code.
* If `error_code` is zero, this does not clear the current error state.
* You must either restore this error state, or free it.
*/
extern int git_error_state_capture(git_error_state *state, int error_code);
/**
* Restore error state to a previous value, returning saved error code.
*/
extern int git_error_state_restore(git_error_state *state);
/** Free an error state. */
extern void git_error_state_free(git_error_state *state);
#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_tform.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_tform_h__
#define INCLUDE_diff_tform_h__
#include "common.h"
#include "diff_file.h"
extern int git_diff_find_similar__hashsig_for_file(
void **out, const git_diff_file *f, const char *path, void *p);
extern int git_diff_find_similar__hashsig_for_buf(
void **out, const git_diff_file *f, const char *buf, size_t len, void *p);
extern void git_diff_find_similar__hashsig_free(void *sig, void *payload);
extern int git_diff_find_similar__calc_similarity(
int *score, void *siga, void *sigb, 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/attrcache.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_attrcache_h__
#define INCLUDE_attrcache_h__
#include "common.h"
#include "attr_file.h"
#include "strmap.h"
#define GIT_ATTR_CONFIG "core.attributesfile"
#define GIT_IGNORE_CONFIG "core.excludesfile"
typedef struct {
char *cfg_attr_file; /* cached value of core.attributesfile */
char *cfg_excl_file; /* cached value of core.excludesfile */
git_strmap *files; /* hash path to git_attr_cache_entry records */
git_strmap *macros; /* hash name to vector<git_attr_assignment> */
git_mutex lock;
git_pool pool;
} git_attr_cache;
extern int git_attr_cache__init(git_repository *repo);
/* get file - loading and reload as needed */
extern int git_attr_cache__get(
git_attr_file **file,
git_repository *repo,
git_attr_session *attr_session,
git_attr_file_source *source,
git_attr_file_parser parser,
bool allow_macros);
extern bool git_attr_cache__is_cached(
git_repository *repo,
git_attr_file_source_t source_type,
const char *filename);
extern int git_attr_cache__alloc_file_entry(
git_attr_file_entry **out,
git_repository *repo,
const char *base,
const char *path,
git_pool *pool);
extern int git_attr_cache__insert_macro(
git_repository *repo, git_attr_rule *macro);
extern git_attr_rule *git_attr_cache__lookup_macro(
git_repository *repo, const char *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/merge_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 "common.h"
#include "repository.h"
#include "posix.h"
#include "futils.h"
#include "index.h"
#include "diff_xdiff.h"
#include "merge.h"
#include "git2/repository.h"
#include "git2/object.h"
#include "git2/index.h"
#include "git2/merge.h"
#include "xdiff/xdiff.h"
/* only examine the first 8000 bytes for binaryness.
* https://github.com/git/git/blob/77bd3ea9f54f1584147b594abc04c26ca516d987/xdiff-interface.c#L197
*/
#define GIT_MERGE_FILE_BINARY_SIZE 8000
#define GIT_MERGE_FILE_SIDE_EXISTS(X) ((X)->mode != 0)
static int merge_file_input_from_index(
git_merge_file_input *input_out,
git_odb_object **odb_object_out,
git_odb *odb,
const git_index_entry *entry)
{
int error = 0;
GIT_ASSERT_ARG(input_out);
GIT_ASSERT_ARG(odb_object_out);
GIT_ASSERT_ARG(odb);
GIT_ASSERT_ARG(entry);
if ((error = git_odb_read(odb_object_out, odb, &entry->id)) < 0)
goto done;
input_out->path = entry->path;
input_out->mode = entry->mode;
input_out->ptr = (char *)git_odb_object_data(*odb_object_out);
input_out->size = git_odb_object_size(*odb_object_out);
done:
return error;
}
static void merge_file_normalize_opts(
git_merge_file_options *out,
const git_merge_file_options *given_opts)
{
if (given_opts)
memcpy(out, given_opts, sizeof(git_merge_file_options));
else {
git_merge_file_options default_opts = GIT_MERGE_FILE_OPTIONS_INIT;
memcpy(out, &default_opts, sizeof(git_merge_file_options));
}
}
static int merge_file__xdiff(
git_merge_file_result *out,
const git_merge_file_input *ancestor,
const git_merge_file_input *ours,
const git_merge_file_input *theirs,
const git_merge_file_options *given_opts)
{
xmparam_t xmparam;
mmfile_t ancestor_mmfile = {0}, our_mmfile = {0}, their_mmfile = {0};
mmbuffer_t mmbuffer;
git_merge_file_options options = GIT_MERGE_FILE_OPTIONS_INIT;
const char *path;
int xdl_result;
int error = 0;
memset(out, 0x0, sizeof(git_merge_file_result));
merge_file_normalize_opts(&options, given_opts);
memset(&xmparam, 0x0, sizeof(xmparam_t));
if (ancestor) {
xmparam.ancestor = (options.ancestor_label) ?
options.ancestor_label : ancestor->path;
ancestor_mmfile.ptr = (char *)ancestor->ptr;
ancestor_mmfile.size = ancestor->size;
}
xmparam.file1 = (options.our_label) ?
options.our_label : ours->path;
our_mmfile.ptr = (char *)ours->ptr;
our_mmfile.size = ours->size;
xmparam.file2 = (options.their_label) ?
options.their_label : theirs->path;
their_mmfile.ptr = (char *)theirs->ptr;
their_mmfile.size = theirs->size;
if (options.favor == GIT_MERGE_FILE_FAVOR_OURS)
xmparam.favor = XDL_MERGE_FAVOR_OURS;
else if (options.favor == GIT_MERGE_FILE_FAVOR_THEIRS)
xmparam.favor = XDL_MERGE_FAVOR_THEIRS;
else if (options.favor == GIT_MERGE_FILE_FAVOR_UNION)
xmparam.favor = XDL_MERGE_FAVOR_UNION;
xmparam.level = (options.flags & GIT_MERGE_FILE_SIMPLIFY_ALNUM) ?
XDL_MERGE_ZEALOUS_ALNUM : XDL_MERGE_ZEALOUS;
if (options.flags & GIT_MERGE_FILE_STYLE_DIFF3)
xmparam.style = XDL_MERGE_DIFF3;
if (options.flags & GIT_MERGE_FILE_IGNORE_WHITESPACE)
xmparam.xpp.flags |= XDF_IGNORE_WHITESPACE;
if (options.flags & GIT_MERGE_FILE_IGNORE_WHITESPACE_CHANGE)
xmparam.xpp.flags |= XDF_IGNORE_WHITESPACE_CHANGE;
if (options.flags & GIT_MERGE_FILE_IGNORE_WHITESPACE_EOL)
xmparam.xpp.flags |= XDF_IGNORE_WHITESPACE_AT_EOL;
if (options.flags & GIT_MERGE_FILE_DIFF_PATIENCE)
xmparam.xpp.flags |= XDF_PATIENCE_DIFF;
if (options.flags & GIT_MERGE_FILE_DIFF_MINIMAL)
xmparam.xpp.flags |= XDF_NEED_MINIMAL;
xmparam.marker_size = options.marker_size;
if ((xdl_result = xdl_merge(&ancestor_mmfile, &our_mmfile,
&their_mmfile, &xmparam, &mmbuffer)) < 0) {
git_error_set(GIT_ERROR_MERGE, "failed to merge files");
error = -1;
goto done;
}
path = git_merge_file__best_path(
ancestor ? ancestor->path : NULL,
ours->path,
theirs->path);
if (path != NULL && (out->path = git__strdup(path)) == NULL) {
error = -1;
goto done;
}
out->automergeable = (xdl_result == 0);
out->ptr = (const char *)mmbuffer.ptr;
out->len = mmbuffer.size;
out->mode = git_merge_file__best_mode(
ancestor ? ancestor->mode : 0,
ours->mode,
theirs->mode);
done:
if (error < 0)
git_merge_file_result_free(out);
return error;
}
static bool merge_file__is_binary(const git_merge_file_input *file)
{
size_t len = file ? file->size : 0;
if (len > GIT_XDIFF_MAX_SIZE)
return true;
if (len > GIT_MERGE_FILE_BINARY_SIZE)
len = GIT_MERGE_FILE_BINARY_SIZE;
return len ? (memchr(file->ptr, 0, len) != NULL) : false;
}
static int merge_file__binary(
git_merge_file_result *out,
const git_merge_file_input *ours,
const git_merge_file_input *theirs,
const git_merge_file_options *given_opts)
{
const git_merge_file_input *favored = NULL;
memset(out, 0x0, sizeof(git_merge_file_result));
if (given_opts && given_opts->favor == GIT_MERGE_FILE_FAVOR_OURS)
favored = ours;
else if (given_opts && given_opts->favor == GIT_MERGE_FILE_FAVOR_THEIRS)
favored = theirs;
else
goto done;
if ((out->path = git__strdup(favored->path)) == NULL ||
(out->ptr = git__malloc(favored->size)) == NULL)
goto done;
memcpy((char *)out->ptr, favored->ptr, favored->size);
out->len = favored->size;
out->mode = favored->mode;
out->automergeable = 1;
done:
return 0;
}
static int merge_file__from_inputs(
git_merge_file_result *out,
const git_merge_file_input *ancestor,
const git_merge_file_input *ours,
const git_merge_file_input *theirs,
const git_merge_file_options *given_opts)
{
if (merge_file__is_binary(ancestor) ||
merge_file__is_binary(ours) ||
merge_file__is_binary(theirs))
return merge_file__binary(out, ours, theirs, given_opts);
return merge_file__xdiff(out, ancestor, ours, theirs, given_opts);
}
static git_merge_file_input *git_merge_file__normalize_inputs(
git_merge_file_input *out,
const git_merge_file_input *given)
{
memcpy(out, given, sizeof(git_merge_file_input));
if (!out->path)
out->path = "file.txt";
if (!out->mode)
out->mode = 0100644;
return out;
}
int git_merge_file(
git_merge_file_result *out,
const git_merge_file_input *ancestor,
const git_merge_file_input *ours,
const git_merge_file_input *theirs,
const git_merge_file_options *options)
{
git_merge_file_input inputs[3] = { {0} };
GIT_ASSERT_ARG(out);
GIT_ASSERT_ARG(ours);
GIT_ASSERT_ARG(theirs);
memset(out, 0x0, sizeof(git_merge_file_result));
if (ancestor)
ancestor = git_merge_file__normalize_inputs(&inputs[0], ancestor);
ours = git_merge_file__normalize_inputs(&inputs[1], ours);
theirs = git_merge_file__normalize_inputs(&inputs[2], theirs);
return merge_file__from_inputs(out, ancestor, ours, theirs, options);
}
int git_merge_file_from_index(
git_merge_file_result *out,
git_repository *repo,
const git_index_entry *ancestor,
const git_index_entry *ours,
const git_index_entry *theirs,
const git_merge_file_options *options)
{
git_merge_file_input *ancestor_ptr = NULL,
ancestor_input = {0}, our_input = {0}, their_input = {0};
git_odb *odb = NULL;
git_odb_object *odb_object[3] = { 0 };
int error = 0;
GIT_ASSERT_ARG(out);
GIT_ASSERT_ARG(repo);
GIT_ASSERT_ARG(ours);
GIT_ASSERT_ARG(theirs);
memset(out, 0x0, sizeof(git_merge_file_result));
if ((error = git_repository_odb(&odb, repo)) < 0)
goto done;
if (ancestor) {
if ((error = merge_file_input_from_index(
&ancestor_input, &odb_object[0], odb, ancestor)) < 0)
goto done;
ancestor_ptr = &ancestor_input;
}
if ((error = merge_file_input_from_index(&our_input, &odb_object[1], odb, ours)) < 0 ||
(error = merge_file_input_from_index(&their_input, &odb_object[2], odb, theirs)) < 0)
goto done;
error = merge_file__from_inputs(out,
ancestor_ptr, &our_input, &their_input, options);
done:
git_odb_object_free(odb_object[0]);
git_odb_object_free(odb_object[1]);
git_odb_object_free(odb_object[2]);
git_odb_free(odb);
return error;
}
void git_merge_file_result_free(git_merge_file_result *result)
{
if (result == NULL)
return;
git__free((char *)result->path);
git__free((char *)result->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/ident.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/filter.h"
#include "filter.h"
#include "buffer.h"
static int ident_find_id(
const char **id_start, const char **id_end, const char *start, size_t len)
{
const char *end = start + len, *found = NULL;
while (len > 3 && (found = memchr(start, '$', len)) != NULL) {
size_t remaining = (size_t)(end - found) - 1;
if (remaining < 3)
return GIT_ENOTFOUND;
start = found + 1;
len = remaining;
if (start[0] == 'I' && start[1] == 'd')
break;
}
if (len < 3 || !found)
return GIT_ENOTFOUND;
*id_start = found;
if ((found = memchr(start + 2, '$', len - 2)) == NULL)
return GIT_ENOTFOUND;
*id_end = found + 1;
return 0;
}
static int ident_insert_id(
git_buf *to, const git_buf *from, const git_filter_source *src)
{
char oid[GIT_OID_HEXSZ+1];
const char *id_start, *id_end, *from_end = from->ptr + from->size;
size_t need_size;
/* replace $Id$ with blob id */
if (!git_filter_source_id(src))
return GIT_PASSTHROUGH;
git_oid_tostr(oid, sizeof(oid), git_filter_source_id(src));
if (ident_find_id(&id_start, &id_end, from->ptr, from->size) < 0)
return GIT_PASSTHROUGH;
need_size = (size_t)(id_start - from->ptr) +
5 /* "$Id: " */ + GIT_OID_HEXSZ + 2 /* " $" */ +
(size_t)(from_end - id_end);
if (git_buf_grow(to, need_size) < 0)
return -1;
git_buf_set(to, from->ptr, (size_t)(id_start - from->ptr));
git_buf_put(to, "$Id: ", 5);
git_buf_put(to, oid, GIT_OID_HEXSZ);
git_buf_put(to, " $", 2);
git_buf_put(to, id_end, (size_t)(from_end - id_end));
return git_buf_oom(to) ? -1 : 0;
}
static int ident_remove_id(
git_buf *to, const git_buf *from)
{
const char *id_start, *id_end, *from_end = from->ptr + from->size;
size_t need_size;
if (ident_find_id(&id_start, &id_end, from->ptr, from->size) < 0)
return GIT_PASSTHROUGH;
need_size = (size_t)(id_start - from->ptr) +
4 /* "$Id$" */ + (size_t)(from_end - id_end);
if (git_buf_grow(to, need_size) < 0)
return -1;
git_buf_set(to, from->ptr, (size_t)(id_start - from->ptr));
git_buf_put(to, "$Id$", 4);
git_buf_put(to, id_end, (size_t)(from_end - id_end));
return git_buf_oom(to) ? -1 : 0;
}
static int ident_apply(
git_filter *self,
void **payload,
git_buf *to,
const git_buf *from,
const git_filter_source *src)
{
GIT_UNUSED(self); GIT_UNUSED(payload);
/* Don't filter binary files */
if (git_buf_is_binary(from))
return GIT_PASSTHROUGH;
if (git_filter_source_mode(src) == GIT_FILTER_SMUDGE)
return ident_insert_id(to, from, src);
else
return ident_remove_id(to, from);
}
static int ident_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, ident_apply, NULL, payload, src, next);
}
git_filter *git_ident_filter_new(void)
{
git_filter *f = git__calloc(1, sizeof(git_filter));
if (f == NULL)
return NULL;
f->version = GIT_FILTER_VERSION;
f->attributes = "+ident"; /* apply to files with ident attribute set */
f->shutdown = git_filter_free;
f->stream = ident_stream;
return 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/config_parse.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_parse.h"
#include <ctype.h>
const char *git_config_escapes = "ntb\"\\";
const char *git_config_escaped = "\n\t\b\"\\";
static void set_parse_error(git_config_parser *reader, int col, const char *error_str)
{
if (col)
git_error_set(GIT_ERROR_CONFIG,
"failed to parse config file: %s (in %s:%"PRIuZ", column %d)",
error_str, reader->path, reader->ctx.line_num, col);
else
git_error_set(GIT_ERROR_CONFIG,
"failed to parse config file: %s (in %s:%"PRIuZ")",
error_str, reader->path, reader->ctx.line_num);
}
GIT_INLINE(int) config_keychar(int c)
{
return isalnum(c) || c == '-';
}
static int strip_comments(char *line, int in_quotes)
{
int quote_count = in_quotes, backslash_count = 0;
char *ptr;
for (ptr = line; *ptr; ++ptr) {
if (ptr[0] == '"' && ptr > line && ptr[-1] != '\\')
quote_count++;
if ((ptr[0] == ';' || ptr[0] == '#') &&
(quote_count % 2) == 0 &&
(backslash_count % 2) == 0) {
ptr[0] = '\0';
break;
}
if (ptr[0] == '\\')
backslash_count++;
else
backslash_count = 0;
}
/* skip any space at the end */
while (ptr > line && git__isspace(ptr[-1])) {
ptr--;
}
ptr[0] = '\0';
return quote_count;
}
static int parse_subsection_header(git_config_parser *reader, const char *line, size_t pos, const char *base_name, char **section_name)
{
int c, rpos;
const char *first_quote, *last_quote;
const char *line_start = line;
git_buf buf = GIT_BUF_INIT;
size_t quoted_len, alloc_len, base_name_len = strlen(base_name);
/* Skip any additional whitespace before our section name */
while (git__isspace(line[pos]))
pos++;
/* We should be at the first quotation mark. */
if (line[pos] != '"') {
set_parse_error(reader, 0, "missing quotation marks in section header");
goto end_error;
}
first_quote = &line[pos];
last_quote = strrchr(line, '"');
quoted_len = last_quote - first_quote;
if ((last_quote - line) > INT_MAX) {
set_parse_error(reader, 0, "invalid section header, line too long");
goto end_error;
}
if (quoted_len == 0) {
set_parse_error(reader, 0, "missing closing quotation mark in section header");
goto end_error;
}
GIT_ERROR_CHECK_ALLOC_ADD(&alloc_len, base_name_len, quoted_len);
GIT_ERROR_CHECK_ALLOC_ADD(&alloc_len, alloc_len, 2);
if (git_buf_grow(&buf, alloc_len) < 0 ||
git_buf_printf(&buf, "%s.", base_name) < 0)
goto end_error;
rpos = 0;
line = first_quote;
c = line[++rpos];
/*
* At the end of each iteration, whatever is stored in c will be
* added to the string. In case of error, jump to out
*/
do {
switch (c) {
case 0:
set_parse_error(reader, 0, "unexpected end-of-line in section header");
goto end_error;
case '"':
goto end_parse;
case '\\':
c = line[++rpos];
if (c == 0) {
set_parse_error(reader, rpos, "unexpected end-of-line in section header");
goto end_error;
}
default:
break;
}
git_buf_putc(&buf, (char)c);
c = line[++rpos];
} while (line + rpos < last_quote);
end_parse:
if (git_buf_oom(&buf))
goto end_error;
if (line[rpos] != '"' || line[rpos + 1] != ']') {
set_parse_error(reader, rpos, "unexpected text after closing quotes");
git_buf_dispose(&buf);
return -1;
}
*section_name = git_buf_detach(&buf);
return (int)(&line[rpos + 2] - line_start); /* rpos is at the closing quote */
end_error:
git_buf_dispose(&buf);
return -1;
}
static int parse_section_header(git_config_parser *reader, char **section_out)
{
char *name, *name_end;
int name_length, c, pos;
int result;
char *line;
size_t line_len;
git_parse_advance_ws(&reader->ctx);
line = git__strndup(reader->ctx.line, reader->ctx.line_len);
if (line == NULL)
return -1;
/* find the end of the variable's name */
name_end = strrchr(line, ']');
if (name_end == NULL) {
git__free(line);
set_parse_error(reader, 0, "missing ']' in section header");
return -1;
}
GIT_ERROR_CHECK_ALLOC_ADD(&line_len, (size_t)(name_end - line), 1);
name = git__malloc(line_len);
GIT_ERROR_CHECK_ALLOC(name);
name_length = 0;
pos = 0;
/* Make sure we were given a section header */
c = line[pos++];
GIT_ASSERT(c == '[');
c = line[pos++];
do {
if (git__isspace(c)){
name[name_length] = '\0';
result = parse_subsection_header(reader, line, pos, name, section_out);
git__free(line);
git__free(name);
return result;
}
if (!config_keychar(c) && c != '.') {
set_parse_error(reader, pos, "unexpected character in header");
goto fail_parse;
}
name[name_length++] = (char)git__tolower(c);
} while ((c = line[pos++]) != ']');
if (line[pos - 1] != ']') {
set_parse_error(reader, pos, "unexpected end of file");
goto fail_parse;
}
git__free(line);
name[name_length] = 0;
*section_out = name;
return pos;
fail_parse:
git__free(line);
git__free(name);
return -1;
}
static int skip_bom(git_parse_ctx *parser)
{
git_buf buf = GIT_BUF_INIT_CONST(parser->content, parser->content_len);
git_buf_bom_t bom;
int bom_offset = git_buf_detect_bom(&bom, &buf);
if (bom == GIT_BUF_BOM_UTF8)
git_parse_advance_chars(parser, bom_offset);
/* TODO: reference implementation is pretty stupid with BoM */
return 0;
}
/*
(* basic types *)
digit = "0".."9"
integer = digit { digit }
alphabet = "a".."z" + "A" .. "Z"
section_char = alphabet | "." | "-"
extension_char = (* any character except newline *)
any_char = (* any character *)
variable_char = "alphabet" | "-"
(* actual grammar *)
config = { section }
section = header { definition }
header = "[" section [subsection | subsection_ext] "]"
subsection = "." section
subsection_ext = "\"" extension "\""
section = section_char { section_char }
extension = extension_char { extension_char }
definition = variable_name ["=" variable_value] "\n"
variable_name = variable_char { variable_char }
variable_value = string | boolean | integer
string = quoted_string | plain_string
quoted_string = "\"" plain_string "\""
plain_string = { any_char }
boolean = boolean_true | boolean_false
boolean_true = "yes" | "1" | "true" | "on"
boolean_false = "no" | "0" | "false" | "off"
*/
/* '\"' -> '"' etc */
static int unescape_line(
char **out, bool *is_multi, const char *ptr, int quote_count)
{
char *str, *fixed, *esc;
size_t ptr_len = strlen(ptr), alloc_len;
*is_multi = false;
if (GIT_ADD_SIZET_OVERFLOW(&alloc_len, ptr_len, 1) ||
(str = git__malloc(alloc_len)) == NULL) {
return -1;
}
fixed = str;
while (*ptr != '\0') {
if (*ptr == '"') {
quote_count++;
} else if (*ptr != '\\') {
*fixed++ = *ptr;
} else {
/* backslash, check the next char */
ptr++;
/* if we're at the end, it's a multiline, so keep the backslash */
if (*ptr == '\0') {
*is_multi = true;
goto done;
}
if ((esc = strchr(git_config_escapes, *ptr)) != NULL) {
*fixed++ = git_config_escaped[esc - git_config_escapes];
} else {
git__free(str);
git_error_set(GIT_ERROR_CONFIG, "invalid escape at %s", ptr);
return -1;
}
}
ptr++;
}
done:
*fixed = '\0';
*out = str;
return 0;
}
static int parse_multiline_variable(git_config_parser *reader, git_buf *value, int in_quotes)
{
int quote_count;
bool multiline = true;
while (multiline) {
char *line = NULL, *proc_line = NULL;
int error;
/* Check that the next line exists */
git_parse_advance_line(&reader->ctx);
line = git__strndup(reader->ctx.line, reader->ctx.line_len);
GIT_ERROR_CHECK_ALLOC(line);
/*
* We've reached the end of the file, there is no continuation.
* (this is not an error).
*/
if (line[0] == '\0') {
error = 0;
goto out;
}
/* If it was just a comment, pretend it didn't exist */
quote_count = strip_comments(line, in_quotes);
if (line[0] == '\0')
goto next;
if ((error = unescape_line(&proc_line, &multiline,
line, in_quotes)) < 0)
goto out;
/* Add this line to the multiline var */
if ((error = git_buf_puts(value, proc_line)) < 0)
goto out;
next:
git__free(line);
git__free(proc_line);
in_quotes = quote_count;
continue;
out:
git__free(line);
git__free(proc_line);
return error;
}
return 0;
}
GIT_INLINE(bool) is_namechar(char c)
{
return isalnum(c) || c == '-';
}
static int parse_name(
char **name, const char **value, git_config_parser *reader, const char *line)
{
const char *name_end = line, *value_start;
*name = NULL;
*value = NULL;
while (*name_end && is_namechar(*name_end))
name_end++;
if (line == name_end) {
set_parse_error(reader, 0, "invalid configuration key");
return -1;
}
value_start = name_end;
while (*value_start && git__isspace(*value_start))
value_start++;
if (*value_start == '=') {
*value = value_start + 1;
} else if (*value_start) {
set_parse_error(reader, 0, "invalid configuration key");
return -1;
}
if ((*name = git__strndup(line, name_end - line)) == NULL)
return -1;
return 0;
}
static int parse_variable(git_config_parser *reader, char **var_name, char **var_value)
{
const char *value_start = NULL;
char *line = NULL, *name = NULL, *value = NULL;
int quote_count, error;
bool multiline;
*var_name = NULL;
*var_value = NULL;
git_parse_advance_ws(&reader->ctx);
line = git__strndup(reader->ctx.line, reader->ctx.line_len);
GIT_ERROR_CHECK_ALLOC(line);
quote_count = strip_comments(line, 0);
if ((error = parse_name(&name, &value_start, reader, line)) < 0)
goto out;
/*
* Now, let's try to parse the value
*/
if (value_start != NULL) {
while (git__isspace(value_start[0]))
value_start++;
if ((error = unescape_line(&value, &multiline, value_start, 0)) < 0)
goto out;
if (multiline) {
git_buf multi_value = GIT_BUF_INIT;
git_buf_attach(&multi_value, value, 0);
value = NULL;
if (parse_multiline_variable(reader, &multi_value, quote_count % 2) < 0 ||
git_buf_oom(&multi_value)) {
error = -1;
git_buf_dispose(&multi_value);
goto out;
}
value = git_buf_detach(&multi_value);
}
}
*var_name = name;
*var_value = value;
name = NULL;
value = NULL;
out:
git__free(name);
git__free(value);
git__free(line);
return error;
}
int git_config_parser_init(git_config_parser *out, const char *path, const char *data, size_t datalen)
{
out->path = path;
return git_parse_ctx_init(&out->ctx, data, datalen);
}
void git_config_parser_dispose(git_config_parser *parser)
{
git_parse_ctx_clear(&parser->ctx);
}
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)
{
git_parse_ctx *ctx;
char *current_section = NULL, *var_name = NULL, *var_value = NULL;
int result = 0;
ctx = &parser->ctx;
skip_bom(ctx);
for (; ctx->remain_len > 0; git_parse_advance_line(ctx)) {
const char *line_start;
size_t line_len;
char c;
restart:
line_start = ctx->line;
line_len = ctx->line_len;
/*
* Get either first non-whitespace character or, if that does
* not exist, the first whitespace character. This is required
* to preserve whitespaces when writing back the file.
*/
if (git_parse_peek(&c, ctx, GIT_PARSE_PEEK_SKIP_WHITESPACE) < 0 &&
git_parse_peek(&c, ctx, 0) < 0)
continue;
switch (c) {
case '[': /* section header, new section begins */
git__free(current_section);
current_section = NULL;
result = parse_section_header(parser, ¤t_section);
if (result < 0)
break;
git_parse_advance_chars(ctx, result);
if (on_section)
result = on_section(parser, current_section, line_start, line_len, payload);
/*
* After we've parsed the section header we may not be
* done with the line. If there's still data in there,
* run the next loop with the rest of the current line
* instead of moving forward.
*/
if (!git_parse_peek(&c, ctx, GIT_PARSE_PEEK_SKIP_WHITESPACE))
goto restart;
break;
case '\n': /* comment or whitespace-only */
case '\r':
case ' ':
case '\t':
case ';':
case '#':
if (on_comment) {
result = on_comment(parser, line_start, line_len, payload);
}
break;
default: /* assume variable declaration */
if ((result = parse_variable(parser, &var_name, &var_value)) == 0 && on_variable) {
result = on_variable(parser, current_section, var_name, var_value, line_start, line_len, payload);
git__free(var_name);
git__free(var_value);
}
break;
}
if (result < 0)
goto out;
}
if (on_eof)
result = on_eof(parser, current_section, payload);
out:
git__free(current_section);
return result;
}
|
0 |
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2
|
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2/src/trace.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_trace_h__
#define INCLUDE_trace_h__
#include "common.h"
#include <git2/trace.h>
#include "buffer.h"
#ifdef GIT_TRACE
struct git_trace_data {
git_trace_level_t level;
git_trace_cb callback;
};
extern struct git_trace_data git_trace__data;
GIT_INLINE(void) git_trace__write_fmt(
git_trace_level_t level,
const char *fmt,
va_list ap)
{
git_trace_cb callback = git_trace__data.callback;
git_buf message = GIT_BUF_INIT;
git_buf_vprintf(&message, fmt, ap);
callback(level, git_buf_cstr(&message));
git_buf_dispose(&message);
}
#define git_trace_level() (git_trace__data.level)
GIT_INLINE(void) git_trace(git_trace_level_t level, const char *fmt, ...)
{
if (git_trace__data.level >= level &&
git_trace__data.callback != NULL) {
va_list ap;
va_start(ap, fmt);
git_trace__write_fmt(level, fmt, ap);
va_end(ap);
}
}
#else
GIT_INLINE(void) git_trace__null(
git_trace_level_t level,
const char *fmt, ...)
{
GIT_UNUSED(level);
GIT_UNUSED(fmt);
}
#define git_trace_level() ((git_trace_level_t)0)
#define git_trace git_trace__null
#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/utf8.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_utf8_h__
#define INCLUDE_utf8_h__
#include "common.h"
/*
* Iterate through an UTF-8 string, yielding one codepoint at a time.
*
* @param out pointer where to store the current codepoint
* @param str current position in the string
* @param str_len size left in the string
* @return length in bytes of the read codepoint; -1 if the codepoint was invalid
*/
extern int git_utf8_iterate(uint32_t *out, const char *str, size_t str_len);
/**
* Returns the number of characters in the given string.
*
* This function will count invalid codepoints; if any given byte is
* not part of a valid UTF-8 codepoint, then it will be counted toward
* the length in characters.
*
* In other words:
* 0x24 (U+0024 "$") has length 1
* 0xc2 0xa2 (U+00A2 "¢") has length 1
* 0x24 0xc2 0xa2 (U+0024 U+00A2 "$¢") has length 2
* 0xf0 0x90 0x8d 0x88 (U+10348 "𐍈") has length 1
* 0x24 0xc0 0xc1 0x34 (U+0024 <invalid> <invalid> "4) has length 4
*
* @param str string to scan
* @param str_len size of the string
* @return length in characters of the string
*/
extern size_t git_utf8_char_length(const char *str, size_t str_len);
/**
* Iterate through an UTF-8 string and stops after finding any invalid UTF-8
* codepoints.
*
* @param str string to scan
* @param str_len size of the string
* @return length in bytes of the string that contains valid data
*/
extern size_t git_utf8_valid_buf_length(const char *str, size_t str_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/odb_loose.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 <zlib.h>
#include "git2/object.h"
#include "git2/sys/odb_backend.h"
#include "futils.h"
#include "hash.h"
#include "odb.h"
#include "delta.h"
#include "filebuf.h"
#include "object.h"
#include "zstream.h"
#include "git2/odb_backend.h"
#include "git2/types.h"
/* maximum possible header length */
#define MAX_HEADER_LEN 64
typedef struct { /* object header data */
git_object_t type; /* object type */
size_t size; /* object size */
} obj_hdr;
typedef struct {
git_odb_stream stream;
git_filebuf fbuf;
} loose_writestream;
typedef struct {
git_odb_stream stream;
git_map map;
char start[MAX_HEADER_LEN];
size_t start_len;
size_t start_read;
git_zstream zstream;
} loose_readstream;
typedef struct loose_backend {
git_odb_backend parent;
int object_zlib_level; /** loose object zlib compression level. */
int fsync_object_files; /** loose object file fsync flag. */
mode_t object_file_mode;
mode_t object_dir_mode;
size_t objects_dirlen;
char objects_dir[GIT_FLEX_ARRAY];
} loose_backend;
/* State structure for exploring directories,
* in order to locate objects matching a short oid.
*/
typedef struct {
size_t dir_len;
unsigned char short_oid[GIT_OID_HEXSZ]; /* hex formatted oid to match */
size_t short_oid_len;
int found; /* number of matching
* objects already found */
unsigned char res_oid[GIT_OID_HEXSZ]; /* hex formatted oid of
* the object found */
} loose_locate_object_state;
/***********************************************************
*
* MISCELLANEOUS HELPER FUNCTIONS
*
***********************************************************/
static int object_file_name(
git_buf *name, const loose_backend *be, const git_oid *id)
{
size_t alloclen;
/* expand length for object root + 40 hex sha1 chars + 2 * '/' + '\0' */
GIT_ERROR_CHECK_ALLOC_ADD(&alloclen, be->objects_dirlen, GIT_OID_HEXSZ);
GIT_ERROR_CHECK_ALLOC_ADD(&alloclen, alloclen, 3);
if (git_buf_grow(name, alloclen) < 0)
return -1;
git_buf_set(name, be->objects_dir, be->objects_dirlen);
git_path_to_dir(name);
/* loose object filename: aa/aaa... (41 bytes) */
git_oid_pathfmt(name->ptr + name->size, id);
name->size += GIT_OID_HEXSZ + 1;
name->ptr[name->size] = '\0';
return 0;
}
static int object_mkdir(const git_buf *name, const loose_backend *be)
{
return git_futils_mkdir_relative(
name->ptr + be->objects_dirlen, be->objects_dir, be->object_dir_mode,
GIT_MKDIR_PATH | GIT_MKDIR_SKIP_LAST | GIT_MKDIR_VERIFY_DIR, NULL);
}
static int parse_header_packlike(
obj_hdr *out, size_t *out_len, const unsigned char *data, size_t len)
{
unsigned long c;
size_t shift, size, used = 0;
if (len == 0)
goto on_error;
c = data[used++];
out->type = (c >> 4) & 7;
size = c & 15;
shift = 4;
while (c & 0x80) {
if (len <= used)
goto on_error;
if (sizeof(size_t) * 8 <= shift)
goto on_error;
c = data[used++];
size += (c & 0x7f) << shift;
shift += 7;
}
out->size = size;
if (out_len)
*out_len = used;
return 0;
on_error:
git_error_set(GIT_ERROR_OBJECT, "failed to parse loose object: invalid header");
return -1;
}
static int parse_header(
obj_hdr *out,
size_t *out_len,
const unsigned char *_data,
size_t data_len)
{
const char *data = (char *)_data;
size_t i, typename_len, size_idx, size_len;
int64_t size;
*out_len = 0;
/* find the object type name */
for (i = 0, typename_len = 0; i < data_len; i++, typename_len++) {
if (data[i] == ' ')
break;
}
if (typename_len == data_len)
goto on_error;
out->type = git_object_stringn2type(data, typename_len);
size_idx = typename_len + 1;
for (i = size_idx, size_len = 0; i < data_len; i++, size_len++) {
if (data[i] == '\0')
break;
}
if (i == data_len)
goto on_error;
if (git__strntol64(&size, &data[size_idx], size_len, NULL, 10) < 0 ||
size < 0)
goto on_error;
if ((uint64_t)size > SIZE_MAX) {
git_error_set(GIT_ERROR_OBJECT, "object is larger than available memory");
return -1;
}
out->size = (size_t)size;
if (GIT_ADD_SIZET_OVERFLOW(out_len, i, 1))
goto on_error;
return 0;
on_error:
git_error_set(GIT_ERROR_OBJECT, "failed to parse loose object: invalid header");
return -1;
}
static int is_zlib_compressed_data(unsigned char *data, size_t data_len)
{
unsigned int w;
if (data_len < 2)
return 0;
w = ((unsigned int)(data[0]) << 8) + data[1];
return (data[0] & 0x8F) == 0x08 && !(w % 31);
}
/***********************************************************
*
* ODB OBJECT READING & WRITING
*
* Backend for the public API; read headers and full objects
* from the ODB. Write raw data to the ODB.
*
***********************************************************/
/*
* At one point, there was a loose object format that was intended to
* mimic the format used in pack-files. This was to allow easy copying
* of loose object data into packs. This format is no longer used, but
* we must still read it.
*/
static int read_loose_packlike(git_rawobj *out, git_buf *obj)
{
git_buf body = GIT_BUF_INIT;
const unsigned char *obj_data;
obj_hdr hdr;
size_t obj_len, head_len, alloc_size;
int error;
obj_data = (unsigned char *)obj->ptr;
obj_len = obj->size;
/*
* read the object header, which is an (uncompressed)
* binary encoding of the object type and size.
*/
if ((error = parse_header_packlike(&hdr, &head_len, obj_data, obj_len)) < 0)
goto done;
if (!git_object_typeisloose(hdr.type) || head_len > obj_len) {
git_error_set(GIT_ERROR_ODB, "failed to inflate loose object");
error = -1;
goto done;
}
obj_data += head_len;
obj_len -= head_len;
/*
* allocate a buffer and inflate the data into it
*/
if (GIT_ADD_SIZET_OVERFLOW(&alloc_size, hdr.size, 1) ||
git_buf_init(&body, alloc_size) < 0) {
error = -1;
goto done;
}
if ((error = git_zstream_inflatebuf(&body, obj_data, obj_len)) < 0)
goto done;
out->len = hdr.size;
out->type = hdr.type;
out->data = git_buf_detach(&body);
done:
git_buf_dispose(&body);
return error;
}
static int read_loose_standard(git_rawobj *out, git_buf *obj)
{
git_zstream zstream = GIT_ZSTREAM_INIT;
unsigned char head[MAX_HEADER_LEN], *body = NULL;
size_t decompressed, head_len, body_len, alloc_size;
obj_hdr hdr;
int error;
if ((error = git_zstream_init(&zstream, GIT_ZSTREAM_INFLATE)) < 0 ||
(error = git_zstream_set_input(&zstream, git_buf_cstr(obj), git_buf_len(obj))) < 0)
goto done;
decompressed = sizeof(head);
/*
* inflate the initial part of the compressed buffer in order to
* parse the header; read the largest header possible, then push the
* remainder into the body buffer.
*/
if ((error = git_zstream_get_output(head, &decompressed, &zstream)) < 0 ||
(error = parse_header(&hdr, &head_len, head, decompressed)) < 0)
goto done;
if (!git_object_typeisloose(hdr.type)) {
git_error_set(GIT_ERROR_ODB, "failed to inflate disk object");
error = -1;
goto done;
}
/*
* allocate a buffer and inflate the object data into it
* (including the initial sequence in the head buffer).
*/
if (GIT_ADD_SIZET_OVERFLOW(&alloc_size, hdr.size, 1) ||
(body = git__calloc(1, alloc_size)) == NULL) {
error = -1;
goto done;
}
GIT_ASSERT(decompressed >= head_len);
body_len = decompressed - head_len;
if (body_len)
memcpy(body, head + head_len, body_len);
decompressed = hdr.size - body_len;
if ((error = git_zstream_get_output(body + body_len, &decompressed, &zstream)) < 0)
goto done;
if (!git_zstream_done(&zstream)) {
git_error_set(GIT_ERROR_ZLIB, "failed to finish zlib inflation: stream aborted prematurely");
error = -1;
goto done;
}
body[hdr.size] = '\0';
out->data = body;
out->len = hdr.size;
out->type = hdr.type;
done:
if (error < 0)
git__free(body);
git_zstream_free(&zstream);
return error;
}
static int read_loose(git_rawobj *out, git_buf *loc)
{
int error;
git_buf obj = GIT_BUF_INIT;
GIT_ASSERT_ARG(out);
GIT_ASSERT_ARG(loc);
if (git_buf_oom(loc))
return -1;
out->data = NULL;
out->len = 0;
out->type = GIT_OBJECT_INVALID;
if ((error = git_futils_readbuffer(&obj, loc->ptr)) < 0)
goto done;
if (!is_zlib_compressed_data((unsigned char *)obj.ptr, obj.size))
error = read_loose_packlike(out, &obj);
else
error = read_loose_standard(out, &obj);
done:
git_buf_dispose(&obj);
return error;
}
static int read_header_loose_packlike(
git_rawobj *out, const unsigned char *data, size_t len)
{
obj_hdr hdr;
size_t header_len;
int error;
if ((error = parse_header_packlike(&hdr, &header_len, data, len)) < 0)
return error;
out->len = hdr.size;
out->type = hdr.type;
return error;
}
static int read_header_loose_standard(
git_rawobj *out, const unsigned char *data, size_t len)
{
git_zstream zs = GIT_ZSTREAM_INIT;
obj_hdr hdr = {0};
unsigned char inflated[MAX_HEADER_LEN] = {0};
size_t header_len, inflated_len = sizeof(inflated);
int error;
if ((error = git_zstream_init(&zs, GIT_ZSTREAM_INFLATE)) < 0 ||
(error = git_zstream_set_input(&zs, data, len)) < 0 ||
(error = git_zstream_get_output_chunk(inflated, &inflated_len, &zs)) < 0 ||
(error = parse_header(&hdr, &header_len, inflated, inflated_len)) < 0)
goto done;
out->len = hdr.size;
out->type = hdr.type;
done:
git_zstream_free(&zs);
return error;
}
static int read_header_loose(git_rawobj *out, git_buf *loc)
{
unsigned char obj[1024];
ssize_t obj_len;
int fd, error;
GIT_ASSERT_ARG(out);
GIT_ASSERT_ARG(loc);
if (git_buf_oom(loc))
return -1;
out->data = NULL;
if ((error = fd = git_futils_open_ro(loc->ptr)) < 0)
goto done;
if ((obj_len = p_read(fd, obj, sizeof(obj))) < 0) {
error = (int)obj_len;
goto done;
}
if (!is_zlib_compressed_data(obj, (size_t)obj_len))
error = read_header_loose_packlike(out, obj, (size_t)obj_len);
else
error = read_header_loose_standard(out, obj, (size_t)obj_len);
if (!error && !git_object_typeisloose(out->type)) {
git_error_set(GIT_ERROR_ZLIB, "failed to read loose object header");
error = -1;
goto done;
}
done:
if (fd >= 0)
p_close(fd);
return error;
}
static int locate_object(
git_buf *object_location,
loose_backend *backend,
const git_oid *oid)
{
int error = object_file_name(object_location, backend, oid);
if (!error && !git_path_exists(object_location->ptr))
return GIT_ENOTFOUND;
return error;
}
/* Explore an entry of a directory and see if it matches a short oid */
static int fn_locate_object_short_oid(void *state, git_buf *pathbuf) {
loose_locate_object_state *sstate = (loose_locate_object_state *)state;
if (git_buf_len(pathbuf) - sstate->dir_len != GIT_OID_HEXSZ - 2) {
/* Entry cannot be an object. Continue to next entry */
return 0;
}
if (git_path_isdir(pathbuf->ptr) == false) {
/* We are already in the directory matching the 2 first hex characters,
* compare the first ncmp characters of the oids */
if (!memcmp(sstate->short_oid + 2,
(unsigned char *)pathbuf->ptr + sstate->dir_len,
sstate->short_oid_len - 2)) {
if (!sstate->found) {
sstate->res_oid[0] = sstate->short_oid[0];
sstate->res_oid[1] = sstate->short_oid[1];
memcpy(sstate->res_oid+2, pathbuf->ptr+sstate->dir_len, GIT_OID_HEXSZ-2);
}
sstate->found++;
}
}
if (sstate->found > 1)
return GIT_EAMBIGUOUS;
return 0;
}
/* Locate an object matching a given short oid */
static int locate_object_short_oid(
git_buf *object_location,
git_oid *res_oid,
loose_backend *backend,
const git_oid *short_oid,
size_t len)
{
char *objects_dir = backend->objects_dir;
size_t dir_len = strlen(objects_dir), alloc_len;
loose_locate_object_state state;
int error;
/* prealloc memory for OBJ_DIR/xx/xx..38x..xx */
GIT_ERROR_CHECK_ALLOC_ADD(&alloc_len, dir_len, GIT_OID_HEXSZ);
GIT_ERROR_CHECK_ALLOC_ADD(&alloc_len, alloc_len, 3);
if (git_buf_grow(object_location, alloc_len) < 0)
return -1;
git_buf_set(object_location, objects_dir, dir_len);
git_path_to_dir(object_location);
/* save adjusted position at end of dir so it can be restored later */
dir_len = git_buf_len(object_location);
/* Convert raw oid to hex formatted oid */
git_oid_fmt((char *)state.short_oid, short_oid);
/* Explore OBJ_DIR/xx/ where xx is the beginning of hex formatted short oid */
if (git_buf_put(object_location, (char *)state.short_oid, 3) < 0)
return -1;
object_location->ptr[object_location->size - 1] = '/';
/* Check that directory exists */
if (git_path_isdir(object_location->ptr) == false)
return git_odb__error_notfound("no matching loose object for prefix",
short_oid, len);
state.dir_len = git_buf_len(object_location);
state.short_oid_len = len;
state.found = 0;
/* Explore directory to find a unique object matching short_oid */
error = git_path_direach(
object_location, 0, fn_locate_object_short_oid, &state);
if (error < 0 && error != GIT_EAMBIGUOUS)
return error;
if (!state.found)
return git_odb__error_notfound("no matching loose object for prefix",
short_oid, len);
if (state.found > 1)
return git_odb__error_ambiguous("multiple matches in loose objects");
/* Convert obtained hex formatted oid to raw */
error = git_oid_fromstr(res_oid, (char *)state.res_oid);
if (error)
return error;
/* Update the location according to the oid obtained */
GIT_ERROR_CHECK_ALLOC_ADD(&alloc_len, dir_len, GIT_OID_HEXSZ);
GIT_ERROR_CHECK_ALLOC_ADD(&alloc_len, alloc_len, 2);
git_buf_truncate(object_location, dir_len);
if (git_buf_grow(object_location, alloc_len) < 0)
return -1;
git_oid_pathfmt(object_location->ptr + dir_len, res_oid);
object_location->size += GIT_OID_HEXSZ + 1;
object_location->ptr[object_location->size] = '\0';
return 0;
}
/***********************************************************
*
* LOOSE BACKEND PUBLIC API
*
* Implement the git_odb_backend API calls
*
***********************************************************/
static int loose_backend__read_header(size_t *len_p, git_object_t *type_p, git_odb_backend *backend, const git_oid *oid)
{
git_buf object_path = GIT_BUF_INIT;
git_rawobj raw;
int error;
GIT_ASSERT_ARG(backend);
GIT_ASSERT_ARG(oid);
raw.len = 0;
raw.type = GIT_OBJECT_INVALID;
if (locate_object(&object_path, (loose_backend *)backend, oid) < 0) {
error = git_odb__error_notfound("no matching loose object",
oid, GIT_OID_HEXSZ);
} else if ((error = read_header_loose(&raw, &object_path)) == 0) {
*len_p = raw.len;
*type_p = raw.type;
}
git_buf_dispose(&object_path);
return error;
}
static int loose_backend__read(void **buffer_p, size_t *len_p, git_object_t *type_p, git_odb_backend *backend, const git_oid *oid)
{
git_buf object_path = GIT_BUF_INIT;
git_rawobj raw;
int error = 0;
GIT_ASSERT_ARG(backend);
GIT_ASSERT_ARG(oid);
if (locate_object(&object_path, (loose_backend *)backend, oid) < 0) {
error = git_odb__error_notfound("no matching loose object",
oid, GIT_OID_HEXSZ);
} else if ((error = read_loose(&raw, &object_path)) == 0) {
*buffer_p = raw.data;
*len_p = raw.len;
*type_p = raw.type;
}
git_buf_dispose(&object_path);
return error;
}
static int loose_backend__read_prefix(
git_oid *out_oid,
void **buffer_p,
size_t *len_p,
git_object_t *type_p,
git_odb_backend *backend,
const git_oid *short_oid,
size_t len)
{
int error = 0;
GIT_ASSERT_ARG(len >= GIT_OID_MINPREFIXLEN && len <= GIT_OID_HEXSZ);
if (len == GIT_OID_HEXSZ) {
/* We can fall back to regular read method */
error = loose_backend__read(buffer_p, len_p, type_p, backend, short_oid);
if (!error)
git_oid_cpy(out_oid, short_oid);
} else {
git_buf object_path = GIT_BUF_INIT;
git_rawobj raw;
GIT_ASSERT_ARG(backend && short_oid);
if ((error = locate_object_short_oid(&object_path, out_oid,
(loose_backend *)backend, short_oid, len)) == 0 &&
(error = read_loose(&raw, &object_path)) == 0)
{
*buffer_p = raw.data;
*len_p = raw.len;
*type_p = raw.type;
}
git_buf_dispose(&object_path);
}
return error;
}
static int loose_backend__exists(git_odb_backend *backend, const git_oid *oid)
{
git_buf object_path = GIT_BUF_INIT;
int error;
GIT_ASSERT_ARG(backend);
GIT_ASSERT_ARG(oid);
error = locate_object(&object_path, (loose_backend *)backend, oid);
git_buf_dispose(&object_path);
return !error;
}
static int loose_backend__exists_prefix(
git_oid *out, git_odb_backend *backend, const git_oid *short_id, size_t len)
{
git_buf object_path = GIT_BUF_INIT;
int error;
GIT_ASSERT_ARG(backend);
GIT_ASSERT_ARG(out);
GIT_ASSERT_ARG(short_id);
GIT_ASSERT_ARG(len >= GIT_OID_MINPREFIXLEN);
error = locate_object_short_oid(
&object_path, out, (loose_backend *)backend, short_id, len);
git_buf_dispose(&object_path);
return error;
}
struct foreach_state {
size_t dir_len;
git_odb_foreach_cb cb;
void *data;
};
GIT_INLINE(int) filename_to_oid(git_oid *oid, const char *ptr)
{
int v, i = 0;
if (strlen(ptr) != GIT_OID_HEXSZ+1)
return -1;
if (ptr[2] != '/') {
return -1;
}
v = (git__fromhex(ptr[i]) << 4) | git__fromhex(ptr[i+1]);
if (v < 0)
return -1;
oid->id[0] = (unsigned char) v;
ptr += 3;
for (i = 0; i < 38; i += 2) {
v = (git__fromhex(ptr[i]) << 4) | git__fromhex(ptr[i + 1]);
if (v < 0)
return -1;
oid->id[1 + i/2] = (unsigned char) v;
}
return 0;
}
static int foreach_object_dir_cb(void *_state, git_buf *path)
{
git_oid oid;
struct foreach_state *state = (struct foreach_state *) _state;
if (filename_to_oid(&oid, path->ptr + state->dir_len) < 0)
return 0;
return git_error_set_after_callback_function(
state->cb(&oid, state->data), "git_odb_foreach");
}
static int foreach_cb(void *_state, git_buf *path)
{
struct foreach_state *state = (struct foreach_state *) _state;
/* non-dir is some stray file, ignore it */
if (!git_path_isdir(git_buf_cstr(path)))
return 0;
return git_path_direach(path, 0, foreach_object_dir_cb, state);
}
static int loose_backend__foreach(git_odb_backend *_backend, git_odb_foreach_cb cb, void *data)
{
char *objects_dir;
int error;
git_buf buf = GIT_BUF_INIT;
struct foreach_state state;
loose_backend *backend = (loose_backend *) _backend;
GIT_ASSERT_ARG(backend);
GIT_ASSERT_ARG(cb);
objects_dir = backend->objects_dir;
git_buf_sets(&buf, objects_dir);
git_path_to_dir(&buf);
if (git_buf_oom(&buf))
return -1;
memset(&state, 0, sizeof(state));
state.cb = cb;
state.data = data;
state.dir_len = git_buf_len(&buf);
error = git_path_direach(&buf, 0, foreach_cb, &state);
git_buf_dispose(&buf);
return error;
}
static int loose_backend__writestream_finalize(git_odb_stream *_stream, const git_oid *oid)
{
loose_writestream *stream = (loose_writestream *)_stream;
loose_backend *backend = (loose_backend *)_stream->backend;
git_buf final_path = GIT_BUF_INIT;
int error = 0;
if (object_file_name(&final_path, backend, oid) < 0 ||
object_mkdir(&final_path, backend) < 0)
error = -1;
else
error = git_filebuf_commit_at(
&stream->fbuf, final_path.ptr);
git_buf_dispose(&final_path);
return error;
}
static int loose_backend__writestream_write(git_odb_stream *_stream, const char *data, size_t len)
{
loose_writestream *stream = (loose_writestream *)_stream;
return git_filebuf_write(&stream->fbuf, data, len);
}
static void loose_backend__writestream_free(git_odb_stream *_stream)
{
loose_writestream *stream = (loose_writestream *)_stream;
git_filebuf_cleanup(&stream->fbuf);
git__free(stream);
}
static int filebuf_flags(loose_backend *backend)
{
int flags = GIT_FILEBUF_TEMPORARY |
(backend->object_zlib_level << GIT_FILEBUF_DEFLATE_SHIFT);
if (backend->fsync_object_files || git_repository__fsync_gitdir)
flags |= GIT_FILEBUF_FSYNC;
return flags;
}
static int loose_backend__writestream(git_odb_stream **stream_out, git_odb_backend *_backend, git_object_size_t length, git_object_t type)
{
loose_backend *backend;
loose_writestream *stream = NULL;
char hdr[MAX_HEADER_LEN];
git_buf tmp_path = GIT_BUF_INIT;
size_t hdrlen;
int error;
GIT_ASSERT_ARG(_backend);
backend = (loose_backend *)_backend;
*stream_out = NULL;
if ((error = git_odb__format_object_header(&hdrlen,
hdr, sizeof(hdr), length, type)) < 0)
return error;
stream = git__calloc(1, sizeof(loose_writestream));
GIT_ERROR_CHECK_ALLOC(stream);
stream->stream.backend = _backend;
stream->stream.read = NULL; /* read only */
stream->stream.write = &loose_backend__writestream_write;
stream->stream.finalize_write = &loose_backend__writestream_finalize;
stream->stream.free = &loose_backend__writestream_free;
stream->stream.mode = GIT_STREAM_WRONLY;
if (git_buf_joinpath(&tmp_path, backend->objects_dir, "tmp_object") < 0 ||
git_filebuf_open(&stream->fbuf, tmp_path.ptr, filebuf_flags(backend),
backend->object_file_mode) < 0 ||
stream->stream.write((git_odb_stream *)stream, hdr, hdrlen) < 0)
{
git_filebuf_cleanup(&stream->fbuf);
git__free(stream);
stream = NULL;
}
git_buf_dispose(&tmp_path);
*stream_out = (git_odb_stream *)stream;
return !stream ? -1 : 0;
}
static int loose_backend__readstream_read(
git_odb_stream *_stream,
char *buffer,
size_t buffer_len)
{
loose_readstream *stream = (loose_readstream *)_stream;
size_t start_remain = stream->start_len - stream->start_read;
int total = 0, error;
buffer_len = min(buffer_len, INT_MAX);
/*
* if we read more than just the header in the initial read, play
* that back for the caller.
*/
if (start_remain && buffer_len) {
size_t chunk = min(start_remain, buffer_len);
memcpy(buffer, stream->start + stream->start_read, chunk);
buffer += chunk;
stream->start_read += chunk;
total += (int)chunk;
buffer_len -= chunk;
}
if (buffer_len) {
size_t chunk = buffer_len;
if ((error = git_zstream_get_output(buffer, &chunk, &stream->zstream)) < 0)
return error;
total += (int)chunk;
}
return (int)total;
}
static void loose_backend__readstream_free(git_odb_stream *_stream)
{
loose_readstream *stream = (loose_readstream *)_stream;
git_futils_mmap_free(&stream->map);
git_zstream_free(&stream->zstream);
git__free(stream);
}
static int loose_backend__readstream_packlike(
obj_hdr *hdr,
loose_readstream *stream)
{
const unsigned char *data;
size_t data_len, head_len;
int error;
data = stream->map.data;
data_len = stream->map.len;
/*
* read the object header, which is an (uncompressed)
* binary encoding of the object type and size.
*/
if ((error = parse_header_packlike(hdr, &head_len, data, data_len)) < 0)
return error;
if (!git_object_typeisloose(hdr->type)) {
git_error_set(GIT_ERROR_ODB, "failed to inflate loose object");
return -1;
}
return git_zstream_set_input(&stream->zstream,
data + head_len, data_len - head_len);
}
static int loose_backend__readstream_standard(
obj_hdr *hdr,
loose_readstream *stream)
{
unsigned char head[MAX_HEADER_LEN];
size_t init, head_len;
int error;
if ((error = git_zstream_set_input(&stream->zstream,
stream->map.data, stream->map.len)) < 0)
return error;
init = sizeof(head);
/*
* inflate the initial part of the compressed buffer in order to
* parse the header; read the largest header possible, then store
* it in the `start` field of the stream object.
*/
if ((error = git_zstream_get_output(head, &init, &stream->zstream)) < 0 ||
(error = parse_header(hdr, &head_len, head, init)) < 0)
return error;
if (!git_object_typeisloose(hdr->type)) {
git_error_set(GIT_ERROR_ODB, "failed to inflate disk object");
return -1;
}
if (init > head_len) {
stream->start_len = init - head_len;
memcpy(stream->start, head + head_len, init - head_len);
}
return 0;
}
static int loose_backend__readstream(
git_odb_stream **stream_out,
size_t *len_out,
git_object_t *type_out,
git_odb_backend *_backend,
const git_oid *oid)
{
loose_backend *backend;
loose_readstream *stream = NULL;
git_hash_ctx *hash_ctx = NULL;
git_buf object_path = GIT_BUF_INIT;
obj_hdr hdr;
int error = 0;
GIT_ASSERT_ARG(stream_out);
GIT_ASSERT_ARG(len_out);
GIT_ASSERT_ARG(type_out);
GIT_ASSERT_ARG(_backend);
GIT_ASSERT_ARG(oid);
backend = (loose_backend *)_backend;
*stream_out = NULL;
*len_out = 0;
*type_out = GIT_OBJECT_INVALID;
if (locate_object(&object_path, backend, oid) < 0) {
error = git_odb__error_notfound("no matching loose object",
oid, GIT_OID_HEXSZ);
goto done;
}
stream = git__calloc(1, sizeof(loose_readstream));
GIT_ERROR_CHECK_ALLOC(stream);
hash_ctx = git__malloc(sizeof(git_hash_ctx));
GIT_ERROR_CHECK_ALLOC(hash_ctx);
if ((error = git_hash_ctx_init(hash_ctx)) < 0 ||
(error = git_futils_mmap_ro_file(&stream->map, object_path.ptr)) < 0 ||
(error = git_zstream_init(&stream->zstream, GIT_ZSTREAM_INFLATE)) < 0)
goto done;
/* check for a packlike loose object */
if (!is_zlib_compressed_data(stream->map.data, stream->map.len))
error = loose_backend__readstream_packlike(&hdr, stream);
else
error = loose_backend__readstream_standard(&hdr, stream);
if (error < 0)
goto done;
stream->stream.backend = _backend;
stream->stream.hash_ctx = hash_ctx;
stream->stream.read = &loose_backend__readstream_read;
stream->stream.free = &loose_backend__readstream_free;
*stream_out = (git_odb_stream *)stream;
*len_out = hdr.size;
*type_out = hdr.type;
done:
if (error < 0) {
if (stream) {
git_futils_mmap_free(&stream->map);
git_zstream_free(&stream->zstream);
git__free(stream);
}
if (hash_ctx) {
git_hash_ctx_cleanup(hash_ctx);
git__free(hash_ctx);
}
}
git_buf_dispose(&object_path);
return error;
}
static int loose_backend__write(git_odb_backend *_backend, const git_oid *oid, const void *data, size_t len, git_object_t type)
{
int error = 0;
git_buf final_path = GIT_BUF_INIT;
char header[MAX_HEADER_LEN];
size_t header_len;
git_filebuf fbuf = GIT_FILEBUF_INIT;
loose_backend *backend;
backend = (loose_backend *)_backend;
/* prepare the header for the file */
if ((error = git_odb__format_object_header(&header_len,
header, sizeof(header), len, type)) < 0)
goto cleanup;
if (git_buf_joinpath(&final_path, backend->objects_dir, "tmp_object") < 0 ||
git_filebuf_open(&fbuf, final_path.ptr, filebuf_flags(backend),
backend->object_file_mode) < 0)
{
error = -1;
goto cleanup;
}
git_filebuf_write(&fbuf, header, header_len);
git_filebuf_write(&fbuf, data, len);
if (object_file_name(&final_path, backend, oid) < 0 ||
object_mkdir(&final_path, backend) < 0 ||
git_filebuf_commit_at(&fbuf, final_path.ptr) < 0)
error = -1;
cleanup:
if (error < 0)
git_filebuf_cleanup(&fbuf);
git_buf_dispose(&final_path);
return error;
}
static int loose_backend__freshen(
git_odb_backend *_backend,
const git_oid *oid)
{
loose_backend *backend = (loose_backend *)_backend;
git_buf path = GIT_BUF_INIT;
int error;
if (object_file_name(&path, backend, oid) < 0)
return -1;
error = git_futils_touch(path.ptr, NULL);
git_buf_dispose(&path);
return error;
}
static void loose_backend__free(git_odb_backend *_backend)
{
git__free(_backend);
}
int git_odb_backend_loose(
git_odb_backend **backend_out,
const char *objects_dir,
int compression_level,
int do_fsync,
unsigned int dir_mode,
unsigned int file_mode)
{
loose_backend *backend;
size_t objects_dirlen, alloclen;
GIT_ASSERT_ARG(backend_out);
GIT_ASSERT_ARG(objects_dir);
objects_dirlen = strlen(objects_dir);
GIT_ERROR_CHECK_ALLOC_ADD(&alloclen, sizeof(loose_backend), objects_dirlen);
GIT_ERROR_CHECK_ALLOC_ADD(&alloclen, alloclen, 2);
backend = git__calloc(1, alloclen);
GIT_ERROR_CHECK_ALLOC(backend);
backend->parent.version = GIT_ODB_BACKEND_VERSION;
backend->objects_dirlen = objects_dirlen;
memcpy(backend->objects_dir, objects_dir, objects_dirlen);
if (backend->objects_dir[backend->objects_dirlen - 1] != '/')
backend->objects_dir[backend->objects_dirlen++] = '/';
if (compression_level < 0)
compression_level = Z_BEST_SPEED;
if (dir_mode == 0)
dir_mode = GIT_OBJECT_DIR_MODE;
if (file_mode == 0)
file_mode = GIT_OBJECT_FILE_MODE;
backend->object_zlib_level = compression_level;
backend->fsync_object_files = do_fsync;
backend->object_dir_mode = dir_mode;
backend->object_file_mode = file_mode;
backend->parent.read = &loose_backend__read;
backend->parent.write = &loose_backend__write;
backend->parent.read_prefix = &loose_backend__read_prefix;
backend->parent.read_header = &loose_backend__read_header;
backend->parent.writestream = &loose_backend__writestream;
backend->parent.readstream = &loose_backend__readstream;
backend->parent.exists = &loose_backend__exists;
backend->parent.exists_prefix = &loose_backend__exists_prefix;
backend->parent.foreach = &loose_backend__foreach;
backend->parent.freshen = &loose_backend__freshen;
backend->parent.free = &loose_backend__free;
*backend_out = (git_odb_backend *)backend;
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/tree-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 "tree-cache.h"
#include "pool.h"
#include "tree.h"
static git_tree_cache *find_child(
const git_tree_cache *tree, const char *path, const char *end)
{
size_t i, dirlen = end ? (size_t)(end - path) : strlen(path);
for (i = 0; i < tree->children_count; ++i) {
git_tree_cache *child = tree->children[i];
if (child->namelen == dirlen && !memcmp(path, child->name, dirlen))
return child;
}
return NULL;
}
void git_tree_cache_invalidate_path(git_tree_cache *tree, const char *path)
{
const char *ptr = path, *end;
if (tree == NULL)
return;
tree->entry_count = -1;
while (ptr != NULL) {
end = strchr(ptr, '/');
if (end == NULL) /* End of path */
break;
tree = find_child(tree, ptr, end);
if (tree == NULL) /* We don't have that tree */
return;
tree->entry_count = -1;
ptr = end + 1;
}
}
const git_tree_cache *git_tree_cache_get(const git_tree_cache *tree, const char *path)
{
const char *ptr = path, *end;
if (tree == NULL) {
return NULL;
}
while (1) {
end = strchr(ptr, '/');
tree = find_child(tree, ptr, end);
if (tree == NULL) /* Can't find it */
return NULL;
if (end == NULL || *end + 1 == '\0')
return tree;
ptr = end + 1;
}
}
static int read_tree_internal(git_tree_cache **out,
const char **buffer_in, const char *buffer_end,
git_pool *pool)
{
git_tree_cache *tree = NULL;
const char *name_start, *buffer;
int count;
buffer = name_start = *buffer_in;
if ((buffer = memchr(buffer, '\0', buffer_end - buffer)) == NULL)
goto corrupted;
if (++buffer >= buffer_end)
goto corrupted;
if (git_tree_cache_new(&tree, name_start, pool) < 0)
return -1;
/* Blank-terminated ASCII decimal number of entries in this tree */
if (git__strntol32(&count, buffer, buffer_end - buffer, &buffer, 10) < 0)
goto corrupted;
tree->entry_count = count;
if (*buffer != ' ' || ++buffer >= buffer_end)
goto corrupted;
/* Number of children of the tree, newline-terminated */
if (git__strntol32(&count, buffer, buffer_end - buffer, &buffer, 10) < 0 || count < 0)
goto corrupted;
tree->children_count = count;
if (*buffer != '\n' || ++buffer > buffer_end)
goto corrupted;
/* The SHA1 is only there if it's not invalidated */
if (tree->entry_count >= 0) {
/* 160-bit SHA-1 for this tree and it's children */
if (buffer + GIT_OID_RAWSZ > buffer_end)
goto corrupted;
git_oid_fromraw(&tree->oid, (const unsigned char *)buffer);
buffer += GIT_OID_RAWSZ;
}
/* Parse children: */
if (tree->children_count > 0) {
size_t i, bufsize;
GIT_ERROR_CHECK_ALLOC_MULTIPLY(&bufsize, tree->children_count, sizeof(git_tree_cache*));
tree->children = git_pool_malloc(pool, bufsize);
GIT_ERROR_CHECK_ALLOC(tree->children);
memset(tree->children, 0x0, bufsize);
for (i = 0; i < tree->children_count; ++i) {
if (read_tree_internal(&tree->children[i], &buffer, buffer_end, pool) < 0)
goto corrupted;
}
}
*buffer_in = buffer;
*out = tree;
return 0;
corrupted:
git_error_set(GIT_ERROR_INDEX, "corrupted TREE extension in index");
return -1;
}
int git_tree_cache_read(git_tree_cache **tree, const char *buffer, size_t buffer_size, git_pool *pool)
{
const char *buffer_end = buffer + buffer_size;
if (read_tree_internal(tree, &buffer, buffer_end, pool) < 0)
return -1;
if (buffer < buffer_end) {
git_error_set(GIT_ERROR_INDEX, "corrupted TREE extension in index (unexpected trailing data)");
return -1;
}
return 0;
}
static int read_tree_recursive(git_tree_cache *cache, const git_tree *tree, git_pool *pool)
{
git_repository *repo;
size_t i, j, nentries, ntrees, alloc_size;
int error;
repo = git_tree_owner(tree);
git_oid_cpy(&cache->oid, git_tree_id(tree));
nentries = git_tree_entrycount(tree);
/*
* We make sure we know how many trees we need to allocate for
* so we don't have to realloc and change the pointers for the
* parents.
*/
ntrees = 0;
for (i = 0; i < nentries; i++) {
const git_tree_entry *entry;
entry = git_tree_entry_byindex(tree, i);
if (git_tree_entry_filemode(entry) == GIT_FILEMODE_TREE)
ntrees++;
}
GIT_ERROR_CHECK_ALLOC_MULTIPLY(&alloc_size, ntrees, sizeof(git_tree_cache *));
cache->children_count = ntrees;
cache->children = git_pool_mallocz(pool, alloc_size);
GIT_ERROR_CHECK_ALLOC(cache->children);
j = 0;
for (i = 0; i < nentries; i++) {
const git_tree_entry *entry;
git_tree *subtree;
entry = git_tree_entry_byindex(tree, i);
if (git_tree_entry_filemode(entry) != GIT_FILEMODE_TREE) {
cache->entry_count++;
continue;
}
if ((error = git_tree_cache_new(&cache->children[j], git_tree_entry_name(entry), pool)) < 0)
return error;
if ((error = git_tree_lookup(&subtree, repo, git_tree_entry_id(entry))) < 0)
return error;
error = read_tree_recursive(cache->children[j], subtree, pool);
git_tree_free(subtree);
cache->entry_count += cache->children[j]->entry_count;
j++;
if (error < 0)
return error;
}
return 0;
}
int git_tree_cache_read_tree(git_tree_cache **out, const git_tree *tree, git_pool *pool)
{
int error;
git_tree_cache *cache;
if ((error = git_tree_cache_new(&cache, "", pool)) < 0)
return error;
if ((error = read_tree_recursive(cache, tree, pool)) < 0)
return error;
*out = cache;
return 0;
}
int git_tree_cache_new(git_tree_cache **out, const char *name, git_pool *pool)
{
size_t name_len, alloc_size;
git_tree_cache *tree;
name_len = strlen(name);
GIT_ERROR_CHECK_ALLOC_ADD3(&alloc_size, sizeof(git_tree_cache), name_len, 1);
tree = git_pool_malloc(pool, alloc_size);
GIT_ERROR_CHECK_ALLOC(tree);
memset(tree, 0x0, sizeof(git_tree_cache));
/* NUL-terminated tree name */
tree->namelen = name_len;
memcpy(tree->name, name, name_len);
tree->name[name_len] = '\0';
*out = tree;
return 0;
}
static void write_tree(git_buf *out, git_tree_cache *tree)
{
size_t i;
git_buf_printf(out, "%s%c%"PRIdZ" %"PRIuZ"\n", tree->name, 0, tree->entry_count, tree->children_count);
if (tree->entry_count != -1)
git_buf_put(out, (const char *) &tree->oid, GIT_OID_RAWSZ);
for (i = 0; i < tree->children_count; i++)
write_tree(out, tree->children[i]);
}
int git_tree_cache_write(git_buf *out, git_tree_cache *tree)
{
write_tree(out, tree);
return git_buf_oom(out) ? -1 : 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.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_h__
#define INCLUDE_diff_h__
#include "common.h"
#include "git2/diff.h"
#include "git2/patch.h"
#include "git2/sys/diff.h"
#include "git2/oid.h"
#include <stdio.h>
#include "vector.h"
#include "buffer.h"
#include "iterator.h"
#include "repository.h"
#include "pool.h"
#include "odb.h"
#define DIFF_OLD_PREFIX_DEFAULT "a/"
#define DIFF_NEW_PREFIX_DEFAULT "b/"
typedef enum {
GIT_DIFF_TYPE_UNKNOWN = 0,
GIT_DIFF_TYPE_GENERATED = 1,
GIT_DIFF_TYPE_PARSED = 2,
} git_diff_origin_t;
struct git_diff {
git_refcount rc;
git_repository *repo;
git_attr_session attrsession;
git_diff_origin_t type;
git_diff_options opts;
git_vector deltas; /* vector of git_diff_delta */
git_pool pool;
git_iterator_t old_src;
git_iterator_t new_src;
git_diff_perfdata perf;
int (*strcomp)(const char *, const char *);
int (*strncomp)(const char *, const char *, size_t);
int (*pfxcomp)(const char *str, const char *pfx);
int (*entrycomp)(const void *a, const void *b);
int (*patch_fn)(git_patch **out, git_diff *diff, size_t idx);
void (*free_fn)(git_diff *diff);
};
extern int git_diff_delta__format_file_header(
git_buf *out,
const git_diff_delta *delta,
const char *oldpfx,
const char *newpfx,
int oid_strlen,
bool print_index);
extern int git_diff_delta__cmp(const void *a, const void *b);
extern int git_diff_delta__casecmp(const void *a, const void *b);
extern int git_diff__entry_cmp(const void *a, const void *b);
extern int git_diff__entry_icmp(const void *a, const void *b);
#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/checkout.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 "checkout.h"
#include "git2/repository.h"
#include "git2/refs.h"
#include "git2/tree.h"
#include "git2/blob.h"
#include "git2/config.h"
#include "git2/diff.h"
#include "git2/submodule.h"
#include "git2/sys/index.h"
#include "git2/sys/filter.h"
#include "git2/merge.h"
#include "refs.h"
#include "repository.h"
#include "index.h"
#include "filter.h"
#include "blob.h"
#include "diff.h"
#include "diff_generate.h"
#include "pathspec.h"
#include "diff_xdiff.h"
#include "path.h"
#include "attr.h"
#include "pool.h"
#include "strmap.h"
/* See docs/checkout-internals.md for more information */
enum {
CHECKOUT_ACTION__NONE = 0,
CHECKOUT_ACTION__REMOVE = 1,
CHECKOUT_ACTION__UPDATE_BLOB = 2,
CHECKOUT_ACTION__UPDATE_SUBMODULE = 4,
CHECKOUT_ACTION__CONFLICT = 8,
CHECKOUT_ACTION__REMOVE_CONFLICT = 16,
CHECKOUT_ACTION__UPDATE_CONFLICT = 32,
CHECKOUT_ACTION__MAX = 32,
CHECKOUT_ACTION__REMOVE_AND_UPDATE =
(CHECKOUT_ACTION__UPDATE_BLOB | CHECKOUT_ACTION__REMOVE),
};
typedef struct {
git_repository *repo;
git_iterator *target;
git_diff *diff;
git_checkout_options opts;
bool opts_free_baseline;
char *pfx;
git_index *index;
git_pool pool;
git_vector removes;
git_vector remove_conflicts;
git_vector update_conflicts;
git_vector *update_reuc;
git_vector *update_names;
git_buf target_path;
size_t target_len;
git_buf tmp;
unsigned int strategy;
int can_symlink;
int respect_filemode;
bool reload_submodules;
size_t total_steps;
size_t completed_steps;
git_checkout_perfdata perfdata;
git_strmap *mkdir_map;
git_attr_session attr_session;
} checkout_data;
typedef struct {
const git_index_entry *ancestor;
const git_index_entry *ours;
const git_index_entry *theirs;
int name_collision:1,
directoryfile:1,
one_to_two:1,
binary:1,
submodule:1;
} checkout_conflictdata;
static int checkout_notify(
checkout_data *data,
git_checkout_notify_t why,
const git_diff_delta *delta,
const git_index_entry *wditem)
{
git_diff_file wdfile;
const git_diff_file *baseline = NULL, *target = NULL, *workdir = NULL;
const char *path = NULL;
if (!data->opts.notify_cb ||
(why & data->opts.notify_flags) == 0)
return 0;
if (wditem) {
memset(&wdfile, 0, sizeof(wdfile));
git_oid_cpy(&wdfile.id, &wditem->id);
wdfile.path = wditem->path;
wdfile.size = wditem->file_size;
wdfile.flags = GIT_DIFF_FLAG_VALID_ID;
wdfile.mode = wditem->mode;
workdir = &wdfile;
path = wditem->path;
}
if (delta) {
switch (delta->status) {
case GIT_DELTA_UNMODIFIED:
case GIT_DELTA_MODIFIED:
case GIT_DELTA_TYPECHANGE:
default:
baseline = &delta->old_file;
target = &delta->new_file;
break;
case GIT_DELTA_ADDED:
case GIT_DELTA_IGNORED:
case GIT_DELTA_UNTRACKED:
case GIT_DELTA_UNREADABLE:
target = &delta->new_file;
break;
case GIT_DELTA_DELETED:
baseline = &delta->old_file;
break;
}
path = delta->old_file.path;
}
{
int error = data->opts.notify_cb(
why, path, baseline, target, workdir, data->opts.notify_payload);
return git_error_set_after_callback_function(
error, "git_checkout notification");
}
}
GIT_INLINE(bool) is_workdir_base_or_new(
const git_oid *workdir_id,
const git_diff_file *baseitem,
const git_diff_file *newitem)
{
return (git_oid__cmp(&baseitem->id, workdir_id) == 0 ||
git_oid__cmp(&newitem->id, workdir_id) == 0);
}
GIT_INLINE(bool) is_filemode_changed(git_filemode_t a, git_filemode_t b, int respect_filemode)
{
/* If core.filemode = false, ignore links in the repository and executable bit changes */
if (!respect_filemode) {
if (a == S_IFLNK)
a = GIT_FILEMODE_BLOB;
if (b == S_IFLNK)
b = GIT_FILEMODE_BLOB;
a &= ~0111;
b &= ~0111;
}
return (a != b);
}
static bool checkout_is_workdir_modified(
checkout_data *data,
const git_diff_file *baseitem,
const git_diff_file *newitem,
const git_index_entry *wditem)
{
git_oid oid;
const git_index_entry *ie;
/* handle "modified" submodule */
if (wditem->mode == GIT_FILEMODE_COMMIT) {
git_submodule *sm;
unsigned int sm_status = 0;
const git_oid *sm_oid = NULL;
bool rval = false;
if (git_submodule_lookup(&sm, data->repo, wditem->path) < 0) {
git_error_clear();
return true;
}
if (git_submodule_status(&sm_status, data->repo, wditem->path, GIT_SUBMODULE_IGNORE_UNSPECIFIED) < 0 ||
GIT_SUBMODULE_STATUS_IS_WD_DIRTY(sm_status))
rval = true;
else if ((sm_oid = git_submodule_wd_id(sm)) == NULL)
rval = false;
else
rval = (git_oid__cmp(&baseitem->id, sm_oid) != 0);
git_submodule_free(sm);
return rval;
}
/*
* Look at the cache to decide if the workdir is modified: if the
* cache contents match the workdir contents, then we do not need
* to examine the working directory directly, instead we can
* examine the cache to see if _it_ has been modified. This allows
* us to avoid touching the disk.
*/
ie = git_index_get_bypath(data->index, wditem->path, 0);
if (ie != NULL &&
!git_index_entry_newer_than_index(ie, data->index) &&
git_index_time_eq(&wditem->mtime, &ie->mtime) &&
wditem->file_size == ie->file_size &&
!is_filemode_changed(wditem->mode, ie->mode, data->respect_filemode)) {
/* The workdir is modified iff the index entry is modified */
return !is_workdir_base_or_new(&ie->id, baseitem, newitem) ||
is_filemode_changed(baseitem->mode, ie->mode, data->respect_filemode);
}
/* depending on where base is coming from, we may or may not know
* the actual size of the data, so we can't rely on this shortcut.
*/
if (baseitem->size && wditem->file_size != baseitem->size)
return true;
/* if the workdir item is a directory, it cannot be a modified file */
if (S_ISDIR(wditem->mode))
return false;
if (is_filemode_changed(baseitem->mode, wditem->mode, data->respect_filemode))
return true;
if (git_diff__oid_for_entry(&oid, data->diff, wditem, wditem->mode, NULL) < 0)
return false;
/* Allow the checkout if the workdir is not modified *or* if the checkout
* target's contents are already in the working directory.
*/
return !is_workdir_base_or_new(&oid, baseitem, newitem);
}
#define CHECKOUT_ACTION_IF(FLAG,YES,NO) \
((data->strategy & GIT_CHECKOUT_##FLAG) ? CHECKOUT_ACTION__##YES : CHECKOUT_ACTION__##NO)
static int checkout_action_common(
int *action,
checkout_data *data,
const git_diff_delta *delta,
const git_index_entry *wd)
{
git_checkout_notify_t notify = GIT_CHECKOUT_NOTIFY_NONE;
if ((data->strategy & GIT_CHECKOUT_UPDATE_ONLY) != 0)
*action = (*action & ~CHECKOUT_ACTION__REMOVE);
if ((*action & CHECKOUT_ACTION__UPDATE_BLOB) != 0) {
if (S_ISGITLINK(delta->new_file.mode))
*action = (*action & ~CHECKOUT_ACTION__UPDATE_BLOB) |
CHECKOUT_ACTION__UPDATE_SUBMODULE;
/* to "update" a symlink, we must remove the old one first */
if (delta->new_file.mode == GIT_FILEMODE_LINK && wd != NULL)
*action |= CHECKOUT_ACTION__REMOVE;
/* if the file is on disk and doesn't match our mode, force update */
if (wd &&
GIT_PERMS_IS_EXEC(wd->mode) != GIT_PERMS_IS_EXEC(delta->new_file.mode))
*action |= CHECKOUT_ACTION__REMOVE;
notify = GIT_CHECKOUT_NOTIFY_UPDATED;
}
if ((*action & CHECKOUT_ACTION__CONFLICT) != 0)
notify = GIT_CHECKOUT_NOTIFY_CONFLICT;
return checkout_notify(data, notify, delta, wd);
}
static int checkout_action_no_wd(
int *action,
checkout_data *data,
const git_diff_delta *delta)
{
int error = 0;
*action = CHECKOUT_ACTION__NONE;
switch (delta->status) {
case GIT_DELTA_UNMODIFIED: /* case 12 */
error = checkout_notify(data, GIT_CHECKOUT_NOTIFY_DIRTY, delta, NULL);
if (error)
return error;
*action = CHECKOUT_ACTION_IF(RECREATE_MISSING, UPDATE_BLOB, NONE);
break;
case GIT_DELTA_ADDED: /* case 2 or 28 (and 5 but not really) */
*action = CHECKOUT_ACTION_IF(SAFE, UPDATE_BLOB, NONE);
break;
case GIT_DELTA_MODIFIED: /* case 13 (and 35 but not really) */
*action = CHECKOUT_ACTION_IF(RECREATE_MISSING, UPDATE_BLOB, CONFLICT);
break;
case GIT_DELTA_TYPECHANGE: /* case 21 (B->T) and 28 (T->B)*/
if (delta->new_file.mode == GIT_FILEMODE_TREE)
*action = CHECKOUT_ACTION_IF(SAFE, UPDATE_BLOB, NONE);
break;
case GIT_DELTA_DELETED: /* case 8 or 25 */
*action = CHECKOUT_ACTION_IF(SAFE, REMOVE, NONE);
break;
default: /* impossible */
break;
}
return checkout_action_common(action, data, delta, NULL);
}
static int checkout_target_fullpath(
git_buf **out, checkout_data *data, const char *path)
{
git_buf_truncate(&data->target_path, data->target_len);
if (path && git_buf_puts(&data->target_path, path) < 0)
return -1;
if (git_path_validate_workdir_buf(data->repo, &data->target_path) < 0)
return -1;
*out = &data->target_path;
return 0;
}
static bool wd_item_is_removable(
checkout_data *data, const git_index_entry *wd)
{
git_buf *full;
if (wd->mode != GIT_FILEMODE_TREE)
return true;
if (checkout_target_fullpath(&full, data, wd->path) < 0)
return false;
return !full || !git_path_contains(full, DOT_GIT);
}
static int checkout_queue_remove(checkout_data *data, const char *path)
{
char *copy = git_pool_strdup(&data->pool, path);
GIT_ERROR_CHECK_ALLOC(copy);
return git_vector_insert(&data->removes, copy);
}
/* note that this advances the iterator over the wd item */
static int checkout_action_wd_only(
checkout_data *data,
git_iterator *workdir,
const git_index_entry **wditem,
git_vector *pathspec)
{
int error = 0;
bool remove = false;
git_checkout_notify_t notify = GIT_CHECKOUT_NOTIFY_NONE;
const git_index_entry *wd = *wditem;
if (!git_pathspec__match(
pathspec, wd->path,
(data->strategy & GIT_CHECKOUT_DISABLE_PATHSPEC_MATCH) != 0,
git_iterator_ignore_case(workdir), NULL, NULL)) {
if (wd->mode == GIT_FILEMODE_TREE)
return git_iterator_advance_into(wditem, workdir);
else
return git_iterator_advance(wditem, workdir);
}
/* check if item is tracked in the index but not in the checkout diff */
if (data->index != NULL) {
size_t pos;
error = git_index__find_pos(
&pos, data->index, wd->path, 0, GIT_INDEX_STAGE_ANY);
if (wd->mode != GIT_FILEMODE_TREE) {
if (!error) { /* found by git_index__find_pos call */
notify = GIT_CHECKOUT_NOTIFY_DIRTY;
remove = ((data->strategy & GIT_CHECKOUT_FORCE) != 0);
} else if (error != GIT_ENOTFOUND)
return error;
else
error = 0; /* git_index__find_pos does not set error msg */
} else {
/* for tree entries, we have to see if there are any index
* entries that are contained inside that tree
*/
const git_index_entry *e = git_index_get_byindex(data->index, pos);
if (e != NULL && data->diff->pfxcomp(e->path, wd->path) == 0)
return git_iterator_advance_into(wditem, workdir);
}
}
if (notify != GIT_CHECKOUT_NOTIFY_NONE) {
/* if we found something in the index, notify and advance */
if ((error = checkout_notify(data, notify, NULL, wd)) != 0)
return error;
if (remove && wd_item_is_removable(data, wd))
error = checkout_queue_remove(data, wd->path);
if (!error)
error = git_iterator_advance(wditem, workdir);
} else {
/* untracked or ignored - can't know which until we advance through */
bool over = false, removable = wd_item_is_removable(data, wd);
git_iterator_status_t untracked_state;
/* copy the entry for issuing notification callback later */
git_index_entry saved_wd = *wd;
git_buf_sets(&data->tmp, wd->path);
saved_wd.path = data->tmp.ptr;
error = git_iterator_advance_over(
wditem, &untracked_state, workdir);
if (error == GIT_ITEROVER)
over = true;
else if (error < 0)
return error;
if (untracked_state == GIT_ITERATOR_STATUS_IGNORED) {
notify = GIT_CHECKOUT_NOTIFY_IGNORED;
remove = ((data->strategy & GIT_CHECKOUT_REMOVE_IGNORED) != 0);
} else {
notify = GIT_CHECKOUT_NOTIFY_UNTRACKED;
remove = ((data->strategy & GIT_CHECKOUT_REMOVE_UNTRACKED) != 0);
}
if ((error = checkout_notify(data, notify, NULL, &saved_wd)) != 0)
return error;
if (remove && removable)
error = checkout_queue_remove(data, saved_wd.path);
if (!error && over) /* restore ITEROVER if needed */
error = GIT_ITEROVER;
}
return error;
}
static bool submodule_is_config_only(
checkout_data *data,
const char *path)
{
git_submodule *sm = NULL;
unsigned int sm_loc = 0;
bool rval = false;
if (git_submodule_lookup(&sm, data->repo, path) < 0)
return true;
if (git_submodule_location(&sm_loc, sm) < 0 ||
sm_loc == GIT_SUBMODULE_STATUS_IN_CONFIG)
rval = true;
git_submodule_free(sm);
return rval;
}
static bool checkout_is_empty_dir(checkout_data *data, const char *path)
{
git_buf *fullpath;
if (checkout_target_fullpath(&fullpath, data, path) < 0)
return false;
return git_path_is_empty_dir(fullpath->ptr);
}
static int checkout_action_with_wd(
int *action,
checkout_data *data,
const git_diff_delta *delta,
git_iterator *workdir,
const git_index_entry *wd)
{
*action = CHECKOUT_ACTION__NONE;
switch (delta->status) {
case GIT_DELTA_UNMODIFIED: /* case 14/15 or 33 */
if (checkout_is_workdir_modified(data, &delta->old_file, &delta->new_file, wd)) {
GIT_ERROR_CHECK_ERROR(
checkout_notify(data, GIT_CHECKOUT_NOTIFY_DIRTY, delta, wd) );
*action = CHECKOUT_ACTION_IF(FORCE, UPDATE_BLOB, NONE);
}
break;
case GIT_DELTA_ADDED: /* case 3, 4 or 6 */
if (git_iterator_current_is_ignored(workdir))
*action = CHECKOUT_ACTION_IF(DONT_OVERWRITE_IGNORED, CONFLICT, UPDATE_BLOB);
else
*action = CHECKOUT_ACTION_IF(FORCE, UPDATE_BLOB, CONFLICT);
break;
case GIT_DELTA_DELETED: /* case 9 or 10 (or 26 but not really) */
if (checkout_is_workdir_modified(data, &delta->old_file, &delta->new_file, wd))
*action = CHECKOUT_ACTION_IF(FORCE, REMOVE, CONFLICT);
else
*action = CHECKOUT_ACTION_IF(SAFE, REMOVE, NONE);
break;
case GIT_DELTA_MODIFIED: /* case 16, 17, 18 (or 36 but not really) */
if (wd->mode != GIT_FILEMODE_COMMIT &&
checkout_is_workdir_modified(data, &delta->old_file, &delta->new_file, wd))
*action = CHECKOUT_ACTION_IF(FORCE, UPDATE_BLOB, CONFLICT);
else
*action = CHECKOUT_ACTION_IF(SAFE, UPDATE_BLOB, NONE);
break;
case GIT_DELTA_TYPECHANGE: /* case 22, 23, 29, 30 */
if (delta->old_file.mode == GIT_FILEMODE_TREE) {
if (wd->mode == GIT_FILEMODE_TREE)
/* either deleting items in old tree will delete the wd dir,
* or we'll get a conflict when we attempt blob update...
*/
*action = CHECKOUT_ACTION_IF(SAFE, UPDATE_BLOB, NONE);
else if (wd->mode == GIT_FILEMODE_COMMIT) {
/* workdir is possibly a "phantom" submodule - treat as a
* tree if the only submodule info came from the config
*/
if (submodule_is_config_only(data, wd->path))
*action = CHECKOUT_ACTION_IF(SAFE, UPDATE_BLOB, NONE);
else
*action = CHECKOUT_ACTION_IF(FORCE, REMOVE_AND_UPDATE, CONFLICT);
} else
*action = CHECKOUT_ACTION_IF(FORCE, REMOVE, CONFLICT);
}
else if (checkout_is_workdir_modified(data, &delta->old_file, &delta->new_file, wd))
*action = CHECKOUT_ACTION_IF(FORCE, REMOVE_AND_UPDATE, CONFLICT);
else
*action = CHECKOUT_ACTION_IF(SAFE, REMOVE_AND_UPDATE, NONE);
/* don't update if the typechange is to a tree */
if (delta->new_file.mode == GIT_FILEMODE_TREE)
*action = (*action & ~CHECKOUT_ACTION__UPDATE_BLOB);
break;
default: /* impossible */
break;
}
return checkout_action_common(action, data, delta, wd);
}
static int checkout_action_with_wd_blocker(
int *action,
checkout_data *data,
const git_diff_delta *delta,
const git_index_entry *wd)
{
*action = CHECKOUT_ACTION__NONE;
switch (delta->status) {
case GIT_DELTA_UNMODIFIED:
/* should show delta as dirty / deleted */
GIT_ERROR_CHECK_ERROR(
checkout_notify(data, GIT_CHECKOUT_NOTIFY_DIRTY, delta, wd) );
*action = CHECKOUT_ACTION_IF(FORCE, REMOVE_AND_UPDATE, NONE);
break;
case GIT_DELTA_ADDED:
case GIT_DELTA_MODIFIED:
*action = CHECKOUT_ACTION_IF(FORCE, REMOVE_AND_UPDATE, CONFLICT);
break;
case GIT_DELTA_DELETED:
*action = CHECKOUT_ACTION_IF(FORCE, REMOVE, CONFLICT);
break;
case GIT_DELTA_TYPECHANGE:
/* not 100% certain about this... */
*action = CHECKOUT_ACTION_IF(FORCE, REMOVE_AND_UPDATE, CONFLICT);
break;
default: /* impossible */
break;
}
return checkout_action_common(action, data, delta, wd);
}
static int checkout_action_with_wd_dir(
int *action,
checkout_data *data,
const git_diff_delta *delta,
git_iterator *workdir,
const git_index_entry *wd)
{
*action = CHECKOUT_ACTION__NONE;
switch (delta->status) {
case GIT_DELTA_UNMODIFIED: /* case 19 or 24 (or 34 but not really) */
GIT_ERROR_CHECK_ERROR(
checkout_notify(data, GIT_CHECKOUT_NOTIFY_DIRTY, delta, NULL));
GIT_ERROR_CHECK_ERROR(
checkout_notify(data, GIT_CHECKOUT_NOTIFY_UNTRACKED, NULL, wd));
*action = CHECKOUT_ACTION_IF(FORCE, REMOVE_AND_UPDATE, NONE);
break;
case GIT_DELTA_ADDED:/* case 4 (and 7 for dir) */
case GIT_DELTA_MODIFIED: /* case 20 (or 37 but not really) */
if (delta->old_file.mode == GIT_FILEMODE_COMMIT)
/* expected submodule (and maybe found one) */;
else if (delta->new_file.mode != GIT_FILEMODE_TREE)
*action = git_iterator_current_is_ignored(workdir) ?
CHECKOUT_ACTION_IF(DONT_OVERWRITE_IGNORED, CONFLICT, REMOVE_AND_UPDATE) :
CHECKOUT_ACTION_IF(FORCE, REMOVE_AND_UPDATE, CONFLICT);
break;
case GIT_DELTA_DELETED: /* case 11 (and 27 for dir) */
if (delta->old_file.mode != GIT_FILEMODE_TREE)
GIT_ERROR_CHECK_ERROR(
checkout_notify(data, GIT_CHECKOUT_NOTIFY_UNTRACKED, NULL, wd));
break;
case GIT_DELTA_TYPECHANGE: /* case 24 or 31 */
if (delta->old_file.mode == GIT_FILEMODE_TREE) {
/* For typechange from dir, remove dir and add blob, but it is
* not safe to remove dir if it contains modified files.
* However, safely removing child files will remove the parent
* directory if is it left empty, so we can defer removing the
* dir and it will succeed if no children are left.
*/
*action = CHECKOUT_ACTION_IF(SAFE, UPDATE_BLOB, NONE);
}
else if (delta->new_file.mode != GIT_FILEMODE_TREE)
/* For typechange to dir, dir is already created so no action */
*action = CHECKOUT_ACTION_IF(FORCE, REMOVE_AND_UPDATE, CONFLICT);
break;
default: /* impossible */
break;
}
return checkout_action_common(action, data, delta, wd);
}
static int checkout_action_with_wd_dir_empty(
int *action,
checkout_data *data,
const git_diff_delta *delta)
{
int error = checkout_action_no_wd(action, data, delta);
/* We can always safely remove an empty directory. */
if (error == 0 && *action != CHECKOUT_ACTION__NONE)
*action |= CHECKOUT_ACTION__REMOVE;
return error;
}
static int checkout_action(
int *action,
checkout_data *data,
git_diff_delta *delta,
git_iterator *workdir,
const git_index_entry **wditem,
git_vector *pathspec)
{
int cmp = -1, error;
int (*strcomp)(const char *, const char *) = data->diff->strcomp;
int (*pfxcomp)(const char *str, const char *pfx) = data->diff->pfxcomp;
int (*advance)(const git_index_entry **, git_iterator *) = NULL;
/* move workdir iterator to follow along with deltas */
while (1) {
const git_index_entry *wd = *wditem;
if (!wd)
return checkout_action_no_wd(action, data, delta);
cmp = strcomp(wd->path, delta->old_file.path);
/* 1. wd before delta ("a/a" before "a/b")
* 2. wd prefixes delta & should expand ("a/" before "a/b")
* 3. wd prefixes delta & cannot expand ("a/b" before "a/b/c")
* 4. wd equals delta ("a/b" and "a/b")
* 5. wd after delta & delta prefixes wd ("a/b/c" after "a/b/" or "a/b")
* 6. wd after delta ("a/c" after "a/b")
*/
if (cmp < 0) {
cmp = pfxcomp(delta->old_file.path, wd->path);
if (cmp == 0) {
if (wd->mode == GIT_FILEMODE_TREE) {
/* case 2 - entry prefixed by workdir tree */
error = git_iterator_advance_into(wditem, workdir);
if (error < 0 && error != GIT_ITEROVER)
goto done;
continue;
}
/* case 3 maybe - wd contains non-dir where dir expected */
if (delta->old_file.path[strlen(wd->path)] == '/') {
error = checkout_action_with_wd_blocker(
action, data, delta, wd);
advance = git_iterator_advance;
goto done;
}
}
/* case 1 - handle wd item (if it matches pathspec) */
error = checkout_action_wd_only(data, workdir, wditem, pathspec);
if (error && error != GIT_ITEROVER)
goto done;
continue;
}
if (cmp == 0) {
/* case 4 */
error = checkout_action_with_wd(action, data, delta, workdir, wd);
advance = git_iterator_advance;
goto done;
}
cmp = pfxcomp(wd->path, delta->old_file.path);
if (cmp == 0) { /* case 5 */
if (wd->path[strlen(delta->old_file.path)] != '/')
return checkout_action_no_wd(action, data, delta);
if (delta->status == GIT_DELTA_TYPECHANGE) {
if (delta->old_file.mode == GIT_FILEMODE_TREE) {
error = checkout_action_with_wd(action, data, delta, workdir, wd);
advance = git_iterator_advance_into;
goto done;
}
if (delta->new_file.mode == GIT_FILEMODE_TREE ||
delta->new_file.mode == GIT_FILEMODE_COMMIT ||
delta->old_file.mode == GIT_FILEMODE_COMMIT)
{
error = checkout_action_with_wd(action, data, delta, workdir, wd);
advance = git_iterator_advance;
goto done;
}
}
return checkout_is_empty_dir(data, wd->path) ?
checkout_action_with_wd_dir_empty(action, data, delta) :
checkout_action_with_wd_dir(action, data, delta, workdir, wd);
}
/* case 6 - wd is after delta */
return checkout_action_no_wd(action, data, delta);
}
done:
if (!error && advance != NULL &&
(error = advance(wditem, workdir)) < 0) {
*wditem = NULL;
if (error == GIT_ITEROVER)
error = 0;
}
return error;
}
static int checkout_remaining_wd_items(
checkout_data *data,
git_iterator *workdir,
const git_index_entry *wd,
git_vector *spec)
{
int error = 0;
while (wd && !error)
error = checkout_action_wd_only(data, workdir, &wd, spec);
if (error == GIT_ITEROVER)
error = 0;
return error;
}
GIT_INLINE(int) checkout_idxentry_cmp(
const git_index_entry *a,
const git_index_entry *b)
{
if (!a && !b)
return 0;
else if (!a && b)
return -1;
else if(a && !b)
return 1;
else
return strcmp(a->path, b->path);
}
static int checkout_conflictdata_cmp(const void *a, const void *b)
{
const checkout_conflictdata *ca = a;
const checkout_conflictdata *cb = b;
int diff;
if ((diff = checkout_idxentry_cmp(ca->ancestor, cb->ancestor)) == 0 &&
(diff = checkout_idxentry_cmp(ca->ours, cb->theirs)) == 0)
diff = checkout_idxentry_cmp(ca->theirs, cb->theirs);
return diff;
}
static int checkout_conflictdata_empty(
const git_vector *conflicts, size_t idx, void *payload)
{
checkout_conflictdata *conflict;
GIT_UNUSED(payload);
if ((conflict = git_vector_get(conflicts, idx)) == NULL)
return -1;
if (conflict->ancestor || conflict->ours || conflict->theirs)
return 0;
git__free(conflict);
return 1;
}
GIT_INLINE(bool) conflict_pathspec_match(
checkout_data *data,
git_iterator *workdir,
git_vector *pathspec,
const git_index_entry *ancestor,
const git_index_entry *ours,
const git_index_entry *theirs)
{
/* if the pathspec matches ours *or* theirs, proceed */
if (ours && git_pathspec__match(pathspec, ours->path,
(data->strategy & GIT_CHECKOUT_DISABLE_PATHSPEC_MATCH) != 0,
git_iterator_ignore_case(workdir), NULL, NULL))
return true;
if (theirs && git_pathspec__match(pathspec, theirs->path,
(data->strategy & GIT_CHECKOUT_DISABLE_PATHSPEC_MATCH) != 0,
git_iterator_ignore_case(workdir), NULL, NULL))
return true;
if (ancestor && git_pathspec__match(pathspec, ancestor->path,
(data->strategy & GIT_CHECKOUT_DISABLE_PATHSPEC_MATCH) != 0,
git_iterator_ignore_case(workdir), NULL, NULL))
return true;
return false;
}
GIT_INLINE(int) checkout_conflict_detect_submodule(checkout_conflictdata *conflict)
{
conflict->submodule = ((conflict->ancestor && S_ISGITLINK(conflict->ancestor->mode)) ||
(conflict->ours && S_ISGITLINK(conflict->ours->mode)) ||
(conflict->theirs && S_ISGITLINK(conflict->theirs->mode)));
return 0;
}
GIT_INLINE(int) checkout_conflict_detect_binary(git_repository *repo, checkout_conflictdata *conflict)
{
git_blob *ancestor_blob = NULL, *our_blob = NULL, *their_blob = NULL;
int error = 0;
if (conflict->submodule)
return 0;
if (conflict->ancestor) {
if ((error = git_blob_lookup(&ancestor_blob, repo, &conflict->ancestor->id)) < 0)
goto done;
conflict->binary = git_blob_is_binary(ancestor_blob);
}
if (!conflict->binary && conflict->ours) {
if ((error = git_blob_lookup(&our_blob, repo, &conflict->ours->id)) < 0)
goto done;
conflict->binary = git_blob_is_binary(our_blob);
}
if (!conflict->binary && conflict->theirs) {
if ((error = git_blob_lookup(&their_blob, repo, &conflict->theirs->id)) < 0)
goto done;
conflict->binary = git_blob_is_binary(their_blob);
}
done:
git_blob_free(ancestor_blob);
git_blob_free(our_blob);
git_blob_free(their_blob);
return error;
}
static int checkout_conflict_append_update(
const git_index_entry *ancestor,
const git_index_entry *ours,
const git_index_entry *theirs,
void *payload)
{
checkout_data *data = payload;
checkout_conflictdata *conflict;
int error;
conflict = git__calloc(1, sizeof(checkout_conflictdata));
GIT_ERROR_CHECK_ALLOC(conflict);
conflict->ancestor = ancestor;
conflict->ours = ours;
conflict->theirs = theirs;
if ((error = checkout_conflict_detect_submodule(conflict)) < 0 ||
(error = checkout_conflict_detect_binary(data->repo, conflict)) < 0)
{
git__free(conflict);
return error;
}
if (git_vector_insert(&data->update_conflicts, conflict))
return -1;
return 0;
}
static int checkout_conflicts_foreach(
checkout_data *data,
git_index *index,
git_iterator *workdir,
git_vector *pathspec,
int (*cb)(const git_index_entry *, const git_index_entry *, const git_index_entry *, void *),
void *payload)
{
git_index_conflict_iterator *iterator = NULL;
const git_index_entry *ancestor, *ours, *theirs;
int error = 0;
if ((error = git_index_conflict_iterator_new(&iterator, index)) < 0)
goto done;
/* Collect the conflicts */
while ((error = git_index_conflict_next(&ancestor, &ours, &theirs, iterator)) == 0) {
if (!conflict_pathspec_match(data, workdir, pathspec, ancestor, ours, theirs))
continue;
if ((error = cb(ancestor, ours, theirs, payload)) < 0)
goto done;
}
if (error == GIT_ITEROVER)
error = 0;
done:
git_index_conflict_iterator_free(iterator);
return error;
}
static int checkout_conflicts_load(checkout_data *data, git_iterator *workdir, git_vector *pathspec)
{
git_index *index;
/* Only write conficts from sources that have them: indexes. */
if ((index = git_iterator_index(data->target)) == NULL)
return 0;
data->update_conflicts._cmp = checkout_conflictdata_cmp;
if (checkout_conflicts_foreach(data, index, workdir, pathspec, checkout_conflict_append_update, data) < 0)
return -1;
/* Collect the REUC and NAME entries */
data->update_reuc = &index->reuc;
data->update_names = &index->names;
return 0;
}
GIT_INLINE(int) checkout_conflicts_cmp_entry(
const char *path,
const git_index_entry *entry)
{
return strcmp((const char *)path, entry->path);
}
static int checkout_conflicts_cmp_ancestor(const void *p, const void *c)
{
const char *path = p;
const checkout_conflictdata *conflict = c;
if (!conflict->ancestor)
return 1;
return checkout_conflicts_cmp_entry(path, conflict->ancestor);
}
static checkout_conflictdata *checkout_conflicts_search_ancestor(
checkout_data *data,
const char *path)
{
size_t pos;
if (git_vector_bsearch2(&pos, &data->update_conflicts, checkout_conflicts_cmp_ancestor, path) < 0)
return NULL;
return git_vector_get(&data->update_conflicts, pos);
}
static checkout_conflictdata *checkout_conflicts_search_branch(
checkout_data *data,
const char *path)
{
checkout_conflictdata *conflict;
size_t i;
git_vector_foreach(&data->update_conflicts, i, conflict) {
int cmp = -1;
if (conflict->ancestor)
break;
if (conflict->ours)
cmp = checkout_conflicts_cmp_entry(path, conflict->ours);
else if (conflict->theirs)
cmp = checkout_conflicts_cmp_entry(path, conflict->theirs);
if (cmp == 0)
return conflict;
}
return NULL;
}
static int checkout_conflicts_load_byname_entry(
checkout_conflictdata **ancestor_out,
checkout_conflictdata **ours_out,
checkout_conflictdata **theirs_out,
checkout_data *data,
const git_index_name_entry *name_entry)
{
checkout_conflictdata *ancestor, *ours = NULL, *theirs = NULL;
int error = 0;
*ancestor_out = NULL;
*ours_out = NULL;
*theirs_out = NULL;
if (!name_entry->ancestor) {
git_error_set(GIT_ERROR_INDEX, "a NAME entry exists without an ancestor");
error = -1;
goto done;
}
if (!name_entry->ours && !name_entry->theirs) {
git_error_set(GIT_ERROR_INDEX, "a NAME entry exists without an ours or theirs");
error = -1;
goto done;
}
if ((ancestor = checkout_conflicts_search_ancestor(data,
name_entry->ancestor)) == NULL) {
git_error_set(GIT_ERROR_INDEX,
"a NAME entry referenced ancestor entry '%s' which does not exist in the main index",
name_entry->ancestor);
error = -1;
goto done;
}
if (name_entry->ours) {
if (strcmp(name_entry->ancestor, name_entry->ours) == 0)
ours = ancestor;
else if ((ours = checkout_conflicts_search_branch(data, name_entry->ours)) == NULL ||
ours->ours == NULL) {
git_error_set(GIT_ERROR_INDEX,
"a NAME entry referenced our entry '%s' which does not exist in the main index",
name_entry->ours);
error = -1;
goto done;
}
}
if (name_entry->theirs) {
if (strcmp(name_entry->ancestor, name_entry->theirs) == 0)
theirs = ancestor;
else if (name_entry->ours && strcmp(name_entry->ours, name_entry->theirs) == 0)
theirs = ours;
else if ((theirs = checkout_conflicts_search_branch(data, name_entry->theirs)) == NULL ||
theirs->theirs == NULL) {
git_error_set(GIT_ERROR_INDEX,
"a NAME entry referenced their entry '%s' which does not exist in the main index",
name_entry->theirs);
error = -1;
goto done;
}
}
*ancestor_out = ancestor;
*ours_out = ours;
*theirs_out = theirs;
done:
return error;
}
static int checkout_conflicts_coalesce_renames(
checkout_data *data)
{
git_index *index;
const git_index_name_entry *name_entry;
checkout_conflictdata *ancestor_conflict, *our_conflict, *their_conflict;
size_t i, names;
int error = 0;
if ((index = git_iterator_index(data->target)) == NULL)
return 0;
/* Juggle entries based on renames */
names = git_index_name_entrycount(index);
for (i = 0; i < names; i++) {
name_entry = git_index_name_get_byindex(index, i);
if ((error = checkout_conflicts_load_byname_entry(
&ancestor_conflict, &our_conflict, &their_conflict,
data, name_entry)) < 0)
goto done;
if (our_conflict && our_conflict != ancestor_conflict) {
ancestor_conflict->ours = our_conflict->ours;
our_conflict->ours = NULL;
if (our_conflict->theirs)
our_conflict->name_collision = 1;
if (our_conflict->name_collision)
ancestor_conflict->name_collision = 1;
}
if (their_conflict && their_conflict != ancestor_conflict) {
ancestor_conflict->theirs = their_conflict->theirs;
their_conflict->theirs = NULL;
if (their_conflict->ours)
their_conflict->name_collision = 1;
if (their_conflict->name_collision)
ancestor_conflict->name_collision = 1;
}
if (our_conflict && our_conflict != ancestor_conflict &&
their_conflict && their_conflict != ancestor_conflict)
ancestor_conflict->one_to_two = 1;
}
git_vector_remove_matching(
&data->update_conflicts, checkout_conflictdata_empty, NULL);
done:
return error;
}
static int checkout_conflicts_mark_directoryfile(
checkout_data *data)
{
git_index *index;
checkout_conflictdata *conflict;
const git_index_entry *entry;
size_t i, j, len;
const char *path;
int prefixed, error = 0;
if ((index = git_iterator_index(data->target)) == NULL)
return 0;
len = git_index_entrycount(index);
/* Find d/f conflicts */
git_vector_foreach(&data->update_conflicts, i, conflict) {
if ((conflict->ours && conflict->theirs) ||
(!conflict->ours && !conflict->theirs))
continue;
path = conflict->ours ?
conflict->ours->path : conflict->theirs->path;
if ((error = git_index_find(&j, index, path)) < 0) {
if (error == GIT_ENOTFOUND)
git_error_set(GIT_ERROR_INDEX,
"index inconsistency, could not find entry for expected conflict '%s'", path);
goto done;
}
for (; j < len; j++) {
if ((entry = git_index_get_byindex(index, j)) == NULL) {
git_error_set(GIT_ERROR_INDEX,
"index inconsistency, truncated index while loading expected conflict '%s'", path);
error = -1;
goto done;
}
prefixed = git_path_equal_or_prefixed(path, entry->path, NULL);
if (prefixed == GIT_PATH_EQUAL)
continue;
if (prefixed == GIT_PATH_PREFIX)
conflict->directoryfile = 1;
break;
}
}
done:
return error;
}
static int checkout_get_update_conflicts(
checkout_data *data,
git_iterator *workdir,
git_vector *pathspec)
{
int error = 0;
if (data->strategy & GIT_CHECKOUT_SKIP_UNMERGED)
return 0;
if ((error = checkout_conflicts_load(data, workdir, pathspec)) < 0 ||
(error = checkout_conflicts_coalesce_renames(data)) < 0 ||
(error = checkout_conflicts_mark_directoryfile(data)) < 0)
goto done;
done:
return error;
}
static int checkout_conflict_append_remove(
const git_index_entry *ancestor,
const git_index_entry *ours,
const git_index_entry *theirs,
void *payload)
{
checkout_data *data = payload;
const char *name;
GIT_ASSERT_ARG(ancestor || ours || theirs);
if (ancestor)
name = git__strdup(ancestor->path);
else if (ours)
name = git__strdup(ours->path);
else if (theirs)
name = git__strdup(theirs->path);
else
abort();
GIT_ERROR_CHECK_ALLOC(name);
return git_vector_insert(&data->remove_conflicts, (char *)name);
}
static int checkout_get_remove_conflicts(
checkout_data *data,
git_iterator *workdir,
git_vector *pathspec)
{
if ((data->strategy & GIT_CHECKOUT_DONT_UPDATE_INDEX) != 0)
return 0;
return checkout_conflicts_foreach(data, data->index, workdir, pathspec, checkout_conflict_append_remove, data);
}
static int checkout_verify_paths(
git_repository *repo,
int action,
git_diff_delta *delta)
{
unsigned int flags = GIT_PATH_REJECT_WORKDIR_DEFAULTS;
if (action & CHECKOUT_ACTION__REMOVE) {
if (!git_path_validate(repo, delta->old_file.path, delta->old_file.mode, flags)) {
git_error_set(GIT_ERROR_CHECKOUT, "cannot remove invalid path '%s'", delta->old_file.path);
return -1;
}
}
if (action & ~CHECKOUT_ACTION__REMOVE) {
if (!git_path_validate(repo, delta->new_file.path, delta->new_file.mode, flags)) {
git_error_set(GIT_ERROR_CHECKOUT, "cannot checkout to invalid path '%s'", delta->new_file.path);
return -1;
}
}
return 0;
}
static int checkout_get_actions(
uint32_t **actions_ptr,
size_t **counts_ptr,
checkout_data *data,
git_iterator *workdir)
{
int error = 0, act;
const git_index_entry *wditem;
git_vector pathspec = GIT_VECTOR_INIT, *deltas;
git_pool pathpool;
git_diff_delta *delta;
size_t i, *counts = NULL;
uint32_t *actions = NULL;
if (git_pool_init(&pathpool, 1) < 0)
return -1;
if (data->opts.paths.count > 0 &&
git_pathspec__vinit(&pathspec, &data->opts.paths, &pathpool) < 0)
return -1;
if ((error = git_iterator_current(&wditem, workdir)) < 0 &&
error != GIT_ITEROVER)
goto fail;
deltas = &data->diff->deltas;
*counts_ptr = counts = git__calloc(CHECKOUT_ACTION__MAX+1, sizeof(size_t));
*actions_ptr = actions = git__calloc(
deltas->length ? deltas->length : 1, sizeof(uint32_t));
if (!counts || !actions) {
error = -1;
goto fail;
}
git_vector_foreach(deltas, i, delta) {
if ((error = checkout_action(&act, data, delta, workdir, &wditem, &pathspec)) == 0)
error = checkout_verify_paths(data->repo, act, delta);
if (error != 0)
goto fail;
actions[i] = act;
if (act & CHECKOUT_ACTION__REMOVE)
counts[CHECKOUT_ACTION__REMOVE]++;
if (act & CHECKOUT_ACTION__UPDATE_BLOB)
counts[CHECKOUT_ACTION__UPDATE_BLOB]++;
if (act & CHECKOUT_ACTION__UPDATE_SUBMODULE)
counts[CHECKOUT_ACTION__UPDATE_SUBMODULE]++;
if (act & CHECKOUT_ACTION__CONFLICT)
counts[CHECKOUT_ACTION__CONFLICT]++;
}
error = checkout_remaining_wd_items(data, workdir, wditem, &pathspec);
if (error)
goto fail;
counts[CHECKOUT_ACTION__REMOVE] += data->removes.length;
if (counts[CHECKOUT_ACTION__CONFLICT] > 0 &&
(data->strategy & GIT_CHECKOUT_ALLOW_CONFLICTS) == 0) {
git_error_set(GIT_ERROR_CHECKOUT, "%"PRIuZ" %s checkout",
counts[CHECKOUT_ACTION__CONFLICT],
counts[CHECKOUT_ACTION__CONFLICT] == 1 ?
"conflict prevents" : "conflicts prevent");
error = GIT_ECONFLICT;
goto fail;
}
if ((error = checkout_get_remove_conflicts(data, workdir, &pathspec)) < 0 ||
(error = checkout_get_update_conflicts(data, workdir, &pathspec)) < 0)
goto fail;
counts[CHECKOUT_ACTION__REMOVE_CONFLICT] = git_vector_length(&data->remove_conflicts);
counts[CHECKOUT_ACTION__UPDATE_CONFLICT] = git_vector_length(&data->update_conflicts);
git_pathspec__vfree(&pathspec);
git_pool_clear(&pathpool);
return 0;
fail:
*counts_ptr = NULL;
git__free(counts);
*actions_ptr = NULL;
git__free(actions);
git_pathspec__vfree(&pathspec);
git_pool_clear(&pathpool);
return error;
}
static bool should_remove_existing(checkout_data *data)
{
int ignorecase;
if (git_repository__configmap_lookup(&ignorecase, data->repo, GIT_CONFIGMAP_IGNORECASE) < 0) {
ignorecase = 0;
}
return (ignorecase &&
(data->strategy & GIT_CHECKOUT_DONT_REMOVE_EXISTING) == 0);
}
#define MKDIR_NORMAL \
GIT_MKDIR_PATH | GIT_MKDIR_VERIFY_DIR
#define MKDIR_REMOVE_EXISTING \
MKDIR_NORMAL | GIT_MKDIR_REMOVE_FILES | GIT_MKDIR_REMOVE_SYMLINKS
static int checkout_mkdir(
checkout_data *data,
const char *path,
const char *base,
mode_t mode,
unsigned int flags)
{
struct git_futils_mkdir_options mkdir_opts = {0};
int error;
mkdir_opts.dir_map = data->mkdir_map;
mkdir_opts.pool = &data->pool;
error = git_futils_mkdir_relative(
path, base, mode, flags, &mkdir_opts);
data->perfdata.mkdir_calls += mkdir_opts.perfdata.mkdir_calls;
data->perfdata.stat_calls += mkdir_opts.perfdata.stat_calls;
data->perfdata.chmod_calls += mkdir_opts.perfdata.chmod_calls;
return error;
}
static int mkpath2file(
checkout_data *data, const char *path, unsigned int mode)
{
struct stat st;
bool remove_existing = should_remove_existing(data);
unsigned int flags =
(remove_existing ? MKDIR_REMOVE_EXISTING : MKDIR_NORMAL) |
GIT_MKDIR_SKIP_LAST;
int error;
if ((error = checkout_mkdir(
data, path, data->opts.target_directory, mode, flags)) < 0)
return error;
if (remove_existing) {
data->perfdata.stat_calls++;
if (p_lstat(path, &st) == 0) {
/* Some file, symlink or folder already exists at this name.
* We would have removed it in remove_the_old unless we're on
* a case inensitive filesystem (or the user has asked us not
* to). Remove the similarly named file to write the new.
*/
error = git_futils_rmdir_r(path, NULL, GIT_RMDIR_REMOVE_FILES);
} else if (errno != ENOENT) {
git_error_set(GIT_ERROR_OS, "failed to stat '%s'", path);
return GIT_EEXISTS;
} else {
git_error_clear();
}
}
return error;
}
struct checkout_stream {
git_writestream base;
const char *path;
int fd;
int open;
};
static int checkout_stream_write(
git_writestream *s, const char *buffer, size_t len)
{
struct checkout_stream *stream = (struct checkout_stream *)s;
int ret;
if ((ret = p_write(stream->fd, buffer, len)) < 0)
git_error_set(GIT_ERROR_OS, "could not write to '%s'", stream->path);
return ret;
}
static int checkout_stream_close(git_writestream *s)
{
struct checkout_stream *stream = (struct checkout_stream *)s;
GIT_ASSERT_ARG(stream);
GIT_ASSERT_ARG(stream->open);
stream->open = 0;
return p_close(stream->fd);
}
static void checkout_stream_free(git_writestream *s)
{
GIT_UNUSED(s);
}
static int blob_content_to_file(
checkout_data *data,
struct stat *st,
git_blob *blob,
const char *path,
const char *hint_path,
mode_t entry_filemode)
{
int flags = data->opts.file_open_flags;
mode_t file_mode = data->opts.file_mode ?
data->opts.file_mode : entry_filemode;
git_filter_session filter_session = GIT_FILTER_SESSION_INIT;
struct checkout_stream writer;
mode_t mode;
git_filter_list *fl = NULL;
int fd;
int error = 0;
GIT_ASSERT(hint_path != NULL);
if ((error = mkpath2file(data, path, data->opts.dir_mode)) < 0)
return error;
if (flags <= 0)
flags = O_CREAT | O_TRUNC | O_WRONLY;
if (!(mode = file_mode))
mode = GIT_FILEMODE_BLOB;
if ((fd = p_open(path, flags, mode)) < 0) {
git_error_set(GIT_ERROR_OS, "could not open '%s' for writing", path);
return fd;
}
filter_session.attr_session = &data->attr_session;
filter_session.temp_buf = &data->tmp;
if (!data->opts.disable_filters &&
(error = git_filter_list__load(
&fl, data->repo, blob, hint_path,
GIT_FILTER_TO_WORKTREE, &filter_session))) {
p_close(fd);
return error;
}
/* setup the writer */
memset(&writer, 0, sizeof(struct checkout_stream));
writer.base.write = checkout_stream_write;
writer.base.close = checkout_stream_close;
writer.base.free = checkout_stream_free;
writer.path = path;
writer.fd = fd;
writer.open = 1;
error = git_filter_list_stream_blob(fl, blob, &writer.base);
GIT_ASSERT(writer.open == 0);
git_filter_list_free(fl);
if (error < 0)
return error;
if (st) {
data->perfdata.stat_calls++;
if ((error = p_stat(path, st)) < 0) {
git_error_set(GIT_ERROR_OS, "failed to stat '%s'", path);
return error;
}
st->st_mode = entry_filemode;
}
return 0;
}
static int blob_content_to_link(
checkout_data *data,
struct stat *st,
git_blob *blob,
const char *path)
{
git_buf linktarget = GIT_BUF_INIT;
int error;
if ((error = mkpath2file(data, path, data->opts.dir_mode)) < 0)
return error;
if ((error = git_blob__getbuf(&linktarget, blob)) < 0)
return error;
if (data->can_symlink) {
if ((error = p_symlink(git_buf_cstr(&linktarget), path)) < 0)
git_error_set(GIT_ERROR_OS, "could not create symlink %s", path);
} else {
error = git_futils_fake_symlink(git_buf_cstr(&linktarget), path);
}
if (!error) {
data->perfdata.stat_calls++;
if ((error = p_lstat(path, st)) < 0)
git_error_set(GIT_ERROR_CHECKOUT, "could not stat symlink %s", path);
st->st_mode = GIT_FILEMODE_LINK;
}
git_buf_dispose(&linktarget);
return error;
}
static int checkout_update_index(
checkout_data *data,
const git_diff_file *file,
struct stat *st)
{
git_index_entry entry;
if (!data->index)
return 0;
memset(&entry, 0, sizeof(entry));
entry.path = (char *)file->path; /* cast to prevent warning */
git_index_entry__init_from_stat(&entry, st, true);
git_oid_cpy(&entry.id, &file->id);
return git_index_add(data->index, &entry);
}
static int checkout_submodule_update_index(
checkout_data *data,
const git_diff_file *file)
{
git_buf *fullpath;
struct stat st;
/* update the index unless prevented */
if ((data->strategy & GIT_CHECKOUT_DONT_UPDATE_INDEX) != 0)
return 0;
if (checkout_target_fullpath(&fullpath, data, file->path) < 0)
return -1;
data->perfdata.stat_calls++;
if (p_stat(fullpath->ptr, &st) < 0) {
git_error_set(
GIT_ERROR_CHECKOUT, "could not stat submodule %s\n", file->path);
return GIT_ENOTFOUND;
}
st.st_mode = GIT_FILEMODE_COMMIT;
return checkout_update_index(data, file, &st);
}
static int checkout_submodule(
checkout_data *data,
const git_diff_file *file)
{
bool remove_existing = should_remove_existing(data);
int error = 0;
/* Until submodules are supported, UPDATE_ONLY means do nothing here */
if ((data->strategy & GIT_CHECKOUT_UPDATE_ONLY) != 0)
return 0;
if ((error = checkout_mkdir(
data,
file->path, data->opts.target_directory, data->opts.dir_mode,
remove_existing ? MKDIR_REMOVE_EXISTING : MKDIR_NORMAL)) < 0)
return error;
if ((error = git_submodule_lookup(NULL, data->repo, file->path)) < 0) {
/* I've observed repos with submodules in the tree that do not
* have a .gitmodules - core Git just makes an empty directory
*/
if (error == GIT_ENOTFOUND) {
git_error_clear();
return checkout_submodule_update_index(data, file);
}
return error;
}
/* TODO: Support checkout_strategy options. Two circumstances:
* 1 - submodule already checked out, but we need to move the HEAD
* to the new OID, or
* 2 - submodule not checked out and we should recursively check it out
*
* Checkout will not execute a pull on the submodule, but a clone
* command should probably be able to. Do we need a submodule callback?
*/
return checkout_submodule_update_index(data, file);
}
static void report_progress(
checkout_data *data,
const char *path)
{
if (data->opts.progress_cb)
data->opts.progress_cb(
path, data->completed_steps, data->total_steps,
data->opts.progress_payload);
}
static int checkout_safe_for_update_only(
checkout_data *data, const char *path, mode_t expected_mode)
{
struct stat st;
data->perfdata.stat_calls++;
if (p_lstat(path, &st) < 0) {
/* if doesn't exist, then no error and no update */
if (errno == ENOENT || errno == ENOTDIR)
return 0;
/* otherwise, stat error and no update */
git_error_set(GIT_ERROR_OS, "failed to stat '%s'", path);
return -1;
}
/* only safe for update if this is the same type of file */
if ((st.st_mode & ~0777) == (expected_mode & ~0777))
return 1;
return 0;
}
static int checkout_write_content(
checkout_data *data,
const git_oid *oid,
const char *full_path,
const char *hint_path,
unsigned int mode,
struct stat *st)
{
int error = 0;
git_blob *blob;
if ((error = git_blob_lookup(&blob, data->repo, oid)) < 0)
return error;
if (S_ISLNK(mode))
error = blob_content_to_link(data, st, blob, full_path);
else
error = blob_content_to_file(data, st, blob, full_path, hint_path, mode);
git_blob_free(blob);
/* if we try to create the blob and an existing directory blocks it from
* being written, then there must have been a typechange conflict in a
* parent directory - suppress the error and try to continue.
*/
if ((data->strategy & GIT_CHECKOUT_ALLOW_CONFLICTS) != 0 &&
(error == GIT_ENOTFOUND || error == GIT_EEXISTS))
{
git_error_clear();
error = 0;
}
return error;
}
static int checkout_blob(
checkout_data *data,
const git_diff_file *file)
{
git_buf *fullpath;
struct stat st;
int error = 0;
if (checkout_target_fullpath(&fullpath, data, file->path) < 0)
return -1;
if ((data->strategy & GIT_CHECKOUT_UPDATE_ONLY) != 0) {
int rval = checkout_safe_for_update_only(
data, fullpath->ptr, file->mode);
if (rval <= 0)
return rval;
}
error = checkout_write_content(
data, &file->id, fullpath->ptr, file->path, file->mode, &st);
/* update the index unless prevented */
if (!error && (data->strategy & GIT_CHECKOUT_DONT_UPDATE_INDEX) == 0)
error = checkout_update_index(data, file, &st);
/* update the submodule data if this was a new .gitmodules file */
if (!error && strcmp(file->path, ".gitmodules") == 0)
data->reload_submodules = true;
return error;
}
static int checkout_remove_the_old(
unsigned int *actions,
checkout_data *data)
{
int error = 0;
git_diff_delta *delta;
const char *str;
size_t i;
git_buf *fullpath;
uint32_t flg = GIT_RMDIR_EMPTY_PARENTS |
GIT_RMDIR_REMOVE_FILES | GIT_RMDIR_REMOVE_BLOCKERS;
if (data->opts.checkout_strategy & GIT_CHECKOUT_SKIP_LOCKED_DIRECTORIES)
flg |= GIT_RMDIR_SKIP_NONEMPTY;
if (checkout_target_fullpath(&fullpath, data, NULL) < 0)
return -1;
git_vector_foreach(&data->diff->deltas, i, delta) {
if (actions[i] & CHECKOUT_ACTION__REMOVE) {
error = git_futils_rmdir_r(
delta->old_file.path, fullpath->ptr, flg);
if (error < 0)
return error;
data->completed_steps++;
report_progress(data, delta->old_file.path);
if ((actions[i] & CHECKOUT_ACTION__UPDATE_BLOB) == 0 &&
(data->strategy & GIT_CHECKOUT_DONT_UPDATE_INDEX) == 0 &&
data->index != NULL)
{
(void)git_index_remove(data->index, delta->old_file.path, 0);
}
}
}
git_vector_foreach(&data->removes, i, str) {
error = git_futils_rmdir_r(str, fullpath->ptr, flg);
if (error < 0)
return error;
data->completed_steps++;
report_progress(data, str);
if ((data->strategy & GIT_CHECKOUT_DONT_UPDATE_INDEX) == 0 &&
data->index != NULL)
{
if (str[strlen(str) - 1] == '/')
(void)git_index_remove_directory(data->index, str, 0);
else
(void)git_index_remove(data->index, str, 0);
}
}
return 0;
}
static int checkout_create_the_new(
unsigned int *actions,
checkout_data *data)
{
int error = 0;
git_diff_delta *delta;
size_t i;
git_vector_foreach(&data->diff->deltas, i, delta) {
if (actions[i] & CHECKOUT_ACTION__UPDATE_BLOB && !S_ISLNK(delta->new_file.mode)) {
if ((error = checkout_blob(data, &delta->new_file)) < 0)
return error;
data->completed_steps++;
report_progress(data, delta->new_file.path);
}
}
git_vector_foreach(&data->diff->deltas, i, delta) {
if (actions[i] & CHECKOUT_ACTION__UPDATE_BLOB && S_ISLNK(delta->new_file.mode)) {
if ((error = checkout_blob(data, &delta->new_file)) < 0)
return error;
data->completed_steps++;
report_progress(data, delta->new_file.path);
}
}
return 0;
}
static int checkout_create_submodules(
unsigned int *actions,
checkout_data *data)
{
git_diff_delta *delta;
size_t i;
git_vector_foreach(&data->diff->deltas, i, delta) {
if (actions[i] & CHECKOUT_ACTION__UPDATE_SUBMODULE) {
int error = checkout_submodule(data, &delta->new_file);
if (error < 0)
return error;
data->completed_steps++;
report_progress(data, delta->new_file.path);
}
}
return 0;
}
static int checkout_lookup_head_tree(git_tree **out, git_repository *repo)
{
int error = 0;
git_reference *ref = NULL;
git_object *head;
if (!(error = git_repository_head(&ref, repo)) &&
!(error = git_reference_peel(&head, ref, GIT_OBJECT_TREE)))
*out = (git_tree *)head;
git_reference_free(ref);
return error;
}
static int conflict_entry_name(
git_buf *out,
const char *side_name,
const char *filename)
{
if (git_buf_puts(out, side_name) < 0 ||
git_buf_putc(out, ':') < 0 ||
git_buf_puts(out, filename) < 0)
return -1;
return 0;
}
static int checkout_path_suffixed(git_buf *path, const char *suffix)
{
size_t path_len;
int i = 0, error = 0;
if ((error = git_buf_putc(path, '~')) < 0 || (error = git_buf_puts(path, suffix)) < 0)
return -1;
path_len = git_buf_len(path);
while (git_path_exists(git_buf_cstr(path)) && i < INT_MAX) {
git_buf_truncate(path, path_len);
if ((error = git_buf_putc(path, '_')) < 0 ||
(error = git_buf_printf(path, "%d", i)) < 0)
return error;
i++;
}
if (i == INT_MAX) {
git_buf_truncate(path, path_len);
git_error_set(GIT_ERROR_CHECKOUT, "could not write '%s': working directory file exists", path->ptr);
return GIT_EEXISTS;
}
return 0;
}
static int checkout_write_entry(
checkout_data *data,
checkout_conflictdata *conflict,
const git_index_entry *side)
{
const char *hint_path, *suffix;
git_buf *fullpath;
struct stat st;
int error;
GIT_ASSERT(side == conflict->ours || side == conflict->theirs);
if (checkout_target_fullpath(&fullpath, data, side->path) < 0)
return -1;
if ((conflict->name_collision || conflict->directoryfile) &&
(data->strategy & GIT_CHECKOUT_USE_OURS) == 0 &&
(data->strategy & GIT_CHECKOUT_USE_THEIRS) == 0) {
if (side == conflict->ours)
suffix = data->opts.our_label ? data->opts.our_label :
"ours";
else
suffix = data->opts.their_label ? data->opts.their_label :
"theirs";
if (checkout_path_suffixed(fullpath, suffix) < 0)
return -1;
}
hint_path = side->path;
if ((data->strategy & GIT_CHECKOUT_UPDATE_ONLY) != 0 &&
(error = checkout_safe_for_update_only(data, fullpath->ptr, side->mode)) <= 0)
return error;
if (!S_ISGITLINK(side->mode))
return checkout_write_content(data,
&side->id, fullpath->ptr, hint_path, side->mode, &st);
return 0;
}
static int checkout_write_entries(
checkout_data *data,
checkout_conflictdata *conflict)
{
int error = 0;
if ((error = checkout_write_entry(data, conflict, conflict->ours)) >= 0)
error = checkout_write_entry(data, conflict, conflict->theirs);
return error;
}
static int checkout_merge_path(
git_buf *out,
checkout_data *data,
checkout_conflictdata *conflict,
git_merge_file_result *result)
{
const char *our_label_raw, *their_label_raw, *suffix;
int error = 0;
if ((error = git_buf_joinpath(out, data->opts.target_directory, result->path)) < 0 ||
(error = git_path_validate_workdir_buf(data->repo, out)) < 0)
return error;
/* Most conflicts simply use the filename in the index */
if (!conflict->name_collision)
return 0;
/* Rename 2->1 conflicts need the branch name appended */
our_label_raw = data->opts.our_label ? data->opts.our_label : "ours";
their_label_raw = data->opts.their_label ? data->opts.their_label : "theirs";
suffix = strcmp(result->path, conflict->ours->path) == 0 ? our_label_raw : their_label_raw;
if ((error = checkout_path_suffixed(out, suffix)) < 0)
return error;
return 0;
}
static int checkout_write_merge(
checkout_data *data,
checkout_conflictdata *conflict)
{
git_buf our_label = GIT_BUF_INIT, their_label = GIT_BUF_INIT,
path_suffixed = GIT_BUF_INIT, path_workdir = GIT_BUF_INIT,
in_data = GIT_BUF_INIT, out_data = GIT_BUF_INIT;
git_merge_file_options opts = GIT_MERGE_FILE_OPTIONS_INIT;
git_merge_file_result result = {0};
git_filebuf output = GIT_FILEBUF_INIT;
git_filter_list *fl = NULL;
git_filter_session filter_session = GIT_FILTER_SESSION_INIT;
int error = 0;
if (data->opts.checkout_strategy & GIT_CHECKOUT_CONFLICT_STYLE_DIFF3)
opts.flags |= GIT_MERGE_FILE_STYLE_DIFF3;
opts.ancestor_label = data->opts.ancestor_label ?
data->opts.ancestor_label : "ancestor";
opts.our_label = data->opts.our_label ?
data->opts.our_label : "ours";
opts.their_label = data->opts.their_label ?
data->opts.their_label : "theirs";
/* If all the paths are identical, decorate the diff3 file with the branch
* names. Otherwise, append branch_name:path.
*/
if (conflict->ours && conflict->theirs &&
strcmp(conflict->ours->path, conflict->theirs->path) != 0) {
if ((error = conflict_entry_name(
&our_label, opts.our_label, conflict->ours->path)) < 0 ||
(error = conflict_entry_name(
&their_label, opts.their_label, conflict->theirs->path)) < 0)
goto done;
opts.our_label = git_buf_cstr(&our_label);
opts.their_label = git_buf_cstr(&their_label);
}
if ((error = git_merge_file_from_index(&result, data->repo,
conflict->ancestor, conflict->ours, conflict->theirs, &opts)) < 0)
goto done;
if (result.path == NULL || result.mode == 0) {
git_error_set(GIT_ERROR_CHECKOUT, "could not merge contents of file");
error = GIT_ECONFLICT;
goto done;
}
if ((error = checkout_merge_path(&path_workdir, data, conflict, &result)) < 0)
goto done;
if ((data->strategy & GIT_CHECKOUT_UPDATE_ONLY) != 0 &&
(error = checkout_safe_for_update_only(data, git_buf_cstr(&path_workdir), result.mode)) <= 0)
goto done;
if (!data->opts.disable_filters) {
in_data.ptr = (char *)result.ptr;
in_data.size = result.len;
filter_session.attr_session = &data->attr_session;
filter_session.temp_buf = &data->tmp;
if ((error = git_filter_list__load(
&fl, data->repo, NULL, result.path,
GIT_FILTER_TO_WORKTREE, &filter_session)) < 0 ||
(error = git_filter_list__convert_buf(&out_data, fl, &in_data)) < 0)
goto done;
} else {
out_data.ptr = (char *)result.ptr;
out_data.size = result.len;
}
if ((error = mkpath2file(data, path_workdir.ptr, data->opts.dir_mode)) < 0 ||
(error = git_filebuf_open(&output, git_buf_cstr(&path_workdir), GIT_FILEBUF_DO_NOT_BUFFER, result.mode)) < 0 ||
(error = git_filebuf_write(&output, out_data.ptr, out_data.size)) < 0 ||
(error = git_filebuf_commit(&output)) < 0)
goto done;
done:
git_filter_list_free(fl);
git_buf_dispose(&out_data);
git_buf_dispose(&our_label);
git_buf_dispose(&their_label);
git_merge_file_result_free(&result);
git_buf_dispose(&path_workdir);
git_buf_dispose(&path_suffixed);
return error;
}
static int checkout_conflict_add(
checkout_data *data,
const git_index_entry *conflict)
{
int error = git_index_remove(data->index, conflict->path, 0);
if (error == GIT_ENOTFOUND)
git_error_clear();
else if (error < 0)
return error;
return git_index_add(data->index, conflict);
}
static int checkout_conflict_update_index(
checkout_data *data,
checkout_conflictdata *conflict)
{
int error = 0;
if (conflict->ancestor)
error = checkout_conflict_add(data, conflict->ancestor);
if (!error && conflict->ours)
error = checkout_conflict_add(data, conflict->ours);
if (!error && conflict->theirs)
error = checkout_conflict_add(data, conflict->theirs);
return error;
}
static int checkout_create_conflicts(checkout_data *data)
{
checkout_conflictdata *conflict;
size_t i;
int error = 0;
git_vector_foreach(&data->update_conflicts, i, conflict) {
/* Both deleted: nothing to do */
if (conflict->ours == NULL && conflict->theirs == NULL)
error = 0;
else if ((data->strategy & GIT_CHECKOUT_USE_OURS) &&
conflict->ours)
error = checkout_write_entry(data, conflict, conflict->ours);
else if ((data->strategy & GIT_CHECKOUT_USE_THEIRS) &&
conflict->theirs)
error = checkout_write_entry(data, conflict, conflict->theirs);
/* Ignore the other side of name collisions. */
else if ((data->strategy & GIT_CHECKOUT_USE_OURS) &&
!conflict->ours && conflict->name_collision)
error = 0;
else if ((data->strategy & GIT_CHECKOUT_USE_THEIRS) &&
!conflict->theirs && conflict->name_collision)
error = 0;
/* For modify/delete, name collisions and d/f conflicts, write
* the file (potentially with the name mangled.
*/
else if (conflict->ours != NULL && conflict->theirs == NULL)
error = checkout_write_entry(data, conflict, conflict->ours);
else if (conflict->ours == NULL && conflict->theirs != NULL)
error = checkout_write_entry(data, conflict, conflict->theirs);
/* Add/add conflicts and rename 1->2 conflicts, write the
* ours/theirs sides (potentially name mangled).
*/
else if (conflict->one_to_two)
error = checkout_write_entries(data, conflict);
/* If all sides are links, write the ours side */
else if (S_ISLNK(conflict->ours->mode) &&
S_ISLNK(conflict->theirs->mode))
error = checkout_write_entry(data, conflict, conflict->ours);
/* Link/file conflicts, write the file side */
else if (S_ISLNK(conflict->ours->mode))
error = checkout_write_entry(data, conflict, conflict->theirs);
else if (S_ISLNK(conflict->theirs->mode))
error = checkout_write_entry(data, conflict, conflict->ours);
/* If any side is a gitlink, do nothing. */
else if (conflict->submodule)
error = 0;
/* If any side is binary, write the ours side */
else if (conflict->binary)
error = checkout_write_entry(data, conflict, conflict->ours);
else if (!error)
error = checkout_write_merge(data, conflict);
/* Update the index extensions (REUC and NAME) if we're checking
* out a different index. (Otherwise just leave them there.)
*/
if (!error && (data->strategy & GIT_CHECKOUT_DONT_UPDATE_INDEX) == 0)
error = checkout_conflict_update_index(data, conflict);
if (error)
break;
data->completed_steps++;
report_progress(data,
conflict->ours ? conflict->ours->path :
(conflict->theirs ? conflict->theirs->path : conflict->ancestor->path));
}
return error;
}
static int checkout_remove_conflicts(checkout_data *data)
{
const char *conflict;
size_t i;
git_vector_foreach(&data->remove_conflicts, i, conflict) {
if (git_index_conflict_remove(data->index, conflict) < 0)
return -1;
data->completed_steps++;
}
return 0;
}
static int checkout_extensions_update_index(checkout_data *data)
{
const git_index_reuc_entry *reuc_entry;
const git_index_name_entry *name_entry;
size_t i;
int error = 0;
if ((data->strategy & GIT_CHECKOUT_UPDATE_ONLY) != 0)
return 0;
if (data->update_reuc) {
git_vector_foreach(data->update_reuc, i, reuc_entry) {
if ((error = git_index_reuc_add(data->index, reuc_entry->path,
reuc_entry->mode[0], &reuc_entry->oid[0],
reuc_entry->mode[1], &reuc_entry->oid[1],
reuc_entry->mode[2], &reuc_entry->oid[2])) < 0)
goto done;
}
}
if (data->update_names) {
git_vector_foreach(data->update_names, i, name_entry) {
if ((error = git_index_name_add(data->index, name_entry->ancestor,
name_entry->ours, name_entry->theirs)) < 0)
goto done;
}
}
done:
return error;
}
static void checkout_data_clear(checkout_data *data)
{
if (data->opts_free_baseline) {
git_tree_free(data->opts.baseline);
data->opts.baseline = NULL;
}
git_vector_free(&data->removes);
git_pool_clear(&data->pool);
git_vector_free_deep(&data->remove_conflicts);
git_vector_free_deep(&data->update_conflicts);
git__free(data->pfx);
data->pfx = NULL;
git_buf_dispose(&data->target_path);
git_buf_dispose(&data->tmp);
git_index_free(data->index);
data->index = NULL;
git_strmap_free(data->mkdir_map);
data->mkdir_map = NULL;
git_attr_session__free(&data->attr_session);
}
static int validate_target_directory(checkout_data *data)
{
int error;
if ((error = git_path_validate_workdir(data->repo, data->opts.target_directory)) < 0)
return error;
if (git_path_isdir(data->opts.target_directory))
return 0;
error = checkout_mkdir(data, data->opts.target_directory, NULL,
GIT_DIR_MODE, GIT_MKDIR_VERIFY_DIR);
return error;
}
static int checkout_data_init(
checkout_data *data,
git_iterator *target,
const git_checkout_options *proposed)
{
int error = 0;
git_repository *repo = git_iterator_owner(target);
memset(data, 0, sizeof(*data));
if (!repo) {
git_error_set(GIT_ERROR_CHECKOUT, "cannot checkout nothing");
return -1;
}
if ((!proposed || !proposed->target_directory) &&
(error = git_repository__ensure_not_bare(repo, "checkout")) < 0)
return error;
data->repo = repo;
data->target = target;
GIT_ERROR_CHECK_VERSION(
proposed, GIT_CHECKOUT_OPTIONS_VERSION, "git_checkout_options");
if (!proposed)
GIT_INIT_STRUCTURE(&data->opts, GIT_CHECKOUT_OPTIONS_VERSION);
else
memmove(&data->opts, proposed, sizeof(git_checkout_options));
if (!data->opts.target_directory)
data->opts.target_directory = git_repository_workdir(repo);
else if ((error = validate_target_directory(data)) < 0)
goto cleanup;
if ((error = git_repository_index(&data->index, data->repo)) < 0)
goto cleanup;
/* refresh config and index content unless NO_REFRESH is given */
if ((data->opts.checkout_strategy & GIT_CHECKOUT_NO_REFRESH) == 0) {
git_config *cfg;
if ((error = git_repository_config__weakptr(&cfg, repo)) < 0)
goto cleanup;
/* Reload the repository index (unless we're checking out the
* index; then it has the changes we're trying to check out
* and those should not be overwritten.)
*/
if (data->index != git_iterator_index(target)) {
if (data->opts.checkout_strategy & GIT_CHECKOUT_FORCE) {
/* When forcing, we can blindly re-read the index */
if ((error = git_index_read(data->index, false)) < 0)
goto cleanup;
} else {
/*
* When not being forced, we need to check for unresolved
* conflicts and unsaved changes in the index before
* proceeding.
*/
if (git_index_has_conflicts(data->index)) {
error = GIT_ECONFLICT;
git_error_set(GIT_ERROR_CHECKOUT,
"unresolved conflicts exist in the index");
goto cleanup;
}
if ((error = git_index_read_safely(data->index)) < 0)
goto cleanup;
}
/* clean conflict data in the current index */
git_index_name_clear(data->index);
git_index_reuc_clear(data->index);
}
}
/* if you are forcing, allow all safe updates, plus recreate missing */
if ((data->opts.checkout_strategy & GIT_CHECKOUT_FORCE) != 0)
data->opts.checkout_strategy |= GIT_CHECKOUT_SAFE |
GIT_CHECKOUT_RECREATE_MISSING;
/* if the repository does not actually have an index file, then this
* is an initial checkout (perhaps from clone), so we allow safe updates
*/
if (!data->index->on_disk &&
(data->opts.checkout_strategy & GIT_CHECKOUT_SAFE) != 0)
data->opts.checkout_strategy |= GIT_CHECKOUT_RECREATE_MISSING;
data->strategy = data->opts.checkout_strategy;
/* opts->disable_filters is false by default */
if (!data->opts.dir_mode)
data->opts.dir_mode = GIT_DIR_MODE;
if (!data->opts.file_open_flags)
data->opts.file_open_flags = O_CREAT | O_TRUNC | O_WRONLY;
data->pfx = git_pathspec_prefix(&data->opts.paths);
if ((error = git_repository__configmap_lookup(
&data->can_symlink, repo, GIT_CONFIGMAP_SYMLINKS)) < 0)
goto cleanup;
if ((error = git_repository__configmap_lookup(
&data->respect_filemode, repo, GIT_CONFIGMAP_FILEMODE)) < 0)
goto cleanup;
if (!data->opts.baseline && !data->opts.baseline_index) {
data->opts_free_baseline = true;
error = 0;
/* if we don't have an index, this is an initial checkout and
* should be against an empty baseline
*/
if (data->index->on_disk)
error = checkout_lookup_head_tree(&data->opts.baseline, repo);
if (error == GIT_EUNBORNBRANCH) {
error = 0;
git_error_clear();
}
if (error < 0)
goto cleanup;
}
if ((data->opts.checkout_strategy &
(GIT_CHECKOUT_CONFLICT_STYLE_MERGE | GIT_CHECKOUT_CONFLICT_STYLE_DIFF3)) == 0) {
git_config_entry *conflict_style = NULL;
git_config *cfg = NULL;
if ((error = git_repository_config__weakptr(&cfg, repo)) < 0 ||
(error = git_config_get_entry(&conflict_style, cfg, "merge.conflictstyle")) < 0 ||
error == GIT_ENOTFOUND)
;
else if (error)
goto cleanup;
else if (strcmp(conflict_style->value, "merge") == 0)
data->opts.checkout_strategy |= GIT_CHECKOUT_CONFLICT_STYLE_MERGE;
else if (strcmp(conflict_style->value, "diff3") == 0)
data->opts.checkout_strategy |= GIT_CHECKOUT_CONFLICT_STYLE_DIFF3;
else {
git_error_set(GIT_ERROR_CHECKOUT, "unknown style '%s' given for 'merge.conflictstyle'",
conflict_style->value);
error = -1;
git_config_entry_free(conflict_style);
goto cleanup;
}
git_config_entry_free(conflict_style);
}
if ((error = git_pool_init(&data->pool, 1)) < 0 ||
(error = git_vector_init(&data->removes, 0, git__strcmp_cb)) < 0 ||
(error = git_vector_init(&data->remove_conflicts, 0, NULL)) < 0 ||
(error = git_vector_init(&data->update_conflicts, 0, NULL)) < 0 ||
(error = git_buf_puts(&data->target_path, data->opts.target_directory)) < 0 ||
(error = git_path_to_dir(&data->target_path)) < 0 ||
(error = git_strmap_new(&data->mkdir_map)) < 0)
goto cleanup;
data->target_len = git_buf_len(&data->target_path);
git_attr_session__init(&data->attr_session, data->repo);
cleanup:
if (error < 0)
checkout_data_clear(data);
return error;
}
#define CHECKOUT_INDEX_DONT_WRITE_MASK \
(GIT_CHECKOUT_DONT_UPDATE_INDEX | GIT_CHECKOUT_DONT_WRITE_INDEX)
GIT_INLINE(void) setup_pathspecs(
git_iterator_options *iter_opts,
const git_checkout_options *checkout_opts)
{
if (checkout_opts &&
(checkout_opts->checkout_strategy & GIT_CHECKOUT_DISABLE_PATHSPEC_MATCH)) {
iter_opts->pathlist.count = checkout_opts->paths.count;
iter_opts->pathlist.strings = checkout_opts->paths.strings;
}
}
int git_checkout_iterator(
git_iterator *target,
git_index *index,
const git_checkout_options *opts)
{
int error = 0;
git_iterator *baseline = NULL, *workdir = NULL;
git_iterator_options baseline_opts = GIT_ITERATOR_OPTIONS_INIT,
workdir_opts = GIT_ITERATOR_OPTIONS_INIT;
checkout_data data = {0};
git_diff_options diff_opts = GIT_DIFF_OPTIONS_INIT;
uint32_t *actions = NULL;
size_t *counts = NULL;
/* initialize structures and options */
error = checkout_data_init(&data, target, opts);
if (error < 0)
return error;
diff_opts.flags =
GIT_DIFF_INCLUDE_UNMODIFIED |
GIT_DIFF_INCLUDE_UNREADABLE |
GIT_DIFF_INCLUDE_UNTRACKED |
GIT_DIFF_RECURSE_UNTRACKED_DIRS | /* needed to match baseline */
GIT_DIFF_INCLUDE_IGNORED |
GIT_DIFF_INCLUDE_TYPECHANGE |
GIT_DIFF_INCLUDE_TYPECHANGE_TREES |
GIT_DIFF_SKIP_BINARY_CHECK |
GIT_DIFF_INCLUDE_CASECHANGE;
if (data.opts.checkout_strategy & GIT_CHECKOUT_DISABLE_PATHSPEC_MATCH)
diff_opts.flags |= GIT_DIFF_DISABLE_PATHSPEC_MATCH;
if (data.opts.paths.count > 0)
diff_opts.pathspec = data.opts.paths;
/* set up iterators */
workdir_opts.flags = git_iterator_ignore_case(target) ?
GIT_ITERATOR_IGNORE_CASE : GIT_ITERATOR_DONT_IGNORE_CASE;
workdir_opts.flags |= GIT_ITERATOR_DONT_AUTOEXPAND;
workdir_opts.start = data.pfx;
workdir_opts.end = data.pfx;
setup_pathspecs(&workdir_opts, opts);
if ((error = git_iterator_reset_range(target, data.pfx, data.pfx)) < 0 ||
(error = git_iterator_for_workdir_ext(
&workdir, data.repo, data.opts.target_directory, index, NULL,
&workdir_opts)) < 0)
goto cleanup;
baseline_opts.flags = git_iterator_ignore_case(target) ?
GIT_ITERATOR_IGNORE_CASE : GIT_ITERATOR_DONT_IGNORE_CASE;
baseline_opts.start = data.pfx;
baseline_opts.end = data.pfx;
setup_pathspecs(&baseline_opts, opts);
if (data.opts.baseline_index) {
if ((error = git_iterator_for_index(
&baseline, git_index_owner(data.opts.baseline_index),
data.opts.baseline_index, &baseline_opts)) < 0)
goto cleanup;
} else {
if ((error = git_iterator_for_tree(
&baseline, data.opts.baseline, &baseline_opts)) < 0)
goto cleanup;
}
/* Should not have case insensitivity mismatch */
GIT_ASSERT(git_iterator_ignore_case(workdir) == git_iterator_ignore_case(baseline));
/* Generate baseline-to-target diff which will include an entry for
* every possible update that might need to be made.
*/
if ((error = git_diff__from_iterators(
&data.diff, data.repo, baseline, target, &diff_opts)) < 0)
goto cleanup;
/* Loop through diff (and working directory iterator) building a list of
* actions to be taken, plus look for conflicts and send notifications,
* then loop through conflicts.
*/
if ((error = checkout_get_actions(&actions, &counts, &data, workdir)) != 0)
goto cleanup;
if (data.strategy & GIT_CHECKOUT_DRY_RUN)
goto cleanup;
data.total_steps = counts[CHECKOUT_ACTION__REMOVE] +
counts[CHECKOUT_ACTION__REMOVE_CONFLICT] +
counts[CHECKOUT_ACTION__UPDATE_BLOB] +
counts[CHECKOUT_ACTION__UPDATE_SUBMODULE] +
counts[CHECKOUT_ACTION__UPDATE_CONFLICT];
report_progress(&data, NULL); /* establish 0 baseline */
/* To deal with some order dependencies, perform remaining checkout
* in three passes: removes, then update blobs, then update submodules.
*/
if (counts[CHECKOUT_ACTION__REMOVE] > 0 &&
(error = checkout_remove_the_old(actions, &data)) < 0)
goto cleanup;
if (counts[CHECKOUT_ACTION__REMOVE_CONFLICT] > 0 &&
(error = checkout_remove_conflicts(&data)) < 0)
goto cleanup;
if (counts[CHECKOUT_ACTION__UPDATE_BLOB] > 0 &&
(error = checkout_create_the_new(actions, &data)) < 0)
goto cleanup;
if (counts[CHECKOUT_ACTION__UPDATE_SUBMODULE] > 0 &&
(error = checkout_create_submodules(actions, &data)) < 0)
goto cleanup;
if (counts[CHECKOUT_ACTION__UPDATE_CONFLICT] > 0 &&
(error = checkout_create_conflicts(&data)) < 0)
goto cleanup;
if (data.index != git_iterator_index(target) &&
(error = checkout_extensions_update_index(&data)) < 0)
goto cleanup;
GIT_ASSERT(data.completed_steps == data.total_steps);
if (data.opts.perfdata_cb)
data.opts.perfdata_cb(&data.perfdata, data.opts.perfdata_payload);
cleanup:
if (!error && data.index != NULL &&
(data.strategy & CHECKOUT_INDEX_DONT_WRITE_MASK) == 0)
error = git_index_write(data.index);
git_diff_free(data.diff);
git_iterator_free(workdir);
git_iterator_free(baseline);
git__free(actions);
git__free(counts);
checkout_data_clear(&data);
return error;
}
int git_checkout_index(
git_repository *repo,
git_index *index,
const git_checkout_options *opts)
{
git_iterator_options iter_opts = GIT_ITERATOR_OPTIONS_INIT;
int error, owned = 0;
git_iterator *index_i;
if (!index && !repo) {
git_error_set(GIT_ERROR_CHECKOUT,
"must provide either repository or index to checkout");
return -1;
}
if (index && repo &&
git_index_owner(index) &&
git_index_owner(index) != repo) {
git_error_set(GIT_ERROR_CHECKOUT,
"index to checkout does not match repository");
return -1;
} else if(index && repo && !git_index_owner(index)) {
GIT_REFCOUNT_OWN(index, repo);
owned = 1;
}
if (!repo)
repo = git_index_owner(index);
if (!index && (error = git_repository_index__weakptr(&index, repo)) < 0)
return error;
GIT_REFCOUNT_INC(index);
setup_pathspecs(&iter_opts, opts);
if (!(error = git_iterator_for_index(&index_i, repo, index, &iter_opts)))
error = git_checkout_iterator(index_i, index, opts);
if (owned)
GIT_REFCOUNT_OWN(index, NULL);
git_iterator_free(index_i);
git_index_free(index);
return error;
}
int git_checkout_tree(
git_repository *repo,
const git_object *treeish,
const git_checkout_options *opts)
{
int error;
git_index *index;
git_tree *tree = NULL;
git_iterator *tree_i = NULL;
git_iterator_options iter_opts = GIT_ITERATOR_OPTIONS_INIT;
if (!treeish && !repo) {
git_error_set(GIT_ERROR_CHECKOUT,
"must provide either repository or tree to checkout");
return -1;
}
if (treeish && repo && git_object_owner(treeish) != repo) {
git_error_set(GIT_ERROR_CHECKOUT,
"object to checkout does not match repository");
return -1;
}
if (!repo)
repo = git_object_owner(treeish);
if (treeish) {
if (git_object_peel((git_object **)&tree, treeish, GIT_OBJECT_TREE) < 0) {
git_error_set(
GIT_ERROR_CHECKOUT, "provided object cannot be peeled to a tree");
return -1;
}
}
else {
if ((error = checkout_lookup_head_tree(&tree, repo)) < 0) {
if (error != GIT_EUNBORNBRANCH)
git_error_set(
GIT_ERROR_CHECKOUT,
"HEAD could not be peeled to a tree and no treeish given");
return error;
}
}
if ((error = git_repository_index(&index, repo)) < 0)
return error;
setup_pathspecs(&iter_opts, opts);
if (!(error = git_iterator_for_tree(&tree_i, tree, &iter_opts)))
error = git_checkout_iterator(tree_i, index, opts);
git_iterator_free(tree_i);
git_index_free(index);
git_tree_free(tree);
return error;
}
int git_checkout_head(
git_repository *repo,
const git_checkout_options *opts)
{
GIT_ASSERT_ARG(repo);
return git_checkout_tree(repo, NULL, opts);
}
int git_checkout_options_init(git_checkout_options *opts, unsigned int version)
{
GIT_INIT_STRUCTURE_FROM_TEMPLATE(
opts, version, git_checkout_options, GIT_CHECKOUT_OPTIONS_INIT);
return 0;
}
#ifndef GIT_DEPRECATE_HARD
int git_checkout_init_options(git_checkout_options *opts, unsigned int version)
{
return git_checkout_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/parse.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 "parse.h"
int git_parse_ctx_init(git_parse_ctx *ctx, const char *content, size_t content_len)
{
if (content && content_len) {
ctx->content = content;
ctx->content_len = content_len;
} else {
ctx->content = "";
ctx->content_len = 0;
}
ctx->remain = ctx->content;
ctx->remain_len = ctx->content_len;
ctx->line = ctx->remain;
ctx->line_len = git__linenlen(ctx->line, ctx->remain_len);
ctx->line_num = 1;
return 0;
}
void git_parse_ctx_clear(git_parse_ctx *ctx)
{
memset(ctx, 0, sizeof(*ctx));
ctx->content = "";
}
void git_parse_advance_line(git_parse_ctx *ctx)
{
ctx->line += ctx->line_len;
ctx->remain_len -= ctx->line_len;
ctx->line_len = git__linenlen(ctx->line, ctx->remain_len);
ctx->line_num++;
}
void git_parse_advance_chars(git_parse_ctx *ctx, size_t char_cnt)
{
ctx->line += char_cnt;
ctx->remain_len -= char_cnt;
ctx->line_len -= char_cnt;
}
int git_parse_advance_expected(
git_parse_ctx *ctx,
const char *expected,
size_t expected_len)
{
if (ctx->line_len < expected_len)
return -1;
if (memcmp(ctx->line, expected, expected_len) != 0)
return -1;
git_parse_advance_chars(ctx, expected_len);
return 0;
}
int git_parse_advance_ws(git_parse_ctx *ctx)
{
int ret = -1;
while (ctx->line_len > 0 &&
ctx->line[0] != '\n' &&
git__isspace(ctx->line[0])) {
ctx->line++;
ctx->line_len--;
ctx->remain_len--;
ret = 0;
}
return ret;
}
int git_parse_advance_nl(git_parse_ctx *ctx)
{
if (ctx->line_len != 1 || ctx->line[0] != '\n')
return -1;
git_parse_advance_line(ctx);
return 0;
}
int git_parse_advance_digit(int64_t *out, git_parse_ctx *ctx, int base)
{
const char *end;
int ret;
if (ctx->line_len < 1 || !git__isdigit(ctx->line[0]))
return -1;
if ((ret = git__strntol64(out, ctx->line, ctx->line_len, &end, base)) < 0)
return -1;
git_parse_advance_chars(ctx, (end - ctx->line));
return 0;
}
int git_parse_advance_oid(git_oid *out, git_parse_ctx *ctx)
{
if (ctx->line_len < GIT_OID_HEXSZ)
return -1;
if ((git_oid_fromstrn(out, ctx->line, GIT_OID_HEXSZ)) < 0)
return -1;
git_parse_advance_chars(ctx, GIT_OID_HEXSZ);
return 0;
}
int git_parse_peek(char *out, git_parse_ctx *ctx, int flags)
{
size_t remain = ctx->line_len;
const char *ptr = ctx->line;
while (remain) {
char c = *ptr;
if ((flags & GIT_PARSE_PEEK_SKIP_WHITESPACE) &&
git__isspace(c)) {
remain--;
ptr++;
continue;
}
*out = c;
return 0;
}
return -1;
}
|
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.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 "ignore.h"
#include "git2/ignore.h"
#include "common.h"
#include "attrcache.h"
#include "path.h"
#include "config.h"
#include "wildmatch.h"
#define GIT_IGNORE_INTERNAL "[internal]exclude"
#define GIT_IGNORE_DEFAULT_RULES ".\n..\n.git\n"
/**
* A negative ignore pattern can negate a positive one without
* wildcards if it is a basename only and equals the basename of
* the positive pattern. Thus
*
* foo/bar
* !bar
*
* would result in foo/bar being unignored again while
*
* moo/foo/bar
* !foo/bar
*
* would do nothing. The reverse also holds true: a positive
* basename pattern can be negated by unignoring the basename in
* subdirectories. Thus
*
* bar
* !foo/bar
*
* would result in foo/bar being unignored again. As with the
* first case,
*
* foo/bar
* !moo/foo/bar
*
* would do nothing, again.
*/
static int does_negate_pattern(git_attr_fnmatch *rule, git_attr_fnmatch *neg)
{
int (*cmp)(const char *, const char *, size_t);
git_attr_fnmatch *longer, *shorter;
char *p;
if ((rule->flags & GIT_ATTR_FNMATCH_NEGATIVE) != 0
|| (neg->flags & GIT_ATTR_FNMATCH_NEGATIVE) == 0)
return false;
if (neg->flags & GIT_ATTR_FNMATCH_ICASE)
cmp = git__strncasecmp;
else
cmp = git__strncmp;
/* If lengths match we need to have an exact match */
if (rule->length == neg->length) {
return cmp(rule->pattern, neg->pattern, rule->length) == 0;
} else if (rule->length < neg->length) {
shorter = rule;
longer = neg;
} else {
shorter = neg;
longer = rule;
}
/* Otherwise, we need to check if the shorter
* rule is a basename only (that is, it contains
* no path separator) and, if so, if it
* matches the tail of the longer rule */
p = longer->pattern + longer->length - shorter->length;
if (p[-1] != '/')
return false;
if (memchr(shorter->pattern, '/', shorter->length) != NULL)
return false;
return cmp(p, shorter->pattern, shorter->length) == 0;
}
/**
* A negative ignore can only unignore a file which is given explicitly before, thus
*
* foo
* !foo/bar
*
* does not unignore 'foo/bar' as it's not in the list. However
*
* foo/<star>
* !foo/bar
*
* does unignore 'foo/bar', as it is contained within the 'foo/<star>' rule.
*/
static int does_negate_rule(int *out, git_vector *rules, git_attr_fnmatch *match)
{
int error = 0, wildmatch_flags, effective_flags;
size_t i;
git_attr_fnmatch *rule;
char *path;
git_buf buf = GIT_BUF_INIT;
*out = 0;
wildmatch_flags = WM_PATHNAME;
if (match->flags & GIT_ATTR_FNMATCH_ICASE)
wildmatch_flags |= WM_CASEFOLD;
/* path of the file relative to the workdir, so we match the rules in subdirs */
if (match->containing_dir) {
git_buf_puts(&buf, match->containing_dir);
}
if (git_buf_puts(&buf, match->pattern) < 0)
return -1;
path = git_buf_detach(&buf);
git_vector_foreach(rules, i, rule) {
if (!(rule->flags & GIT_ATTR_FNMATCH_HASWILD)) {
if (does_negate_pattern(rule, match)) {
error = 0;
*out = 1;
goto out;
}
else
continue;
}
git_buf_clear(&buf);
if (rule->containing_dir)
git_buf_puts(&buf, rule->containing_dir);
git_buf_puts(&buf, rule->pattern);
if (git_buf_oom(&buf))
goto out;
/*
* if rule isn't for full path we match without PATHNAME flag
* as lines like *.txt should match something like dir/test.txt
* requiring * to also match /
*/
effective_flags = wildmatch_flags;
if (!(rule->flags & GIT_ATTR_FNMATCH_FULLPATH))
effective_flags &= ~WM_PATHNAME;
/* if we found a match, we want to keep this rule */
if ((wildmatch(git_buf_cstr(&buf), path, effective_flags)) == WM_MATCH) {
*out = 1;
error = 0;
goto out;
}
}
error = 0;
out:
git__free(path);
git_buf_dispose(&buf);
return error;
}
static int parse_ignore_file(
git_repository *repo, git_attr_file *attrs, const char *data, bool allow_macros)
{
int error = 0;
int ignore_case = false;
const char *scan = data, *context = NULL;
git_attr_fnmatch *match = NULL;
GIT_UNUSED(allow_macros);
if (git_repository__configmap_lookup(&ignore_case, repo, GIT_CONFIGMAP_IGNORECASE) < 0)
git_error_clear();
/* 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_IGNORE_FILE))
context = attrs->entry->path;
if (git_mutex_lock(&attrs->lock) < 0) {
git_error_set(GIT_ERROR_OS, "failed to lock ignore file");
return -1;
}
while (!error && *scan) {
int valid_rule = 1;
if (!match && !(match = git__calloc(1, sizeof(*match)))) {
error = -1;
break;
}
match->flags =
GIT_ATTR_FNMATCH_ALLOWSPACE | GIT_ATTR_FNMATCH_ALLOWNEG;
if (!(error = git_attr_fnmatch__parse(
match, &attrs->pool, context, &scan)))
{
match->flags |= GIT_ATTR_FNMATCH_IGNORE;
if (ignore_case)
match->flags |= GIT_ATTR_FNMATCH_ICASE;
scan = git__next_line(scan);
/*
* If a negative match doesn't actually do anything,
* throw it away. As we cannot always verify whether a
* rule containing wildcards negates another rule, we
* do not optimize away these rules, though.
* */
if (match->flags & GIT_ATTR_FNMATCH_NEGATIVE
&& !(match->flags & GIT_ATTR_FNMATCH_HASWILD))
error = does_negate_rule(&valid_rule, &attrs->rules, match);
if (!error && valid_rule)
error = git_vector_insert(&attrs->rules, match);
}
if (error != 0 || !valid_rule) {
match->pattern = NULL;
if (error == GIT_ENOTFOUND)
error = 0;
} else {
match = NULL; /* vector now "owns" the match */
}
}
git_mutex_unlock(&attrs->lock);
git__free(match);
return error;
}
static int push_ignore_file(
git_ignores *ignores,
git_vector *which_list,
const char *base,
const char *filename)
{
git_attr_file_source source = { GIT_ATTR_FILE_SOURCE_FILE, base, filename };
git_attr_file *file = NULL;
int error = 0;
error = git_attr_cache__get(&file, ignores->repo, NULL, &source, parse_ignore_file, false);
if (error < 0)
return error;
if (file != NULL) {
if ((error = git_vector_insert(which_list, file)) < 0)
git_attr_file__free(file);
}
return error;
}
static int push_one_ignore(void *payload, const char *path)
{
git_ignores *ign = payload;
ign->depth++;
return push_ignore_file(ign, &ign->ign_path, path, GIT_IGNORE_FILE);
}
static int get_internal_ignores(git_attr_file **out, git_repository *repo)
{
git_attr_file_source source = { GIT_ATTR_FILE_SOURCE_MEMORY, NULL, GIT_IGNORE_INTERNAL };
int error;
if ((error = git_attr_cache__init(repo)) < 0)
return error;
error = git_attr_cache__get(out, repo, NULL, &source, NULL, false);
/* if internal rules list is empty, insert default rules */
if (!error && !(*out)->rules.length)
error = parse_ignore_file(repo, *out, GIT_IGNORE_DEFAULT_RULES, false);
return error;
}
int git_ignore__for_path(
git_repository *repo,
const char *path,
git_ignores *ignores)
{
int error = 0;
const char *workdir = git_repository_workdir(repo);
git_buf infopath = GIT_BUF_INIT;
GIT_ASSERT_ARG(repo);
GIT_ASSERT_ARG(ignores);
GIT_ASSERT_ARG(path);
memset(ignores, 0, sizeof(*ignores));
ignores->repo = repo;
/* Read the ignore_case flag */
if ((error = git_repository__configmap_lookup(
&ignores->ignore_case, repo, GIT_CONFIGMAP_IGNORECASE)) < 0)
goto cleanup;
if ((error = git_attr_cache__init(repo)) < 0)
goto cleanup;
/* given a unrooted path in a non-bare repo, resolve it */
if (workdir && git_path_root(path) < 0) {
git_buf local = GIT_BUF_INIT;
if ((error = git_path_dirname_r(&local, path)) < 0 ||
(error = git_path_resolve_relative(&local, 0)) < 0 ||
(error = git_path_to_dir(&local)) < 0 ||
(error = git_buf_joinpath(&ignores->dir, workdir, local.ptr)) < 0 ||
(error = git_path_validate_workdir_buf(repo, &ignores->dir)) < 0) {
/* Nothing, we just want to stop on the first error */
}
git_buf_dispose(&local);
} else {
if (!(error = git_buf_joinpath(&ignores->dir, path, "")))
error = git_path_validate_filesystem(ignores->dir.ptr, ignores->dir.size);
}
if (error < 0)
goto cleanup;
if (workdir && !git__prefixcmp(ignores->dir.ptr, workdir))
ignores->dir_root = strlen(workdir);
/* set up internals */
if ((error = get_internal_ignores(&ignores->ign_internal, repo)) < 0)
goto cleanup;
/* load .gitignore up the path */
if (workdir != NULL) {
error = git_path_walk_up(
&ignores->dir, workdir, push_one_ignore, ignores);
if (error < 0)
goto cleanup;
}
/* load .git/info/exclude if possible */
if ((error = git_repository_item_path(&infopath, repo, GIT_REPOSITORY_ITEM_INFO)) < 0 ||
(error = push_ignore_file(ignores, &ignores->ign_global, infopath.ptr, GIT_IGNORE_FILE_INREPO)) < 0) {
if (error != GIT_ENOTFOUND)
goto cleanup;
error = 0;
}
/* load core.excludesfile */
if (git_repository_attr_cache(repo)->cfg_excl_file != NULL)
error = push_ignore_file(
ignores, &ignores->ign_global, NULL,
git_repository_attr_cache(repo)->cfg_excl_file);
cleanup:
git_buf_dispose(&infopath);
if (error < 0)
git_ignore__free(ignores);
return error;
}
int git_ignore__push_dir(git_ignores *ign, const char *dir)
{
if (git_buf_joinpath(&ign->dir, ign->dir.ptr, dir) < 0)
return -1;
ign->depth++;
return push_ignore_file(
ign, &ign->ign_path, ign->dir.ptr, GIT_IGNORE_FILE);
}
int git_ignore__pop_dir(git_ignores *ign)
{
if (ign->ign_path.length > 0) {
git_attr_file *file = git_vector_last(&ign->ign_path);
const char *start = file->entry->path, *end;
/* - ign->dir looks something like "/home/user/a/b/" (or "a/b/c/d/")
* - file->path looks something like "a/b/.gitignore
*
* We are popping the last directory off ign->dir. We also want
* to remove the file from the vector if the popped directory
* matches the ignore path. We need to test if the "a/b" part of
* the file key matches the path we are about to pop.
*/
if ((end = strrchr(start, '/')) != NULL) {
size_t dirlen = (end - start) + 1;
const char *relpath = ign->dir.ptr + ign->dir_root;
size_t pathlen = ign->dir.size - ign->dir_root;
if (pathlen == dirlen && !memcmp(relpath, start, dirlen)) {
git_vector_pop(&ign->ign_path);
git_attr_file__free(file);
}
}
}
if (--ign->depth > 0) {
git_buf_rtruncate_at_char(&ign->dir, '/');
git_path_to_dir(&ign->dir);
}
return 0;
}
void git_ignore__free(git_ignores *ignores)
{
unsigned int i;
git_attr_file *file;
git_attr_file__free(ignores->ign_internal);
git_vector_foreach(&ignores->ign_path, i, file) {
git_attr_file__free(file);
ignores->ign_path.contents[i] = NULL;
}
git_vector_free(&ignores->ign_path);
git_vector_foreach(&ignores->ign_global, i, file) {
git_attr_file__free(file);
ignores->ign_global.contents[i] = NULL;
}
git_vector_free(&ignores->ign_global);
git_buf_dispose(&ignores->dir);
}
static bool ignore_lookup_in_rules(
int *ignored, git_attr_file *file, git_attr_path *path)
{
size_t j;
git_attr_fnmatch *match;
git_vector_rforeach(&file->rules, j, match) {
if (match->flags & GIT_ATTR_FNMATCH_DIRECTORY &&
path->is_dir == GIT_DIR_FLAG_FALSE)
continue;
if (git_attr_fnmatch__match(match, path)) {
*ignored = ((match->flags & GIT_ATTR_FNMATCH_NEGATIVE) == 0) ?
GIT_IGNORE_TRUE : GIT_IGNORE_FALSE;
return true;
}
}
return false;
}
int git_ignore__lookup(
int *out, git_ignores *ignores, const char *pathname, git_dir_flag dir_flag)
{
size_t i;
git_attr_file *file;
git_attr_path path;
*out = GIT_IGNORE_NOTFOUND;
if (git_attr_path__init(
&path, pathname, git_repository_workdir(ignores->repo), dir_flag) < 0)
return -1;
/* first process builtins - success means path was found */
if (ignore_lookup_in_rules(out, ignores->ign_internal, &path))
goto cleanup;
/* next process files in the path.
* this process has to process ignores in reverse order
* to ensure correct prioritization of rules
*/
git_vector_rforeach(&ignores->ign_path, i, file) {
if (ignore_lookup_in_rules(out, file, &path))
goto cleanup;
}
/* last process global ignores */
git_vector_foreach(&ignores->ign_global, i, file) {
if (ignore_lookup_in_rules(out, file, &path))
goto cleanup;
}
cleanup:
git_attr_path__free(&path);
return 0;
}
int git_ignore_add_rule(git_repository *repo, const char *rules)
{
int error;
git_attr_file *ign_internal = NULL;
if ((error = get_internal_ignores(&ign_internal, repo)) < 0)
return error;
error = parse_ignore_file(repo, ign_internal, rules, false);
git_attr_file__free(ign_internal);
return error;
}
int git_ignore_clear_internal_rules(git_repository *repo)
{
int error;
git_attr_file *ign_internal;
if ((error = get_internal_ignores(&ign_internal, repo)) < 0)
return error;
if (!(error = git_attr_file__clear_rules(ign_internal, true)))
error = parse_ignore_file(
repo, ign_internal, GIT_IGNORE_DEFAULT_RULES, false);
git_attr_file__free(ign_internal);
return error;
}
int git_ignore_path_is_ignored(
int *ignored,
git_repository *repo,
const char *pathname)
{
int error;
const char *workdir;
git_attr_path path;
git_ignores ignores;
unsigned int i;
git_attr_file *file;
git_dir_flag dir_flag = GIT_DIR_FLAG_UNKNOWN;
GIT_ASSERT_ARG(repo);
GIT_ASSERT_ARG(ignored);
GIT_ASSERT_ARG(pathname);
workdir = git_repository_workdir(repo);
memset(&path, 0, sizeof(path));
memset(&ignores, 0, sizeof(ignores));
if (!git__suffixcmp(pathname, "/"))
dir_flag = GIT_DIR_FLAG_TRUE;
else if (git_repository_is_bare(repo))
dir_flag = GIT_DIR_FLAG_FALSE;
if ((error = git_attr_path__init(&path, pathname, workdir, dir_flag)) < 0 ||
(error = git_ignore__for_path(repo, path.path, &ignores)) < 0)
goto cleanup;
while (1) {
/* first process builtins - success means path was found */
if (ignore_lookup_in_rules(ignored, ignores.ign_internal, &path))
goto cleanup;
/* next process files in the path */
git_vector_foreach(&ignores.ign_path, i, file) {
if (ignore_lookup_in_rules(ignored, file, &path))
goto cleanup;
}
/* last process global ignores */
git_vector_foreach(&ignores.ign_global, i, file) {
if (ignore_lookup_in_rules(ignored, file, &path))
goto cleanup;
}
/* move up one directory */
if (path.basename == path.path)
break;
path.basename[-1] = '\0';
while (path.basename > path.path && *path.basename != '/')
path.basename--;
if (path.basename > path.path)
path.basename++;
path.is_dir = 1;
if ((error = git_ignore__pop_dir(&ignores)) < 0)
break;
}
*ignored = 0;
cleanup:
git_attr_path__free(&path);
git_ignore__free(&ignores);
return error;
}
int git_ignore__check_pathspec_for_exact_ignores(
git_repository *repo,
git_vector *vspec,
bool no_fnmatch)
{
int error = 0;
size_t i;
git_attr_fnmatch *match;
int ignored;
git_buf path = GIT_BUF_INIT;
const char *filename;
git_index *idx;
if ((error = git_repository__ensure_not_bare(
repo, "validate pathspec")) < 0 ||
(error = git_repository_index(&idx, repo)) < 0)
return error;
git_vector_foreach(vspec, i, match) {
/* skip wildcard matches (if they are being used) */
if ((match->flags & GIT_ATTR_FNMATCH_HASWILD) != 0 &&
!no_fnmatch)
continue;
filename = match->pattern;
/* if file is already in the index, it's fine */
if (git_index_get_bypath(idx, filename, 0) != NULL)
continue;
if ((error = git_repository_workdir_path(&path, repo, filename)) < 0)
break;
/* is there a file on disk that matches this exactly? */
if (!git_path_isfile(path.ptr))
continue;
/* is that file ignored? */
if ((error = git_ignore_path_is_ignored(&ignored, repo, filename)) < 0)
break;
if (ignored) {
git_error_set(GIT_ERROR_INVALID, "pathspec contains ignored file '%s'",
filename);
error = GIT_EINVALIDSPEC;
break;
}
}
git_index_free(idx);
git_buf_dispose(&path);
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_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 "diff_generate.h"
#include "diff.h"
#include "patch_generate.h"
#include "futils.h"
#include "config.h"
#include "attr_file.h"
#include "filter.h"
#include "pathspec.h"
#include "index.h"
#include "odb.h"
#include "submodule.h"
#define DIFF_FLAG_IS_SET(DIFF,FLAG) \
(((DIFF)->base.opts.flags & (FLAG)) != 0)
#define DIFF_FLAG_ISNT_SET(DIFF,FLAG) \
(((DIFF)->base.opts.flags & (FLAG)) == 0)
#define DIFF_FLAG_SET(DIFF,FLAG,VAL) (DIFF)->base.opts.flags = \
(VAL) ? ((DIFF)->base.opts.flags | (FLAG)) : \
((DIFF)->base.opts.flags & ~(FLAG))
typedef struct {
struct git_diff base;
git_vector pathspec;
uint32_t diffcaps;
bool index_updated;
} git_diff_generated;
static git_diff_delta *diff_delta__alloc(
git_diff_generated *diff,
git_delta_t status,
const char *path)
{
git_diff_delta *delta = git__calloc(1, sizeof(git_diff_delta));
if (!delta)
return NULL;
delta->old_file.path = git_pool_strdup(&diff->base.pool, path);
if (delta->old_file.path == NULL) {
git__free(delta);
return NULL;
}
delta->new_file.path = delta->old_file.path;
if (DIFF_FLAG_IS_SET(diff, GIT_DIFF_REVERSE)) {
switch (status) {
case GIT_DELTA_ADDED: status = GIT_DELTA_DELETED; break;
case GIT_DELTA_DELETED: status = GIT_DELTA_ADDED; break;
default: break; /* leave other status values alone */
}
}
delta->status = status;
return delta;
}
static int diff_insert_delta(
git_diff_generated *diff,
git_diff_delta *delta,
const char *matched_pathspec)
{
int error = 0;
if (diff->base.opts.notify_cb) {
error = diff->base.opts.notify_cb(
&diff->base, delta, matched_pathspec, diff->base.opts.payload);
if (error) {
git__free(delta);
if (error > 0) /* positive value means to skip this delta */
return 0;
else /* negative value means to cancel diff */
return git_error_set_after_callback_function(error, "git_diff");
}
}
if ((error = git_vector_insert(&diff->base.deltas, delta)) < 0)
git__free(delta);
return error;
}
static bool diff_pathspec_match(
const char **matched_pathspec,
git_diff_generated *diff,
const git_index_entry *entry)
{
bool disable_pathspec_match =
DIFF_FLAG_IS_SET(diff, GIT_DIFF_DISABLE_PATHSPEC_MATCH);
/* If we're disabling fnmatch, then the iterator has already applied
* the filters to the files for us and we don't have to do anything.
* However, this only applies to *files* - the iterator will include
* directories that we need to recurse into when not autoexpanding,
* so we still need to apply the pathspec match to directories.
*/
if ((S_ISLNK(entry->mode) || S_ISREG(entry->mode)) &&
disable_pathspec_match) {
*matched_pathspec = entry->path;
return true;
}
return git_pathspec__match(
&diff->pathspec, entry->path, disable_pathspec_match,
DIFF_FLAG_IS_SET(diff, GIT_DIFF_IGNORE_CASE),
matched_pathspec, NULL);
}
static int diff_delta__from_one(
git_diff_generated *diff,
git_delta_t status,
const git_index_entry *oitem,
const git_index_entry *nitem)
{
const git_index_entry *entry = nitem;
bool has_old = false;
git_diff_delta *delta;
const char *matched_pathspec;
GIT_ASSERT_ARG((oitem != NULL) ^ (nitem != NULL));
if (oitem) {
entry = oitem;
has_old = true;
}
if (DIFF_FLAG_IS_SET(diff, GIT_DIFF_REVERSE))
has_old = !has_old;
if ((entry->flags & GIT_INDEX_ENTRY_VALID) != 0)
return 0;
if (status == GIT_DELTA_IGNORED &&
DIFF_FLAG_ISNT_SET(diff, GIT_DIFF_INCLUDE_IGNORED))
return 0;
if (status == GIT_DELTA_UNTRACKED &&
DIFF_FLAG_ISNT_SET(diff, GIT_DIFF_INCLUDE_UNTRACKED))
return 0;
if (status == GIT_DELTA_UNREADABLE &&
DIFF_FLAG_ISNT_SET(diff, GIT_DIFF_INCLUDE_UNREADABLE))
return 0;
if (!diff_pathspec_match(&matched_pathspec, diff, entry))
return 0;
delta = diff_delta__alloc(diff, status, entry->path);
GIT_ERROR_CHECK_ALLOC(delta);
/* This fn is just for single-sided diffs */
GIT_ASSERT(status != GIT_DELTA_MODIFIED);
delta->nfiles = 1;
if (has_old) {
delta->old_file.mode = entry->mode;
delta->old_file.size = entry->file_size;
delta->old_file.flags |= GIT_DIFF_FLAG_EXISTS;
git_oid_cpy(&delta->old_file.id, &entry->id);
delta->old_file.id_abbrev = GIT_OID_HEXSZ;
} else /* ADDED, IGNORED, UNTRACKED */ {
delta->new_file.mode = entry->mode;
delta->new_file.size = entry->file_size;
delta->new_file.flags |= GIT_DIFF_FLAG_EXISTS;
git_oid_cpy(&delta->new_file.id, &entry->id);
delta->new_file.id_abbrev = GIT_OID_HEXSZ;
}
delta->old_file.flags |= GIT_DIFF_FLAG_VALID_ID;
if (has_old || !git_oid_is_zero(&delta->new_file.id))
delta->new_file.flags |= GIT_DIFF_FLAG_VALID_ID;
return diff_insert_delta(diff, delta, matched_pathspec);
}
static int diff_delta__from_two(
git_diff_generated *diff,
git_delta_t status,
const git_index_entry *old_entry,
uint32_t old_mode,
const git_index_entry *new_entry,
uint32_t new_mode,
const git_oid *new_id,
const char *matched_pathspec)
{
const git_oid *old_id = &old_entry->id;
git_diff_delta *delta;
const char *canonical_path = old_entry->path;
if (status == GIT_DELTA_UNMODIFIED &&
DIFF_FLAG_ISNT_SET(diff, GIT_DIFF_INCLUDE_UNMODIFIED))
return 0;
if (!new_id)
new_id = &new_entry->id;
if (DIFF_FLAG_IS_SET(diff, GIT_DIFF_REVERSE)) {
uint32_t temp_mode = old_mode;
const git_index_entry *temp_entry = old_entry;
const git_oid *temp_id = old_id;
old_entry = new_entry;
new_entry = temp_entry;
old_mode = new_mode;
new_mode = temp_mode;
old_id = new_id;
new_id = temp_id;
}
delta = diff_delta__alloc(diff, status, canonical_path);
GIT_ERROR_CHECK_ALLOC(delta);
delta->nfiles = 2;
if (!git_index_entry_is_conflict(old_entry)) {
delta->old_file.size = old_entry->file_size;
delta->old_file.mode = old_mode;
git_oid_cpy(&delta->old_file.id, old_id);
delta->old_file.id_abbrev = GIT_OID_HEXSZ;
delta->old_file.flags |= GIT_DIFF_FLAG_VALID_ID |
GIT_DIFF_FLAG_EXISTS;
}
if (!git_index_entry_is_conflict(new_entry)) {
git_oid_cpy(&delta->new_file.id, new_id);
delta->new_file.id_abbrev = GIT_OID_HEXSZ;
delta->new_file.size = new_entry->file_size;
delta->new_file.mode = new_mode;
delta->old_file.flags |= GIT_DIFF_FLAG_EXISTS;
delta->new_file.flags |= GIT_DIFF_FLAG_EXISTS;
if (!git_oid_is_zero(&new_entry->id))
delta->new_file.flags |= GIT_DIFF_FLAG_VALID_ID;
}
return diff_insert_delta(diff, delta, matched_pathspec);
}
static git_diff_delta *diff_delta__last_for_item(
git_diff_generated *diff,
const git_index_entry *item)
{
git_diff_delta *delta = git_vector_last(&diff->base.deltas);
if (!delta)
return NULL;
switch (delta->status) {
case GIT_DELTA_UNMODIFIED:
case GIT_DELTA_DELETED:
if (git_oid__cmp(&delta->old_file.id, &item->id) == 0)
return delta;
break;
case GIT_DELTA_ADDED:
if (git_oid__cmp(&delta->new_file.id, &item->id) == 0)
return delta;
break;
case GIT_DELTA_UNREADABLE:
case GIT_DELTA_UNTRACKED:
if (diff->base.strcomp(delta->new_file.path, item->path) == 0 &&
git_oid__cmp(&delta->new_file.id, &item->id) == 0)
return delta;
break;
case GIT_DELTA_MODIFIED:
if (git_oid__cmp(&delta->old_file.id, &item->id) == 0 ||
(delta->new_file.mode == item->mode &&
git_oid__cmp(&delta->new_file.id, &item->id) == 0))
return delta;
break;
default:
break;
}
return NULL;
}
static char *diff_strdup_prefix(git_pool *pool, const char *prefix)
{
size_t len = strlen(prefix);
/* append '/' at end if needed */
if (len > 0 && prefix[len - 1] != '/')
return git_pool_strcat(pool, prefix, "/");
else
return git_pool_strndup(pool, prefix, len + 1);
}
GIT_INLINE(const char *) diff_delta__i2w_path(const git_diff_delta *delta)
{
return delta->old_file.path ?
delta->old_file.path : delta->new_file.path;
}
static int diff_delta_i2w_cmp(const void *a, const void *b)
{
const git_diff_delta *da = a, *db = b;
int val = strcmp(diff_delta__i2w_path(da), diff_delta__i2w_path(db));
return val ? val : ((int)da->status - (int)db->status);
}
static int diff_delta_i2w_casecmp(const void *a, const void *b)
{
const git_diff_delta *da = a, *db = b;
int val = strcasecmp(diff_delta__i2w_path(da), diff_delta__i2w_path(db));
return val ? val : ((int)da->status - (int)db->status);
}
bool git_diff_delta__should_skip(
const git_diff_options *opts, const git_diff_delta *delta)
{
uint32_t flags = opts ? opts->flags : 0;
if (delta->status == GIT_DELTA_UNMODIFIED &&
(flags & GIT_DIFF_INCLUDE_UNMODIFIED) == 0)
return true;
if (delta->status == GIT_DELTA_IGNORED &&
(flags & GIT_DIFF_INCLUDE_IGNORED) == 0)
return true;
if (delta->status == GIT_DELTA_UNTRACKED &&
(flags & GIT_DIFF_INCLUDE_UNTRACKED) == 0)
return true;
if (delta->status == GIT_DELTA_UNREADABLE &&
(flags & GIT_DIFF_INCLUDE_UNREADABLE) == 0)
return true;
return false;
}
static const char *diff_mnemonic_prefix(
git_iterator_t type, bool left_side)
{
const char *pfx = "";
switch (type) {
case GIT_ITERATOR_EMPTY: pfx = "c"; break;
case GIT_ITERATOR_TREE: pfx = "c"; break;
case GIT_ITERATOR_INDEX: pfx = "i"; break;
case GIT_ITERATOR_WORKDIR: pfx = "w"; break;
case GIT_ITERATOR_FS: pfx = left_side ? "1" : "2"; break;
default: break;
}
/* note: without a deeper look at pathspecs, there is no easy way
* to get the (o)bject / (w)ork tree mnemonics working...
*/
return pfx;
}
static void diff_set_ignore_case(git_diff *diff, bool ignore_case)
{
if (!ignore_case) {
diff->opts.flags &= ~GIT_DIFF_IGNORE_CASE;
diff->strcomp = git__strcmp;
diff->strncomp = git__strncmp;
diff->pfxcomp = git__prefixcmp;
diff->entrycomp = git_diff__entry_cmp;
git_vector_set_cmp(&diff->deltas, git_diff_delta__cmp);
} else {
diff->opts.flags |= GIT_DIFF_IGNORE_CASE;
diff->strcomp = git__strcasecmp;
diff->strncomp = git__strncasecmp;
diff->pfxcomp = git__prefixcmp_icase;
diff->entrycomp = git_diff__entry_icmp;
git_vector_set_cmp(&diff->deltas, git_diff_delta__casecmp);
}
git_vector_sort(&diff->deltas);
}
static void diff_generated_free(git_diff *d)
{
git_diff_generated *diff = (git_diff_generated *)d;
git_attr_session__free(&diff->base.attrsession);
git_vector_free_deep(&diff->base.deltas);
git_pathspec__vfree(&diff->pathspec);
git_pool_clear(&diff->base.pool);
git__memzero(diff, sizeof(*diff));
git__free(diff);
}
static git_diff_generated *diff_generated_alloc(
git_repository *repo,
git_iterator *old_iter,
git_iterator *new_iter)
{
git_diff_generated *diff;
git_diff_options dflt = GIT_DIFF_OPTIONS_INIT;
GIT_ASSERT_ARG_WITH_RETVAL(repo, NULL);
GIT_ASSERT_ARG_WITH_RETVAL(old_iter, NULL);
GIT_ASSERT_ARG_WITH_RETVAL(new_iter, NULL);
if ((diff = git__calloc(1, sizeof(git_diff_generated))) == NULL)
return NULL;
GIT_REFCOUNT_INC(&diff->base);
diff->base.type = GIT_DIFF_TYPE_GENERATED;
diff->base.repo = repo;
diff->base.old_src = old_iter->type;
diff->base.new_src = new_iter->type;
diff->base.patch_fn = git_patch_generated_from_diff;
diff->base.free_fn = diff_generated_free;
git_attr_session__init(&diff->base.attrsession, repo);
memcpy(&diff->base.opts, &dflt, sizeof(git_diff_options));
if (git_pool_init(&diff->base.pool, 1) < 0 ||
git_vector_init(&diff->base.deltas, 0, git_diff_delta__cmp) < 0) {
git_diff_free(&diff->base);
return NULL;
}
/* Use case-insensitive compare if either iterator has
* the ignore_case bit set */
diff_set_ignore_case(
&diff->base,
git_iterator_ignore_case(old_iter) ||
git_iterator_ignore_case(new_iter));
return diff;
}
static int diff_generated_apply_options(
git_diff_generated *diff,
const git_diff_options *opts)
{
git_config *cfg = NULL;
git_repository *repo = diff->base.repo;
git_pool *pool = &diff->base.pool;
int val;
if (opts) {
/* copy user options (except case sensitivity info from iterators) */
bool icase = DIFF_FLAG_IS_SET(diff, GIT_DIFF_IGNORE_CASE);
memcpy(&diff->base.opts, opts, sizeof(diff->base.opts));
DIFF_FLAG_SET(diff, GIT_DIFF_IGNORE_CASE, icase);
/* initialize pathspec from options */
if (git_pathspec__vinit(&diff->pathspec, &opts->pathspec, pool) < 0)
return -1;
}
/* flag INCLUDE_TYPECHANGE_TREES implies INCLUDE_TYPECHANGE */
if (DIFF_FLAG_IS_SET(diff, GIT_DIFF_INCLUDE_TYPECHANGE_TREES))
diff->base.opts.flags |= GIT_DIFF_INCLUDE_TYPECHANGE;
/* flag INCLUDE_UNTRACKED_CONTENT implies INCLUDE_UNTRACKED */
if (DIFF_FLAG_IS_SET(diff, GIT_DIFF_SHOW_UNTRACKED_CONTENT))
diff->base.opts.flags |= GIT_DIFF_INCLUDE_UNTRACKED;
/* load config values that affect diff behavior */
if ((val = git_repository_config_snapshot(&cfg, repo)) < 0)
return val;
if (!git_config__configmap_lookup(&val, cfg, GIT_CONFIGMAP_SYMLINKS) && val)
diff->diffcaps |= GIT_DIFFCAPS_HAS_SYMLINKS;
if (!git_config__configmap_lookup(&val, cfg, GIT_CONFIGMAP_IGNORESTAT) && val)
diff->diffcaps |= GIT_DIFFCAPS_IGNORE_STAT;
if ((diff->base.opts.flags & GIT_DIFF_IGNORE_FILEMODE) == 0 &&
!git_config__configmap_lookup(&val, cfg, GIT_CONFIGMAP_FILEMODE) && val)
diff->diffcaps |= GIT_DIFFCAPS_TRUST_MODE_BITS;
if (!git_config__configmap_lookup(&val, cfg, GIT_CONFIGMAP_TRUSTCTIME) && val)
diff->diffcaps |= GIT_DIFFCAPS_TRUST_CTIME;
/* Don't set GIT_DIFFCAPS_USE_DEV - compile time option in core git */
/* If not given explicit `opts`, check `diff.xyz` configs */
if (!opts) {
int context = git_config__get_int_force(cfg, "diff.context", 3);
diff->base.opts.context_lines = context >= 0 ? (uint32_t)context : 3;
/* add other defaults here */
}
/* Reverse src info if diff is reversed */
if (DIFF_FLAG_IS_SET(diff, GIT_DIFF_REVERSE)) {
git_iterator_t tmp_src = diff->base.old_src;
diff->base.old_src = diff->base.new_src;
diff->base.new_src = tmp_src;
}
/* Unset UPDATE_INDEX unless diffing workdir and index */
if (DIFF_FLAG_IS_SET(diff, GIT_DIFF_UPDATE_INDEX) &&
(!(diff->base.old_src == GIT_ITERATOR_WORKDIR ||
diff->base.new_src == GIT_ITERATOR_WORKDIR) ||
!(diff->base.old_src == GIT_ITERATOR_INDEX ||
diff->base.new_src == GIT_ITERATOR_INDEX)))
diff->base.opts.flags &= ~GIT_DIFF_UPDATE_INDEX;
/* if ignore_submodules not explicitly set, check diff config */
if (diff->base.opts.ignore_submodules <= 0) {
git_config_entry *entry;
git_config__lookup_entry(&entry, cfg, "diff.ignoresubmodules", true);
if (entry && git_submodule_parse_ignore(
&diff->base.opts.ignore_submodules, entry->value) < 0)
git_error_clear();
git_config_entry_free(entry);
}
/* if either prefix is not set, figure out appropriate value */
if (!diff->base.opts.old_prefix || !diff->base.opts.new_prefix) {
const char *use_old = DIFF_OLD_PREFIX_DEFAULT;
const char *use_new = DIFF_NEW_PREFIX_DEFAULT;
if (git_config__get_bool_force(cfg, "diff.noprefix", 0))
use_old = use_new = "";
else if (git_config__get_bool_force(cfg, "diff.mnemonicprefix", 0)) {
use_old = diff_mnemonic_prefix(diff->base.old_src, true);
use_new = diff_mnemonic_prefix(diff->base.new_src, false);
}
if (!diff->base.opts.old_prefix)
diff->base.opts.old_prefix = use_old;
if (!diff->base.opts.new_prefix)
diff->base.opts.new_prefix = use_new;
}
/* strdup prefix from pool so we're not dependent on external data */
diff->base.opts.old_prefix = diff_strdup_prefix(pool, diff->base.opts.old_prefix);
diff->base.opts.new_prefix = diff_strdup_prefix(pool, diff->base.opts.new_prefix);
if (DIFF_FLAG_IS_SET(diff, GIT_DIFF_REVERSE)) {
const char *tmp_prefix = diff->base.opts.old_prefix;
diff->base.opts.old_prefix = diff->base.opts.new_prefix;
diff->base.opts.new_prefix = tmp_prefix;
}
git_config_free(cfg);
/* check strdup results for error */
return (!diff->base.opts.old_prefix || !diff->base.opts.new_prefix) ? -1 : 0;
}
int git_diff__oid_for_file(
git_oid *out,
git_diff *diff,
const char *path,
uint16_t mode,
git_object_size_t size)
{
git_index_entry entry;
if (size > UINT32_MAX) {
git_error_set(GIT_ERROR_NOMEMORY, "file size overflow (for 32-bits) on '%s'", path);
return -1;
}
memset(&entry, 0, sizeof(entry));
entry.mode = mode;
entry.file_size = (uint32_t)size;
entry.path = (char *)path;
return git_diff__oid_for_entry(out, diff, &entry, mode, NULL);
}
int git_diff__oid_for_entry(
git_oid *out,
git_diff *d,
const git_index_entry *src,
uint16_t mode,
const git_oid *update_match)
{
git_diff_generated *diff;
git_buf full_path = GIT_BUF_INIT;
git_index_entry entry = *src;
git_filter_list *fl = NULL;
int error = 0;
GIT_ASSERT(d->type == GIT_DIFF_TYPE_GENERATED);
diff = (git_diff_generated *)d;
memset(out, 0, sizeof(*out));
if (git_repository_workdir_path(&full_path, diff->base.repo, entry.path) < 0)
return -1;
if (!mode) {
struct stat st;
diff->base.perf.stat_calls++;
if (p_stat(full_path.ptr, &st) < 0) {
error = git_path_set_error(errno, entry.path, "stat");
git_buf_dispose(&full_path);
return error;
}
git_index_entry__init_from_stat(&entry,
&st, (diff->diffcaps & GIT_DIFFCAPS_TRUST_MODE_BITS) != 0);
}
/* calculate OID for file if possible */
if (S_ISGITLINK(mode)) {
git_submodule *sm;
if (!git_submodule_lookup(&sm, diff->base.repo, entry.path)) {
const git_oid *sm_oid = git_submodule_wd_id(sm);
if (sm_oid)
git_oid_cpy(out, sm_oid);
git_submodule_free(sm);
} else {
/* if submodule lookup failed probably just in an intermediate
* state where some init hasn't happened, so ignore the error
*/
git_error_clear();
}
} else if (S_ISLNK(mode)) {
error = git_odb__hashlink(out, full_path.ptr);
diff->base.perf.oid_calculations++;
} else if (!git__is_sizet(entry.file_size)) {
git_error_set(GIT_ERROR_NOMEMORY, "file size overflow (for 32-bits) on '%s'",
entry.path);
error = -1;
} else if (!(error = git_filter_list_load(&fl,
diff->base.repo, NULL, entry.path,
GIT_FILTER_TO_ODB, GIT_FILTER_ALLOW_UNSAFE)))
{
int fd = git_futils_open_ro(full_path.ptr);
if (fd < 0)
error = fd;
else {
error = git_odb__hashfd_filtered(
out, fd, (size_t)entry.file_size, GIT_OBJECT_BLOB, fl);
p_close(fd);
diff->base.perf.oid_calculations++;
}
git_filter_list_free(fl);
}
/* update index for entry if requested */
if (!error && update_match && git_oid_equal(out, update_match)) {
git_index *idx;
git_index_entry updated_entry;
memcpy(&updated_entry, &entry, sizeof(git_index_entry));
updated_entry.mode = mode;
git_oid_cpy(&updated_entry.id, out);
if (!(error = git_repository_index__weakptr(&idx,
diff->base.repo))) {
error = git_index_add(idx, &updated_entry);
diff->index_updated = true;
}
}
git_buf_dispose(&full_path);
return error;
}
typedef struct {
git_repository *repo;
git_iterator *old_iter;
git_iterator *new_iter;
const git_index_entry *oitem;
const git_index_entry *nitem;
git_strmap *submodule_cache;
bool submodule_cache_initialized;
} diff_in_progress;
#define MODE_BITS_MASK 0000777
static int maybe_modified_submodule(
git_delta_t *status,
git_oid *found_oid,
git_diff_generated *diff,
diff_in_progress *info)
{
int error = 0;
git_submodule *sub;
unsigned int sm_status = 0;
git_submodule_ignore_t ign = diff->base.opts.ignore_submodules;
git_strmap *submodule_cache = NULL;
*status = GIT_DELTA_UNMODIFIED;
if (DIFF_FLAG_IS_SET(diff, GIT_DIFF_IGNORE_SUBMODULES) ||
ign == GIT_SUBMODULE_IGNORE_ALL)
return 0;
if (diff->base.repo->submodule_cache != NULL) {
submodule_cache = diff->base.repo->submodule_cache;
} else {
if (!info->submodule_cache_initialized) {
info->submodule_cache_initialized = true;
/*
* Try to cache the submodule information to avoid having to parse it for
* every submodule. It is okay if it fails, the cache will still be NULL
* and the submodules will be attempted to be looked up individually.
*/
git_submodule_cache_init(&info->submodule_cache, diff->base.repo);
}
submodule_cache = info->submodule_cache;
}
if ((error = git_submodule__lookup_with_cache(
&sub, diff->base.repo, info->nitem->path, submodule_cache)) < 0) {
/* GIT_EEXISTS means dir with .git in it was found - ignore it */
if (error == GIT_EEXISTS) {
git_error_clear();
error = 0;
}
return error;
}
if (ign <= 0 && git_submodule_ignore(sub) == GIT_SUBMODULE_IGNORE_ALL)
/* ignore it */;
else if ((error = git_submodule__status(
&sm_status, NULL, NULL, found_oid, sub, ign)) < 0)
/* return error below */;
/* check IS_WD_UNMODIFIED because this case is only used
* when the new side of the diff is the working directory
*/
else if (!GIT_SUBMODULE_STATUS_IS_WD_UNMODIFIED(sm_status))
*status = GIT_DELTA_MODIFIED;
/* now that we have a HEAD OID, check if HEAD moved */
else if ((sm_status & GIT_SUBMODULE_STATUS_IN_WD) != 0 &&
!git_oid_equal(&info->oitem->id, found_oid))
*status = GIT_DELTA_MODIFIED;
git_submodule_free(sub);
return error;
}
static int maybe_modified(
git_diff_generated *diff,
diff_in_progress *info)
{
git_oid noid;
git_delta_t status = GIT_DELTA_MODIFIED;
const git_index_entry *oitem = info->oitem;
const git_index_entry *nitem = info->nitem;
unsigned int omode = oitem->mode;
unsigned int nmode = nitem->mode;
bool new_is_workdir = (info->new_iter->type == GIT_ITERATOR_WORKDIR);
bool modified_uncertain = false;
const char *matched_pathspec;
int error = 0;
if (!diff_pathspec_match(&matched_pathspec, diff, oitem))
return 0;
memset(&noid, 0, sizeof(noid));
/* on platforms with no symlinks, preserve mode of existing symlinks */
if (S_ISLNK(omode) && S_ISREG(nmode) && new_is_workdir &&
!(diff->diffcaps & GIT_DIFFCAPS_HAS_SYMLINKS))
nmode = omode;
/* on platforms with no execmode, just preserve old mode */
if (!(diff->diffcaps & GIT_DIFFCAPS_TRUST_MODE_BITS) &&
(nmode & MODE_BITS_MASK) != (omode & MODE_BITS_MASK) &&
new_is_workdir)
nmode = (nmode & ~MODE_BITS_MASK) | (omode & MODE_BITS_MASK);
/* if one side is a conflict, mark the whole delta as conflicted */
if (git_index_entry_is_conflict(oitem) ||
git_index_entry_is_conflict(nitem)) {
status = GIT_DELTA_CONFLICTED;
/* support "assume unchanged" (poorly, b/c we still stat everything) */
} else if ((oitem->flags & GIT_INDEX_ENTRY_VALID) != 0) {
status = GIT_DELTA_UNMODIFIED;
/* support "skip worktree" index bit */
} else if ((oitem->flags_extended & GIT_INDEX_ENTRY_SKIP_WORKTREE) != 0) {
status = GIT_DELTA_UNMODIFIED;
/* if basic type of file changed, then split into delete and add */
} else if (GIT_MODE_TYPE(omode) != GIT_MODE_TYPE(nmode)) {
if (DIFF_FLAG_IS_SET(diff, GIT_DIFF_INCLUDE_TYPECHANGE)) {
status = GIT_DELTA_TYPECHANGE;
}
else if (nmode == GIT_FILEMODE_UNREADABLE) {
if (!(error = diff_delta__from_one(diff, GIT_DELTA_DELETED, oitem, NULL)))
error = diff_delta__from_one(diff, GIT_DELTA_UNREADABLE, NULL, nitem);
return error;
}
else {
if (!(error = diff_delta__from_one(diff, GIT_DELTA_DELETED, oitem, NULL)))
error = diff_delta__from_one(diff, GIT_DELTA_ADDED, NULL, nitem);
return error;
}
/* if oids and modes match (and are valid), then file is unmodified */
} else if (git_oid_equal(&oitem->id, &nitem->id) &&
omode == nmode &&
!git_oid_is_zero(&oitem->id)) {
status = GIT_DELTA_UNMODIFIED;
/* if we have an unknown OID and a workdir iterator, then check some
* circumstances that can accelerate things or need special handling
*/
} else if (git_oid_is_zero(&nitem->id) && new_is_workdir) {
bool use_ctime =
((diff->diffcaps & GIT_DIFFCAPS_TRUST_CTIME) != 0);
git_index *index = git_iterator_index(info->new_iter);
status = GIT_DELTA_UNMODIFIED;
if (S_ISGITLINK(nmode)) {
if ((error = maybe_modified_submodule(&status, &noid, diff, info)) < 0)
return error;
}
/* if the stat data looks different, then mark modified - this just
* means that the OID will be recalculated below to confirm change
*/
else if (omode != nmode || oitem->file_size != nitem->file_size) {
status = GIT_DELTA_MODIFIED;
modified_uncertain =
(oitem->file_size <= 0 && nitem->file_size > 0);
}
else if (!git_index_time_eq(&oitem->mtime, &nitem->mtime) ||
(use_ctime && !git_index_time_eq(&oitem->ctime, &nitem->ctime)) ||
oitem->ino != nitem->ino ||
oitem->uid != nitem->uid ||
oitem->gid != nitem->gid ||
git_index_entry_newer_than_index(nitem, index))
{
status = GIT_DELTA_MODIFIED;
modified_uncertain = true;
}
/* if mode is GITLINK and submodules are ignored, then skip */
} else if (S_ISGITLINK(nmode) &&
DIFF_FLAG_IS_SET(diff, GIT_DIFF_IGNORE_SUBMODULES)) {
status = GIT_DELTA_UNMODIFIED;
}
/* if we got here and decided that the files are modified, but we
* haven't calculated the OID of the new item, then calculate it now
*/
if (modified_uncertain && git_oid_is_zero(&nitem->id)) {
const git_oid *update_check =
DIFF_FLAG_IS_SET(diff, GIT_DIFF_UPDATE_INDEX) && omode == nmode ?
&oitem->id : NULL;
if ((error = git_diff__oid_for_entry(
&noid, &diff->base, nitem, nmode, update_check)) < 0)
return error;
/* if oid matches, then mark unmodified (except submodules, where
* the filesystem content may be modified even if the oid still
* matches between the index and the workdir HEAD)
*/
if (omode == nmode && !S_ISGITLINK(omode) &&
git_oid_equal(&oitem->id, &noid))
status = GIT_DELTA_UNMODIFIED;
}
/* If we want case changes, then break this into a delete of the old
* and an add of the new so that consumers can act accordingly (eg,
* checkout will update the case on disk.)
*/
if (DIFF_FLAG_IS_SET(diff, GIT_DIFF_IGNORE_CASE) &&
DIFF_FLAG_IS_SET(diff, GIT_DIFF_INCLUDE_CASECHANGE) &&
strcmp(oitem->path, nitem->path) != 0) {
if (!(error = diff_delta__from_one(diff, GIT_DELTA_DELETED, oitem, NULL)))
error = diff_delta__from_one(diff, GIT_DELTA_ADDED, NULL, nitem);
return error;
}
return diff_delta__from_two(
diff, status, oitem, omode, nitem, nmode,
git_oid_is_zero(&noid) ? NULL : &noid, matched_pathspec);
}
static bool entry_is_prefixed(
git_diff_generated *diff,
const git_index_entry *item,
const git_index_entry *prefix_item)
{
size_t pathlen;
if (!item || diff->base.pfxcomp(item->path, prefix_item->path) != 0)
return false;
pathlen = strlen(prefix_item->path);
return (prefix_item->path[pathlen - 1] == '/' ||
item->path[pathlen] == '\0' ||
item->path[pathlen] == '/');
}
static int iterator_current(
const git_index_entry **entry,
git_iterator *iterator)
{
int error;
if ((error = git_iterator_current(entry, iterator)) == GIT_ITEROVER) {
*entry = NULL;
error = 0;
}
return error;
}
static int iterator_advance(
const git_index_entry **entry,
git_iterator *iterator)
{
const git_index_entry *prev_entry = *entry;
int cmp, error;
/* if we're looking for conflicts, we only want to report
* one conflict for each file, instead of all three sides.
* so if this entry is a conflict for this file, and the
* previous one was a conflict for the same file, skip it.
*/
while ((error = git_iterator_advance(entry, iterator)) == 0) {
if (!(iterator->flags & GIT_ITERATOR_INCLUDE_CONFLICTS) ||
!git_index_entry_is_conflict(prev_entry) ||
!git_index_entry_is_conflict(*entry))
break;
cmp = (iterator->flags & GIT_ITERATOR_IGNORE_CASE) ?
strcasecmp(prev_entry->path, (*entry)->path) :
strcmp(prev_entry->path, (*entry)->path);
if (cmp)
break;
}
if (error == GIT_ITEROVER) {
*entry = NULL;
error = 0;
}
return error;
}
static int iterator_advance_into(
const git_index_entry **entry,
git_iterator *iterator)
{
int error;
if ((error = git_iterator_advance_into(entry, iterator)) == GIT_ITEROVER) {
*entry = NULL;
error = 0;
}
return error;
}
static int iterator_advance_over(
const git_index_entry **entry,
git_iterator_status_t *status,
git_iterator *iterator)
{
int error = git_iterator_advance_over(entry, status, iterator);
if (error == GIT_ITEROVER) {
*entry = NULL;
error = 0;
}
return error;
}
static int handle_unmatched_new_item(
git_diff_generated *diff, diff_in_progress *info)
{
int error = 0;
const git_index_entry *nitem = info->nitem;
git_delta_t delta_type = GIT_DELTA_UNTRACKED;
bool contains_oitem;
/* check if this is a prefix of the other side */
contains_oitem = entry_is_prefixed(diff, info->oitem, nitem);
/* update delta_type if this item is conflicted */
if (git_index_entry_is_conflict(nitem))
delta_type = GIT_DELTA_CONFLICTED;
/* update delta_type if this item is ignored */
else if (git_iterator_current_is_ignored(info->new_iter))
delta_type = GIT_DELTA_IGNORED;
if (nitem->mode == GIT_FILEMODE_TREE) {
bool recurse_into_dir = contains_oitem;
/* check if user requests recursion into this type of dir */
recurse_into_dir = contains_oitem ||
(delta_type == GIT_DELTA_UNTRACKED &&
DIFF_FLAG_IS_SET(diff, GIT_DIFF_RECURSE_UNTRACKED_DIRS)) ||
(delta_type == GIT_DELTA_IGNORED &&
DIFF_FLAG_IS_SET(diff, GIT_DIFF_RECURSE_IGNORED_DIRS));
/* do not advance into directories that contain a .git file */
if (recurse_into_dir && !contains_oitem) {
git_buf *full = NULL;
if (git_iterator_current_workdir_path(&full, info->new_iter) < 0)
return -1;
if (full && git_path_contains(full, DOT_GIT)) {
/* TODO: warning if not a valid git repository */
recurse_into_dir = false;
}
}
/* still have to look into untracked directories to match core git -
* with no untracked files, directory is treated as ignored
*/
if (!recurse_into_dir &&
delta_type == GIT_DELTA_UNTRACKED &&
DIFF_FLAG_ISNT_SET(diff, GIT_DIFF_ENABLE_FAST_UNTRACKED_DIRS))
{
git_diff_delta *last;
git_iterator_status_t untracked_state;
/* attempt to insert record for this directory */
if ((error = diff_delta__from_one(diff, delta_type, NULL, nitem)) != 0)
return error;
/* if delta wasn't created (because of rules), just skip ahead */
last = diff_delta__last_for_item(diff, nitem);
if (!last)
return iterator_advance(&info->nitem, info->new_iter);
/* iterate into dir looking for an actual untracked file */
if ((error = iterator_advance_over(
&info->nitem, &untracked_state, info->new_iter)) < 0)
return error;
/* if we found nothing that matched our pathlist filter, exclude */
if (untracked_state == GIT_ITERATOR_STATUS_FILTERED) {
git_vector_pop(&diff->base.deltas);
git__free(last);
}
/* if we found nothing or just ignored items, update the record */
if (untracked_state == GIT_ITERATOR_STATUS_IGNORED ||
untracked_state == GIT_ITERATOR_STATUS_EMPTY) {
last->status = GIT_DELTA_IGNORED;
/* remove the record if we don't want ignored records */
if (DIFF_FLAG_ISNT_SET(diff, GIT_DIFF_INCLUDE_IGNORED)) {
git_vector_pop(&diff->base.deltas);
git__free(last);
}
}
return 0;
}
/* try to advance into directory if necessary */
if (recurse_into_dir) {
error = iterator_advance_into(&info->nitem, info->new_iter);
/* if directory is empty, can't advance into it, so skip it */
if (error == GIT_ENOTFOUND) {
git_error_clear();
error = iterator_advance(&info->nitem, info->new_iter);
}
return error;
}
}
else if (delta_type == GIT_DELTA_IGNORED &&
DIFF_FLAG_ISNT_SET(diff, GIT_DIFF_RECURSE_IGNORED_DIRS) &&
git_iterator_current_tree_is_ignored(info->new_iter))
/* item contained in ignored directory, so skip over it */
return iterator_advance(&info->nitem, info->new_iter);
else if (info->new_iter->type != GIT_ITERATOR_WORKDIR) {
if (delta_type != GIT_DELTA_CONFLICTED)
delta_type = GIT_DELTA_ADDED;
}
else if (nitem->mode == GIT_FILEMODE_COMMIT) {
/* ignore things that are not actual submodules */
if (git_submodule_lookup(NULL, info->repo, nitem->path) != 0) {
git_error_clear();
delta_type = GIT_DELTA_IGNORED;
/* if this contains a tracked item, treat as normal TREE */
if (contains_oitem) {
error = iterator_advance_into(&info->nitem, info->new_iter);
if (error != GIT_ENOTFOUND)
return error;
git_error_clear();
return iterator_advance(&info->nitem, info->new_iter);
}
}
}
else if (nitem->mode == GIT_FILEMODE_UNREADABLE) {
if (DIFF_FLAG_IS_SET(diff, GIT_DIFF_INCLUDE_UNREADABLE_AS_UNTRACKED))
delta_type = GIT_DELTA_UNTRACKED;
else
delta_type = GIT_DELTA_UNREADABLE;
}
/* Actually create the record for this item if necessary */
if ((error = diff_delta__from_one(diff, delta_type, NULL, nitem)) != 0)
return error;
/* If user requested TYPECHANGE records, then check for that instead of
* just generating an ADDED/UNTRACKED record
*/
if (delta_type != GIT_DELTA_IGNORED &&
DIFF_FLAG_IS_SET(diff, GIT_DIFF_INCLUDE_TYPECHANGE_TREES) &&
contains_oitem)
{
/* this entry was prefixed with a tree - make TYPECHANGE */
git_diff_delta *last = diff_delta__last_for_item(diff, nitem);
if (last) {
last->status = GIT_DELTA_TYPECHANGE;
last->old_file.mode = GIT_FILEMODE_TREE;
}
}
return iterator_advance(&info->nitem, info->new_iter);
}
static int handle_unmatched_old_item(
git_diff_generated *diff, diff_in_progress *info)
{
git_delta_t delta_type = GIT_DELTA_DELETED;
int error;
/* update delta_type if this item is conflicted */
if (git_index_entry_is_conflict(info->oitem))
delta_type = GIT_DELTA_CONFLICTED;
if ((error = diff_delta__from_one(diff, delta_type, info->oitem, NULL)) < 0)
return error;
/* if we are generating TYPECHANGE records then check for that
* instead of just generating a DELETE record
*/
if (DIFF_FLAG_IS_SET(diff, GIT_DIFF_INCLUDE_TYPECHANGE_TREES) &&
entry_is_prefixed(diff, info->nitem, info->oitem))
{
/* this entry has become a tree! convert to TYPECHANGE */
git_diff_delta *last = diff_delta__last_for_item(diff, info->oitem);
if (last) {
last->status = GIT_DELTA_TYPECHANGE;
last->new_file.mode = GIT_FILEMODE_TREE;
}
/* If new_iter is a workdir iterator, then this situation
* will certainly be followed by a series of untracked items.
* Unless RECURSE_UNTRACKED_DIRS is set, skip over them...
*/
if (S_ISDIR(info->nitem->mode) &&
DIFF_FLAG_ISNT_SET(diff, GIT_DIFF_RECURSE_UNTRACKED_DIRS))
return iterator_advance(&info->nitem, info->new_iter);
}
return iterator_advance(&info->oitem, info->old_iter);
}
static int handle_matched_item(
git_diff_generated *diff, diff_in_progress *info)
{
int error = 0;
if ((error = maybe_modified(diff, info)) < 0)
return error;
if (!(error = iterator_advance(&info->oitem, info->old_iter)))
error = iterator_advance(&info->nitem, info->new_iter);
return error;
}
int git_diff__from_iterators(
git_diff **out,
git_repository *repo,
git_iterator *old_iter,
git_iterator *new_iter,
const git_diff_options *opts)
{
git_diff_generated *diff;
diff_in_progress info = {0};
int error = 0;
*out = NULL;
diff = diff_generated_alloc(repo, old_iter, new_iter);
GIT_ERROR_CHECK_ALLOC(diff);
info.repo = repo;
info.old_iter = old_iter;
info.new_iter = new_iter;
/* make iterators have matching icase behavior */
if (DIFF_FLAG_IS_SET(diff, GIT_DIFF_IGNORE_CASE)) {
if ((error = git_iterator_set_ignore_case(old_iter, true)) < 0 ||
(error = git_iterator_set_ignore_case(new_iter, true)) < 0)
goto cleanup;
}
/* finish initialization */
if ((error = diff_generated_apply_options(diff, opts)) < 0)
goto cleanup;
if ((error = iterator_current(&info.oitem, old_iter)) < 0 ||
(error = iterator_current(&info.nitem, new_iter)) < 0)
goto cleanup;
/* run iterators building diffs */
while (!error && (info.oitem || info.nitem)) {
int cmp;
/* report progress */
if (opts && opts->progress_cb) {
if ((error = opts->progress_cb(&diff->base,
info.oitem ? info.oitem->path : NULL,
info.nitem ? info.nitem->path : NULL,
opts->payload)))
break;
}
cmp = info.oitem ?
(info.nitem ? diff->base.entrycomp(info.oitem, info.nitem) : -1) : 1;
/* create DELETED records for old items not matched in new */
if (cmp < 0)
error = handle_unmatched_old_item(diff, &info);
/* create ADDED, TRACKED, or IGNORED records for new items not
* matched in old (and/or descend into directories as needed)
*/
else if (cmp > 0)
error = handle_unmatched_new_item(diff, &info);
/* otherwise item paths match, so create MODIFIED record
* (or ADDED and DELETED pair if type changed)
*/
else
error = handle_matched_item(diff, &info);
}
diff->base.perf.stat_calls +=
old_iter->stat_calls + new_iter->stat_calls;
cleanup:
if (!error)
*out = &diff->base;
else
git_diff_free(&diff->base);
if (info.submodule_cache)
git_submodule_cache_free(info.submodule_cache);
return error;
}
static int diff_prepare_iterator_opts(char **prefix, git_iterator_options *a, int aflags,
git_iterator_options *b, int bflags,
const git_diff_options *opts)
{
GIT_ERROR_CHECK_VERSION(opts, GIT_DIFF_OPTIONS_VERSION, "git_diff_options");
*prefix = NULL;
if (opts && (opts->flags & GIT_DIFF_DISABLE_PATHSPEC_MATCH)) {
a->pathlist.strings = opts->pathspec.strings;
a->pathlist.count = opts->pathspec.count;
b->pathlist.strings = opts->pathspec.strings;
b->pathlist.count = opts->pathspec.count;
} else if (opts) {
*prefix = git_pathspec_prefix(&opts->pathspec);
GIT_ERROR_CHECK_ALLOC(prefix);
}
a->flags = aflags;
b->flags = bflags;
a->start = b->start = *prefix;
a->end = b->end = *prefix;
return 0;
}
int git_diff_tree_to_tree(
git_diff **out,
git_repository *repo,
git_tree *old_tree,
git_tree *new_tree,
const git_diff_options *opts)
{
git_iterator_flag_t iflag = GIT_ITERATOR_DONT_IGNORE_CASE;
git_iterator_options a_opts = GIT_ITERATOR_OPTIONS_INIT,
b_opts = GIT_ITERATOR_OPTIONS_INIT;
git_iterator *a = NULL, *b = NULL;
git_diff *diff = NULL;
char *prefix = NULL;
int error = 0;
GIT_ASSERT_ARG(out);
GIT_ASSERT_ARG(repo);
*out = NULL;
/* for tree to tree diff, be case sensitive even if the index is
* currently case insensitive, unless the user explicitly asked
* for case insensitivity
*/
if (opts && (opts->flags & GIT_DIFF_IGNORE_CASE) != 0)
iflag = GIT_ITERATOR_IGNORE_CASE;
if ((error = diff_prepare_iterator_opts(&prefix, &a_opts, iflag, &b_opts, iflag, opts)) < 0 ||
(error = git_iterator_for_tree(&a, old_tree, &a_opts)) < 0 ||
(error = git_iterator_for_tree(&b, new_tree, &b_opts)) < 0 ||
(error = git_diff__from_iterators(&diff, repo, a, b, opts)) < 0)
goto out;
*out = diff;
diff = NULL;
out:
git_iterator_free(a);
git_iterator_free(b);
git_diff_free(diff);
git__free(prefix);
return error;
}
static int diff_load_index(git_index **index, git_repository *repo)
{
int error = git_repository_index__weakptr(index, repo);
/* reload the repository index when user did not pass one in */
if (!error && git_index_read(*index, false) < 0)
git_error_clear();
return error;
}
int git_diff_tree_to_index(
git_diff **out,
git_repository *repo,
git_tree *old_tree,
git_index *index,
const git_diff_options *opts)
{
git_iterator_flag_t iflag = GIT_ITERATOR_DONT_IGNORE_CASE |
GIT_ITERATOR_INCLUDE_CONFLICTS;
git_iterator_options a_opts = GIT_ITERATOR_OPTIONS_INIT,
b_opts = GIT_ITERATOR_OPTIONS_INIT;
git_iterator *a = NULL, *b = NULL;
git_diff *diff = NULL;
char *prefix = NULL;
bool index_ignore_case = false;
int error = 0;
GIT_ASSERT_ARG(out);
GIT_ASSERT_ARG(repo);
*out = NULL;
if (!index && (error = diff_load_index(&index, repo)) < 0)
return error;
index_ignore_case = index->ignore_case;
if ((error = diff_prepare_iterator_opts(&prefix, &a_opts, iflag, &b_opts, iflag, opts)) < 0 ||
(error = git_iterator_for_tree(&a, old_tree, &a_opts)) < 0 ||
(error = git_iterator_for_index(&b, repo, index, &b_opts)) < 0 ||
(error = git_diff__from_iterators(&diff, repo, a, b, opts)) < 0)
goto out;
/* if index is in case-insensitive order, re-sort deltas to match */
if (index_ignore_case)
diff_set_ignore_case(diff, true);
*out = diff;
diff = NULL;
out:
git_iterator_free(a);
git_iterator_free(b);
git_diff_free(diff);
git__free(prefix);
return error;
}
int git_diff_index_to_workdir(
git_diff **out,
git_repository *repo,
git_index *index,
const git_diff_options *opts)
{
git_iterator_options a_opts = GIT_ITERATOR_OPTIONS_INIT,
b_opts = GIT_ITERATOR_OPTIONS_INIT;
git_iterator *a = NULL, *b = NULL;
git_diff *diff = NULL;
char *prefix = NULL;
int error = 0;
GIT_ASSERT_ARG(out);
GIT_ASSERT_ARG(repo);
*out = NULL;
if (!index && (error = diff_load_index(&index, repo)) < 0)
return error;
if ((error = diff_prepare_iterator_opts(&prefix, &a_opts, GIT_ITERATOR_INCLUDE_CONFLICTS,
&b_opts, GIT_ITERATOR_DONT_AUTOEXPAND, opts)) < 0 ||
(error = git_iterator_for_index(&a, repo, index, &a_opts)) < 0 ||
(error = git_iterator_for_workdir(&b, repo, index, NULL, &b_opts)) < 0 ||
(error = git_diff__from_iterators(&diff, repo, a, b, opts)) < 0)
goto out;
if ((diff->opts.flags & GIT_DIFF_UPDATE_INDEX) && ((git_diff_generated *)diff)->index_updated)
if ((error = git_index_write(index)) < 0)
goto out;
*out = diff;
diff = NULL;
out:
git_iterator_free(a);
git_iterator_free(b);
git_diff_free(diff);
git__free(prefix);
return error;
}
int git_diff_tree_to_workdir(
git_diff **out,
git_repository *repo,
git_tree *old_tree,
const git_diff_options *opts)
{
git_iterator_options a_opts = GIT_ITERATOR_OPTIONS_INIT,
b_opts = GIT_ITERATOR_OPTIONS_INIT;
git_iterator *a = NULL, *b = NULL;
git_diff *diff = NULL;
char *prefix = NULL;
git_index *index;
int error;
GIT_ASSERT_ARG(out);
GIT_ASSERT_ARG(repo);
*out = NULL;
if ((error = diff_prepare_iterator_opts(&prefix, &a_opts, 0,
&b_opts, GIT_ITERATOR_DONT_AUTOEXPAND, opts) < 0) ||
(error = git_repository_index__weakptr(&index, repo)) < 0 ||
(error = git_iterator_for_tree(&a, old_tree, &a_opts)) < 0 ||
(error = git_iterator_for_workdir(&b, repo, index, old_tree, &b_opts)) < 0 ||
(error = git_diff__from_iterators(&diff, repo, a, b, opts)) < 0)
goto out;
*out = diff;
diff = NULL;
out:
git_iterator_free(a);
git_iterator_free(b);
git_diff_free(diff);
git__free(prefix);
return error;
}
int git_diff_tree_to_workdir_with_index(
git_diff **out,
git_repository *repo,
git_tree *tree,
const git_diff_options *opts)
{
git_diff *d1 = NULL, *d2 = NULL;
git_index *index = NULL;
int error = 0;
GIT_ASSERT_ARG(out);
GIT_ASSERT_ARG(repo);
*out = NULL;
if ((error = diff_load_index(&index, repo)) < 0)
return error;
if (!(error = git_diff_tree_to_index(&d1, repo, tree, index, opts)) &&
!(error = git_diff_index_to_workdir(&d2, repo, index, opts)))
error = git_diff_merge(d1, d2);
git_diff_free(d2);
if (error) {
git_diff_free(d1);
d1 = NULL;
}
*out = d1;
return error;
}
int git_diff_index_to_index(
git_diff **out,
git_repository *repo,
git_index *old_index,
git_index *new_index,
const git_diff_options *opts)
{
git_iterator_options a_opts = GIT_ITERATOR_OPTIONS_INIT,
b_opts = GIT_ITERATOR_OPTIONS_INIT;
git_iterator *a = NULL, *b = NULL;
git_diff *diff = NULL;
char *prefix = NULL;
int error;
GIT_ASSERT_ARG(out);
GIT_ASSERT_ARG(old_index);
GIT_ASSERT_ARG(new_index);
*out = NULL;
if ((error = diff_prepare_iterator_opts(&prefix, &a_opts, GIT_ITERATOR_DONT_IGNORE_CASE,
&b_opts, GIT_ITERATOR_DONT_IGNORE_CASE, opts) < 0) ||
(error = git_iterator_for_index(&a, repo, old_index, &a_opts)) < 0 ||
(error = git_iterator_for_index(&b, repo, new_index, &b_opts)) < 0 ||
(error = git_diff__from_iterators(&diff, repo, a, b, opts)) < 0)
goto out;
/* if index is in case-insensitive order, re-sort deltas to match */
if (old_index->ignore_case || new_index->ignore_case)
diff_set_ignore_case(diff, true);
*out = diff;
diff = NULL;
out:
git_iterator_free(a);
git_iterator_free(b);
git_diff_free(diff);
git__free(prefix);
return error;
}
int git_diff__paired_foreach(
git_diff *head2idx,
git_diff *idx2wd,
int (*cb)(git_diff_delta *h2i, git_diff_delta *i2w, void *payload),
void *payload)
{
int cmp, error = 0;
git_diff_delta *h2i, *i2w;
size_t i, j, i_max, j_max;
int (*strcomp)(const char *, const char *) = git__strcmp;
bool h2i_icase, i2w_icase, icase_mismatch;
i_max = head2idx ? head2idx->deltas.length : 0;
j_max = idx2wd ? idx2wd->deltas.length : 0;
if (!i_max && !j_max)
return 0;
/* At some point, tree-to-index diffs will probably never ignore case,
* even if that isn't true now. Index-to-workdir diffs may or may not
* ignore case, but the index filename for the idx2wd diff should
* still be using the canonical case-preserving name.
*
* Therefore the main thing we need to do here is make sure the diffs
* are traversed in a compatible order. To do this, we temporarily
* resort a mismatched diff to get the order correct.
*
* In order to traverse renames in the index->workdir, we need to
* ensure that we compare the index name on both sides, so we
* always sort by the old name in the i2w list.
*/
h2i_icase = head2idx != NULL && git_diff_is_sorted_icase(head2idx);
i2w_icase = idx2wd != NULL && git_diff_is_sorted_icase(idx2wd);
icase_mismatch =
(head2idx != NULL && idx2wd != NULL && h2i_icase != i2w_icase);
if (icase_mismatch && h2i_icase) {
git_vector_set_cmp(&head2idx->deltas, git_diff_delta__cmp);
git_vector_sort(&head2idx->deltas);
}
if (i2w_icase && !icase_mismatch) {
strcomp = git__strcasecmp;
git_vector_set_cmp(&idx2wd->deltas, diff_delta_i2w_casecmp);
git_vector_sort(&idx2wd->deltas);
} else if (idx2wd != NULL) {
git_vector_set_cmp(&idx2wd->deltas, diff_delta_i2w_cmp);
git_vector_sort(&idx2wd->deltas);
}
for (i = 0, j = 0; i < i_max || j < j_max; ) {
h2i = head2idx ? GIT_VECTOR_GET(&head2idx->deltas, i) : NULL;
i2w = idx2wd ? GIT_VECTOR_GET(&idx2wd->deltas, j) : NULL;
cmp = !i2w ? -1 : !h2i ? 1 :
strcomp(h2i->new_file.path, i2w->old_file.path);
if (cmp < 0) {
i++; i2w = NULL;
} else if (cmp > 0) {
j++; h2i = NULL;
} else {
i++; j++;
}
if ((error = cb(h2i, i2w, payload)) != 0) {
git_error_set_after_callback(error);
break;
}
}
/* restore case-insensitive delta sort */
if (icase_mismatch && h2i_icase) {
git_vector_set_cmp(&head2idx->deltas, git_diff_delta__casecmp);
git_vector_sort(&head2idx->deltas);
}
/* restore idx2wd sort by new path */
if (idx2wd != NULL) {
git_vector_set_cmp(&idx2wd->deltas,
i2w_icase ? git_diff_delta__casecmp : git_diff_delta__cmp);
git_vector_sort(&idx2wd->deltas);
}
return error;
}
int git_diff__commit(
git_diff **out,
git_repository *repo,
const git_commit *commit,
const git_diff_options *opts)
{
git_commit *parent = NULL;
git_diff *commit_diff = NULL;
git_tree *old_tree = NULL, *new_tree = NULL;
size_t parents;
int error = 0;
*out = NULL;
if ((parents = git_commit_parentcount(commit)) > 1) {
char commit_oidstr[GIT_OID_HEXSZ + 1];
error = -1;
git_error_set(GIT_ERROR_INVALID, "commit %s is a merge commit",
git_oid_tostr(commit_oidstr, GIT_OID_HEXSZ + 1, git_commit_id(commit)));
goto on_error;
}
if (parents > 0)
if ((error = git_commit_parent(&parent, commit, 0)) < 0 ||
(error = git_commit_tree(&old_tree, parent)) < 0)
goto on_error;
if ((error = git_commit_tree(&new_tree, commit)) < 0 ||
(error = git_diff_tree_to_tree(&commit_diff, repo, old_tree, new_tree, opts)) < 0)
goto on_error;
*out = commit_diff;
on_error:
git_tree_free(new_tree);
git_tree_free(old_tree);
git_commit_free(parent);
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/libgit2.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_libgit2_h__
#define INCLUDE_libgit2_h__
extern int git_libgit2_init_count(void);
extern const char *git_libgit2__user_agent(void);
extern const char *git_libgit2__ssl_ciphers(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/merge_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_merge_driver_h__
#define INCLUDE_merge_driver_h__
#include "common.h"
#include "git2/merge.h"
#include "git2/index.h"
#include "git2/sys/merge.h"
struct git_merge_driver_source {
git_repository *repo;
const char *default_driver;
const git_merge_file_options *file_opts;
const git_index_entry *ancestor;
const git_index_entry *ours;
const git_index_entry *theirs;
};
typedef struct git_merge_driver__builtin {
git_merge_driver base;
git_merge_file_favor_t favor;
} git_merge_driver__builtin;
extern int git_merge_driver_global_init(void);
extern int git_merge_driver_for_path(
char **name_out,
git_merge_driver **driver_out,
git_repository *repo,
const char *path);
/* Merge driver configuration */
extern int git_merge_driver_for_source(
const char **name_out,
git_merge_driver **driver_out,
const git_merge_driver_source *src);
extern 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);
/* Merge driver for text files, performs a standard three-way merge */
extern git_merge_driver__builtin git_merge_driver__text;
/* Merge driver for union-style merging */
extern git_merge_driver__builtin git_merge_driver__union;
/* Merge driver for unmergeable (binary) files: always produces conflicts */
extern git_merge_driver git_merge_driver__binary;
#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/blob.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 "blob.h"
#include "git2/common.h"
#include "git2/object.h"
#include "git2/repository.h"
#include "git2/odb_backend.h"
#include "filebuf.h"
#include "filter.h"
const void *git_blob_rawcontent(const git_blob *blob)
{
GIT_ASSERT_ARG_WITH_RETVAL(blob, NULL);
if (blob->raw)
return blob->data.raw.data;
else
return git_odb_object_data(blob->data.odb);
}
git_object_size_t git_blob_rawsize(const git_blob *blob)
{
GIT_ASSERT_ARG(blob);
if (blob->raw)
return blob->data.raw.size;
else
return (git_object_size_t)git_odb_object_size(blob->data.odb);
}
int git_blob__getbuf(git_buf *buffer, git_blob *blob)
{
git_object_size_t size = git_blob_rawsize(blob);
GIT_ERROR_CHECK_BLOBSIZE(size);
return git_buf_set(buffer, git_blob_rawcontent(blob), (size_t)size);
}
void git_blob__free(void *_blob)
{
git_blob *blob = (git_blob *) _blob;
if (!blob->raw)
git_odb_object_free(blob->data.odb);
git__free(blob);
}
int git_blob__parse_raw(void *_blob, const char *data, size_t size)
{
git_blob *blob = (git_blob *) _blob;
GIT_ASSERT_ARG(blob);
blob->raw = 1;
blob->data.raw.data = data;
blob->data.raw.size = size;
return 0;
}
int git_blob__parse(void *_blob, git_odb_object *odb_obj)
{
git_blob *blob = (git_blob *) _blob;
GIT_ASSERT_ARG(blob);
git_cached_obj_incref((git_cached_obj *)odb_obj);
blob->raw = 0;
blob->data.odb = odb_obj;
return 0;
}
int git_blob_create_from_buffer(
git_oid *id, git_repository *repo, const void *buffer, size_t len)
{
int error;
git_odb *odb;
git_odb_stream *stream;
GIT_ASSERT_ARG(id);
GIT_ASSERT_ARG(repo);
if ((error = git_repository_odb__weakptr(&odb, repo)) < 0 ||
(error = git_odb_open_wstream(&stream, odb, len, GIT_OBJECT_BLOB)) < 0)
return error;
if ((error = git_odb_stream_write(stream, buffer, len)) == 0)
error = git_odb_stream_finalize_write(id, stream);
git_odb_stream_free(stream);
return error;
}
static int write_file_stream(
git_oid *id, git_odb *odb, const char *path, git_object_size_t file_size)
{
int fd, error;
char buffer[FILEIO_BUFSIZE];
git_odb_stream *stream = NULL;
ssize_t read_len = -1;
git_object_size_t written = 0;
if ((error = git_odb_open_wstream(
&stream, odb, file_size, GIT_OBJECT_BLOB)) < 0)
return error;
if ((fd = git_futils_open_ro(path)) < 0) {
git_odb_stream_free(stream);
return -1;
}
while (!error && (read_len = p_read(fd, buffer, sizeof(buffer))) > 0) {
error = git_odb_stream_write(stream, buffer, read_len);
written += read_len;
}
p_close(fd);
if (written != file_size || read_len < 0) {
git_error_set(GIT_ERROR_OS, "failed to read file into stream");
error = -1;
}
if (!error)
error = git_odb_stream_finalize_write(id, stream);
git_odb_stream_free(stream);
return error;
}
static int write_file_filtered(
git_oid *id,
git_object_size_t *size,
git_odb *odb,
const char *full_path,
git_filter_list *fl,
git_repository* repo)
{
int error;
git_buf tgt = GIT_BUF_INIT;
error = git_filter_list_apply_to_file(&tgt, fl, repo, full_path);
/* Write the file to disk if it was properly filtered */
if (!error) {
*size = tgt.size;
error = git_odb_write(id, odb, tgt.ptr, tgt.size, GIT_OBJECT_BLOB);
}
git_buf_dispose(&tgt);
return error;
}
static int write_symlink(
git_oid *id, git_odb *odb, const char *path, size_t link_size)
{
char *link_data;
ssize_t read_len;
int error;
link_data = git__malloc(link_size);
GIT_ERROR_CHECK_ALLOC(link_data);
read_len = p_readlink(path, link_data, link_size);
if (read_len != (ssize_t)link_size) {
git_error_set(GIT_ERROR_OS, "failed to create blob: cannot read symlink '%s'", path);
git__free(link_data);
return -1;
}
error = git_odb_write(id, odb, (void *)link_data, link_size, GIT_OBJECT_BLOB);
git__free(link_data);
return error;
}
int git_blob__create_from_paths(
git_oid *id,
struct stat *out_st,
git_repository *repo,
const char *content_path,
const char *hint_path,
mode_t hint_mode,
bool try_load_filters)
{
int error;
struct stat st;
git_odb *odb = NULL;
git_object_size_t size;
mode_t mode;
git_buf path = GIT_BUF_INIT;
GIT_ASSERT_ARG(hint_path || !try_load_filters);
if (!content_path) {
if (git_repository_workdir_path(&path, repo, hint_path) < 0)
return -1;
content_path = path.ptr;
}
if ((error = git_path_lstat(content_path, &st)) < 0 ||
(error = git_repository_odb(&odb, repo)) < 0)
goto done;
if (S_ISDIR(st.st_mode)) {
git_error_set(GIT_ERROR_ODB, "cannot create blob from '%s': it is a directory", content_path);
error = GIT_EDIRECTORY;
goto done;
}
if (out_st)
memcpy(out_st, &st, sizeof(st));
size = st.st_size;
mode = hint_mode ? hint_mode : st.st_mode;
if (S_ISLNK(mode)) {
error = write_symlink(id, odb, content_path, (size_t)size);
} else {
git_filter_list *fl = NULL;
if (try_load_filters)
/* Load the filters for writing this file to the ODB */
error = git_filter_list_load(
&fl, repo, NULL, hint_path,
GIT_FILTER_TO_ODB, GIT_FILTER_DEFAULT);
if (error < 0)
/* well, that didn't work */;
else if (fl == NULL)
/* No filters need to be applied to the document: we can stream
* directly from disk */
error = write_file_stream(id, odb, content_path, size);
else {
/* We need to apply one or more filters */
error = write_file_filtered(id, &size, odb, content_path, fl, repo);
git_filter_list_free(fl);
}
/*
* TODO: eventually support streaming filtered files, for files
* which are bigger than a given threshold. This is not a priority
* because applying a filter in streaming mode changes the final
* size of the blob, and without knowing its final size, the blob
* cannot be written in stream mode to the ODB.
*
* The plan is to do streaming writes to a tempfile on disk and then
* opening streaming that file to the ODB, using
* `write_file_stream`.
*
* CAREFULLY DESIGNED APIS YO
*/
}
done:
git_odb_free(odb);
git_buf_dispose(&path);
return error;
}
int git_blob_create_from_workdir(
git_oid *id, git_repository *repo, const char *path)
{
return git_blob__create_from_paths(id, NULL, repo, NULL, path, 0, true);
}
int git_blob_create_from_disk(
git_oid *id, git_repository *repo, const char *path)
{
int error;
git_buf full_path = GIT_BUF_INIT;
const char *workdir, *hintpath = NULL;
if ((error = git_path_prettify(&full_path, path, NULL)) < 0) {
git_buf_dispose(&full_path);
return error;
}
workdir = git_repository_workdir(repo);
if (workdir && !git__prefixcmp(full_path.ptr, workdir))
hintpath = full_path.ptr + strlen(workdir);
error = git_blob__create_from_paths(
id, NULL, repo, git_buf_cstr(&full_path), hintpath, 0, !!hintpath);
git_buf_dispose(&full_path);
return error;
}
typedef struct {
git_writestream parent;
git_filebuf fbuf;
git_repository *repo;
char *hintpath;
} blob_writestream;
static int blob_writestream_close(git_writestream *_stream)
{
blob_writestream *stream = (blob_writestream *) _stream;
git_filebuf_cleanup(&stream->fbuf);
return 0;
}
static void blob_writestream_free(git_writestream *_stream)
{
blob_writestream *stream = (blob_writestream *) _stream;
git_filebuf_cleanup(&stream->fbuf);
git__free(stream->hintpath);
git__free(stream);
}
static int blob_writestream_write(git_writestream *_stream, const char *buffer, size_t len)
{
blob_writestream *stream = (blob_writestream *) _stream;
return git_filebuf_write(&stream->fbuf, buffer, len);
}
int git_blob_create_from_stream(git_writestream **out, git_repository *repo, const char *hintpath)
{
int error;
git_buf path = GIT_BUF_INIT;
blob_writestream *stream;
GIT_ASSERT_ARG(out);
GIT_ASSERT_ARG(repo);
stream = git__calloc(1, sizeof(blob_writestream));
GIT_ERROR_CHECK_ALLOC(stream);
if (hintpath) {
stream->hintpath = git__strdup(hintpath);
GIT_ERROR_CHECK_ALLOC(stream->hintpath);
}
stream->repo = repo;
stream->parent.write = blob_writestream_write;
stream->parent.close = blob_writestream_close;
stream->parent.free = blob_writestream_free;
if ((error = git_repository_item_path(&path, repo, GIT_REPOSITORY_ITEM_OBJECTS)) < 0
|| (error = git_buf_joinpath(&path, path.ptr, "streamed")) < 0)
goto cleanup;
if ((error = git_filebuf_open_withsize(&stream->fbuf, git_buf_cstr(&path), GIT_FILEBUF_TEMPORARY,
0666, 2 * 1024 * 1024)) < 0)
goto cleanup;
*out = (git_writestream *) stream;
cleanup:
if (error < 0)
blob_writestream_free((git_writestream *) stream);
git_buf_dispose(&path);
return error;
}
int git_blob_create_from_stream_commit(git_oid *out, git_writestream *_stream)
{
int error;
blob_writestream *stream = (blob_writestream *) _stream;
/*
* We can make this more officient by avoiding writing to
* disk, but for now let's re-use the helper functions we
* have.
*/
if ((error = git_filebuf_flush(&stream->fbuf)) < 0)
goto cleanup;
error = git_blob__create_from_paths(out, NULL, stream->repo, stream->fbuf.path_lock,
stream->hintpath, 0, !!stream->hintpath);
cleanup:
blob_writestream_free(_stream);
return error;
}
int git_blob_is_binary(const git_blob *blob)
{
git_buf content = GIT_BUF_INIT;
git_object_size_t size;
GIT_ASSERT_ARG(blob);
size = git_blob_rawsize(blob);
git_buf_attach_notowned(&content, git_blob_rawcontent(blob),
(size_t)min(size, GIT_FILTER_BYTES_TO_CHECK_NUL));
return git_buf_is_binary(&content);
}
int git_blob_filter_options_init(
git_blob_filter_options *opts,
unsigned int version)
{
GIT_INIT_STRUCTURE_FROM_TEMPLATE(opts, version,
git_blob_filter_options, GIT_BLOB_FILTER_OPTIONS_INIT);
return 0;
}
int git_blob_filter(
git_buf *out,
git_blob *blob,
const char *path,
git_blob_filter_options *given_opts)
{
int error = 0;
git_filter_list *fl = NULL;
git_blob_filter_options opts = GIT_BLOB_FILTER_OPTIONS_INIT;
git_filter_options filter_opts = GIT_FILTER_OPTIONS_INIT;
GIT_ASSERT_ARG(blob);
GIT_ASSERT_ARG(path);
GIT_ASSERT_ARG(out);
GIT_ERROR_CHECK_VERSION(
given_opts, GIT_BLOB_FILTER_OPTIONS_VERSION, "git_blob_filter_options");
if (git_buf_sanitize(out) < 0)
return -1;
if (given_opts != NULL)
memcpy(&opts, given_opts, sizeof(git_blob_filter_options));
if ((opts.flags & GIT_BLOB_FILTER_CHECK_FOR_BINARY) != 0 &&
git_blob_is_binary(blob))
return 0;
if ((opts.flags & GIT_BLOB_FILTER_NO_SYSTEM_ATTRIBUTES) != 0)
filter_opts.flags |= GIT_FILTER_NO_SYSTEM_ATTRIBUTES;
if ((opts.flags & GIT_BLOB_FILTER_ATTRIBUTES_FROM_HEAD) != 0)
filter_opts.flags |= GIT_FILTER_ATTRIBUTES_FROM_HEAD;
if ((opts.flags & GIT_BLOB_FILTER_ATTRIBUTES_FROM_COMMIT) != 0) {
filter_opts.flags |= GIT_FILTER_ATTRIBUTES_FROM_COMMIT;
#ifndef GIT_DEPRECATE_HARD
if (opts.commit_id)
git_oid_cpy(&filter_opts.attr_commit_id, opts.commit_id);
else
#endif
git_oid_cpy(&filter_opts.attr_commit_id, &opts.attr_commit_id);
}
if (!(error = git_filter_list_load_ext(
&fl, git_blob_owner(blob), blob, path,
GIT_FILTER_TO_WORKTREE, &filter_opts))) {
error = git_filter_list_apply_to_blob(out, fl, blob);
git_filter_list_free(fl);
}
return error;
}
/* Deprecated functions */
#ifndef GIT_DEPRECATE_HARD
int git_blob_create_frombuffer(
git_oid *id, git_repository *repo, const void *buffer, size_t len)
{
return git_blob_create_from_buffer(id, repo, buffer, len);
}
int git_blob_create_fromworkdir(git_oid *id, git_repository *repo, const char *relative_path)
{
return git_blob_create_from_workdir(id, repo, relative_path);
}
int git_blob_create_fromdisk(git_oid *id, git_repository *repo, const char *path)
{
return git_blob_create_from_disk(id, repo, path);
}
int git_blob_create_fromstream(
git_writestream **out,
git_repository *repo,
const char *hintpath)
{
return git_blob_create_from_stream(out, repo, hintpath);
}
int git_blob_create_fromstream_commit(
git_oid *out,
git_writestream *stream)
{
return git_blob_create_from_stream_commit(out, stream);
}
int git_blob_filtered_content(
git_buf *out,
git_blob *blob,
const char *path,
int check_for_binary_data)
{
git_blob_filter_options opts = GIT_BLOB_FILTER_OPTIONS_INIT;
if (check_for_binary_data)
opts.flags |= GIT_BLOB_FILTER_CHECK_FOR_BINARY;
else
opts.flags &= ~GIT_BLOB_FILTER_CHECK_FOR_BINARY;
return git_blob_filter(out, blob, path, &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/patch_parse.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_parse.h"
#include "git2/patch.h"
#include "patch.h"
#include "diff_parse.h"
#include "path.h"
typedef struct {
git_patch base;
git_patch_parse_ctx *ctx;
/* the paths from the `diff --git` header, these will be used if this is not
* a rename (and rename paths are specified) or if no `+++`/`---` line specify
* the paths.
*/
char *header_old_path, *header_new_path;
/* renamed paths are precise and are not prefixed */
char *rename_old_path, *rename_new_path;
/* the paths given in `---` and `+++` lines */
char *old_path, *new_path;
/* the prefixes from the old/new paths */
char *old_prefix, *new_prefix;
} git_patch_parsed;
static int git_parse_err(const char *fmt, ...) GIT_FORMAT_PRINTF(1, 2);
static int git_parse_err(const char *fmt, ...)
{
va_list ap;
va_start(ap, fmt);
git_error_vset(GIT_ERROR_PATCH, fmt, ap);
va_end(ap);
return -1;
}
static size_t header_path_len(git_patch_parse_ctx *ctx)
{
bool inquote = 0;
bool quoted = git_parse_ctx_contains_s(&ctx->parse_ctx, "\"");
size_t len;
for (len = quoted; len < ctx->parse_ctx.line_len; len++) {
if (!quoted && git__isspace(ctx->parse_ctx.line[len]))
break;
else if (quoted && !inquote && ctx->parse_ctx.line[len] == '"') {
len++;
break;
}
inquote = (!inquote && ctx->parse_ctx.line[len] == '\\');
}
return len;
}
static int parse_header_path_buf(git_buf *path, git_patch_parse_ctx *ctx, size_t path_len)
{
int error;
if ((error = git_buf_put(path, ctx->parse_ctx.line, path_len)) < 0)
return error;
git_parse_advance_chars(&ctx->parse_ctx, path_len);
git_buf_rtrim(path);
if (path->size > 0 && path->ptr[0] == '"' &&
(error = git_buf_unquote(path)) < 0)
return error;
git_path_squash_slashes(path);
if (!path->size)
return git_parse_err("patch contains empty path at line %"PRIuZ,
ctx->parse_ctx.line_num);
return 0;
}
static int parse_header_path(char **out, git_patch_parse_ctx *ctx)
{
git_buf path = GIT_BUF_INIT;
int error;
if ((error = parse_header_path_buf(&path, ctx, header_path_len(ctx))) < 0)
goto out;
*out = git_buf_detach(&path);
out:
git_buf_dispose(&path);
return error;
}
static int parse_header_git_oldpath(
git_patch_parsed *patch, git_patch_parse_ctx *ctx)
{
git_buf old_path = GIT_BUF_INIT;
int error;
if (patch->old_path) {
error = git_parse_err("patch contains duplicate old path at line %"PRIuZ,
ctx->parse_ctx.line_num);
goto out;
}
if ((error = parse_header_path_buf(&old_path, ctx, ctx->parse_ctx.line_len - 1)) < 0)
goto out;
patch->old_path = git_buf_detach(&old_path);
out:
git_buf_dispose(&old_path);
return error;
}
static int parse_header_git_newpath(
git_patch_parsed *patch, git_patch_parse_ctx *ctx)
{
git_buf new_path = GIT_BUF_INIT;
int error;
if (patch->new_path) {
error = git_parse_err("patch contains duplicate new path at line %"PRIuZ,
ctx->parse_ctx.line_num);
goto out;
}
if ((error = parse_header_path_buf(&new_path, ctx, ctx->parse_ctx.line_len - 1)) < 0)
goto out;
patch->new_path = git_buf_detach(&new_path);
out:
git_buf_dispose(&new_path);
return error;
}
static int parse_header_mode(uint16_t *mode, git_patch_parse_ctx *ctx)
{
int64_t m;
if ((git_parse_advance_digit(&m, &ctx->parse_ctx, 8)) < 0)
return git_parse_err("invalid file mode at line %"PRIuZ, ctx->parse_ctx.line_num);
if (m > UINT16_MAX)
return -1;
*mode = (uint16_t)m;
return 0;
}
static int parse_header_oid(
git_oid *oid,
uint16_t *oid_len,
git_patch_parse_ctx *ctx)
{
size_t len;
for (len = 0; len < ctx->parse_ctx.line_len && len < GIT_OID_HEXSZ; len++) {
if (!git__isxdigit(ctx->parse_ctx.line[len]))
break;
}
if (len < GIT_OID_MINPREFIXLEN || len > GIT_OID_HEXSZ ||
git_oid_fromstrn(oid, ctx->parse_ctx.line, len) < 0)
return git_parse_err("invalid hex formatted object id at line %"PRIuZ,
ctx->parse_ctx.line_num);
git_parse_advance_chars(&ctx->parse_ctx, len);
*oid_len = (uint16_t)len;
return 0;
}
static int parse_header_git_index(
git_patch_parsed *patch, git_patch_parse_ctx *ctx)
{
char c;
if (parse_header_oid(&patch->base.delta->old_file.id,
&patch->base.delta->old_file.id_abbrev, ctx) < 0 ||
git_parse_advance_expected_str(&ctx->parse_ctx, "..") < 0 ||
parse_header_oid(&patch->base.delta->new_file.id,
&patch->base.delta->new_file.id_abbrev, ctx) < 0)
return -1;
if (git_parse_peek(&c, &ctx->parse_ctx, 0) == 0 && c == ' ') {
uint16_t mode = 0;
git_parse_advance_chars(&ctx->parse_ctx, 1);
if (parse_header_mode(&mode, ctx) < 0)
return -1;
if (!patch->base.delta->new_file.mode)
patch->base.delta->new_file.mode = mode;
if (!patch->base.delta->old_file.mode)
patch->base.delta->old_file.mode = mode;
}
return 0;
}
static int parse_header_git_oldmode(
git_patch_parsed *patch, git_patch_parse_ctx *ctx)
{
return parse_header_mode(&patch->base.delta->old_file.mode, ctx);
}
static int parse_header_git_newmode(
git_patch_parsed *patch, git_patch_parse_ctx *ctx)
{
return parse_header_mode(&patch->base.delta->new_file.mode, ctx);
}
static int parse_header_git_deletedfilemode(
git_patch_parsed *patch,
git_patch_parse_ctx *ctx)
{
git__free((char *)patch->base.delta->new_file.path);
patch->base.delta->new_file.path = NULL;
patch->base.delta->status = GIT_DELTA_DELETED;
patch->base.delta->nfiles = 1;
return parse_header_mode(&patch->base.delta->old_file.mode, ctx);
}
static int parse_header_git_newfilemode(
git_patch_parsed *patch,
git_patch_parse_ctx *ctx)
{
git__free((char *)patch->base.delta->old_file.path);
patch->base.delta->old_file.path = NULL;
patch->base.delta->status = GIT_DELTA_ADDED;
patch->base.delta->nfiles = 1;
return parse_header_mode(&patch->base.delta->new_file.mode, ctx);
}
static int parse_header_rename(
char **out,
git_patch_parse_ctx *ctx)
{
git_buf path = GIT_BUF_INIT;
if (parse_header_path_buf(&path, ctx, header_path_len(ctx)) < 0)
return -1;
/* Note: the `rename from` and `rename to` lines include the literal
* filename. They do *not* include the prefix. (Who needs consistency?)
*/
*out = git_buf_detach(&path);
return 0;
}
static int parse_header_renamefrom(
git_patch_parsed *patch, git_patch_parse_ctx *ctx)
{
patch->base.delta->status = GIT_DELTA_RENAMED;
return parse_header_rename(&patch->rename_old_path, ctx);
}
static int parse_header_renameto(
git_patch_parsed *patch, git_patch_parse_ctx *ctx)
{
patch->base.delta->status = GIT_DELTA_RENAMED;
return parse_header_rename(&patch->rename_new_path, ctx);
}
static int parse_header_copyfrom(
git_patch_parsed *patch, git_patch_parse_ctx *ctx)
{
patch->base.delta->status = GIT_DELTA_COPIED;
return parse_header_rename(&patch->rename_old_path, ctx);
}
static int parse_header_copyto(
git_patch_parsed *patch, git_patch_parse_ctx *ctx)
{
patch->base.delta->status = GIT_DELTA_COPIED;
return parse_header_rename(&patch->rename_new_path, ctx);
}
static int parse_header_percent(uint16_t *out, git_patch_parse_ctx *ctx)
{
int64_t val;
if (git_parse_advance_digit(&val, &ctx->parse_ctx, 10) < 0)
return -1;
if (git_parse_advance_expected_str(&ctx->parse_ctx, "%") < 0)
return -1;
if (val < 0 || val > 100)
return -1;
*out = (uint16_t)val;
return 0;
}
static int parse_header_similarity(
git_patch_parsed *patch, git_patch_parse_ctx *ctx)
{
if (parse_header_percent(&patch->base.delta->similarity, ctx) < 0)
return git_parse_err("invalid similarity percentage at line %"PRIuZ,
ctx->parse_ctx.line_num);
return 0;
}
static int parse_header_dissimilarity(
git_patch_parsed *patch, git_patch_parse_ctx *ctx)
{
uint16_t dissimilarity;
if (parse_header_percent(&dissimilarity, ctx) < 0)
return git_parse_err("invalid similarity percentage at line %"PRIuZ,
ctx->parse_ctx.line_num);
patch->base.delta->similarity = 100 - dissimilarity;
return 0;
}
static int parse_header_start(git_patch_parsed *patch, git_patch_parse_ctx *ctx)
{
if (parse_header_path(&patch->header_old_path, ctx) < 0)
return git_parse_err("corrupt old path in git diff header at line %"PRIuZ,
ctx->parse_ctx.line_num);
if (git_parse_advance_ws(&ctx->parse_ctx) < 0 ||
parse_header_path(&patch->header_new_path, ctx) < 0)
return git_parse_err("corrupt new path in git diff header at line %"PRIuZ,
ctx->parse_ctx.line_num);
/*
* We cannot expect to be able to always parse paths correctly at this
* point. Due to the possibility of unquoted names, whitespaces in
* filenames and custom prefixes we have to allow that, though, and just
* proceeed here. We then hope for the "---" and "+++" lines to fix that
* for us.
*/
if (!git_parse_ctx_contains(&ctx->parse_ctx, "\n", 1) &&
!git_parse_ctx_contains(&ctx->parse_ctx, "\r\n", 2)) {
git_parse_advance_chars(&ctx->parse_ctx, ctx->parse_ctx.line_len - 1);
git__free(patch->header_old_path);
patch->header_old_path = NULL;
git__free(patch->header_new_path);
patch->header_new_path = NULL;
}
return 0;
}
typedef enum {
STATE_START,
STATE_DIFF,
STATE_FILEMODE,
STATE_MODE,
STATE_INDEX,
STATE_PATH,
STATE_SIMILARITY,
STATE_RENAME,
STATE_COPY,
STATE_END,
} parse_header_state;
typedef struct {
const char *str;
parse_header_state expected_state;
parse_header_state next_state;
int(*fn)(git_patch_parsed *, git_patch_parse_ctx *);
} parse_header_transition;
static const parse_header_transition transitions[] = {
/* Start */
{ "diff --git " , STATE_START, STATE_DIFF, parse_header_start },
{ "deleted file mode " , STATE_DIFF, STATE_FILEMODE, parse_header_git_deletedfilemode },
{ "new file mode " , STATE_DIFF, STATE_FILEMODE, parse_header_git_newfilemode },
{ "old mode " , STATE_DIFF, STATE_MODE, parse_header_git_oldmode },
{ "new mode " , STATE_MODE, STATE_END, parse_header_git_newmode },
{ "index " , STATE_FILEMODE, STATE_INDEX, parse_header_git_index },
{ "index " , STATE_DIFF, STATE_INDEX, parse_header_git_index },
{ "index " , STATE_END, STATE_INDEX, parse_header_git_index },
{ "--- " , STATE_DIFF, STATE_PATH, parse_header_git_oldpath },
{ "--- " , STATE_INDEX, STATE_PATH, parse_header_git_oldpath },
{ "--- " , STATE_FILEMODE, STATE_PATH, parse_header_git_oldpath },
{ "+++ " , STATE_PATH, STATE_END, parse_header_git_newpath },
{ "GIT binary patch" , STATE_INDEX, STATE_END, NULL },
{ "Binary files " , STATE_INDEX, STATE_END, NULL },
{ "similarity index " , STATE_END, STATE_SIMILARITY, parse_header_similarity },
{ "similarity index " , STATE_DIFF, STATE_SIMILARITY, parse_header_similarity },
{ "dissimilarity index ", STATE_DIFF, STATE_SIMILARITY, parse_header_dissimilarity },
{ "rename from " , STATE_SIMILARITY, STATE_RENAME, parse_header_renamefrom },
{ "rename old " , STATE_SIMILARITY, STATE_RENAME, parse_header_renamefrom },
{ "copy from " , STATE_SIMILARITY, STATE_COPY, parse_header_copyfrom },
{ "rename to " , STATE_RENAME, STATE_END, parse_header_renameto },
{ "rename new " , STATE_RENAME, STATE_END, parse_header_renameto },
{ "copy to " , STATE_COPY, STATE_END, parse_header_copyto },
/* Next patch */
{ "diff --git " , STATE_END, 0, NULL },
{ "@@ -" , STATE_END, 0, NULL },
{ "-- " , STATE_INDEX, 0, NULL },
{ "-- " , STATE_END, 0, NULL },
};
static int parse_header_git(
git_patch_parsed *patch,
git_patch_parse_ctx *ctx)
{
size_t i;
int error = 0;
parse_header_state state = STATE_START;
/* Parse remaining header lines */
for (; ctx->parse_ctx.remain_len > 0; git_parse_advance_line(&ctx->parse_ctx)) {
bool found = false;
if (ctx->parse_ctx.line_len == 0 || ctx->parse_ctx.line[ctx->parse_ctx.line_len - 1] != '\n')
break;
for (i = 0; i < ARRAY_SIZE(transitions); i++) {
const parse_header_transition *transition = &transitions[i];
size_t op_len = strlen(transition->str);
if (transition->expected_state != state ||
git__prefixcmp(ctx->parse_ctx.line, transition->str) != 0)
continue;
state = transition->next_state;
/* Do not advance if this is the patch separator */
if (transition->fn == NULL)
goto done;
git_parse_advance_chars(&ctx->parse_ctx, op_len);
if ((error = transition->fn(patch, ctx)) < 0)
goto done;
git_parse_advance_ws(&ctx->parse_ctx);
if (git_parse_advance_expected_str(&ctx->parse_ctx, "\n") < 0 ||
ctx->parse_ctx.line_len > 0) {
error = git_parse_err("trailing data at line %"PRIuZ, ctx->parse_ctx.line_num);
goto done;
}
found = true;
break;
}
if (!found) {
error = git_parse_err("invalid patch header at line %"PRIuZ,
ctx->parse_ctx.line_num);
goto done;
}
}
if (state != STATE_END) {
error = git_parse_err("unexpected header line %"PRIuZ, ctx->parse_ctx.line_num);
goto done;
}
done:
return error;
}
static int parse_int(int *out, git_patch_parse_ctx *ctx)
{
int64_t num;
if (git_parse_advance_digit(&num, &ctx->parse_ctx, 10) < 0 || !git__is_int(num))
return -1;
*out = (int)num;
return 0;
}
static int parse_hunk_header(
git_patch_hunk *hunk,
git_patch_parse_ctx *ctx)
{
const char *header_start = ctx->parse_ctx.line;
char c;
hunk->hunk.old_lines = 1;
hunk->hunk.new_lines = 1;
if (git_parse_advance_expected_str(&ctx->parse_ctx, "@@ -") < 0 ||
parse_int(&hunk->hunk.old_start, ctx) < 0)
goto fail;
if (git_parse_peek(&c, &ctx->parse_ctx, 0) == 0 && c == ',') {
if (git_parse_advance_expected_str(&ctx->parse_ctx, ",") < 0 ||
parse_int(&hunk->hunk.old_lines, ctx) < 0)
goto fail;
}
if (git_parse_advance_expected_str(&ctx->parse_ctx, " +") < 0 ||
parse_int(&hunk->hunk.new_start, ctx) < 0)
goto fail;
if (git_parse_peek(&c, &ctx->parse_ctx, 0) == 0 && c == ',') {
if (git_parse_advance_expected_str(&ctx->parse_ctx, ",") < 0 ||
parse_int(&hunk->hunk.new_lines, ctx) < 0)
goto fail;
}
if (git_parse_advance_expected_str(&ctx->parse_ctx, " @@") < 0)
goto fail;
git_parse_advance_line(&ctx->parse_ctx);
if (!hunk->hunk.old_lines && !hunk->hunk.new_lines)
goto fail;
hunk->hunk.header_len = ctx->parse_ctx.line - header_start;
if (hunk->hunk.header_len > (GIT_DIFF_HUNK_HEADER_SIZE - 1))
return git_parse_err("oversized patch hunk header at line %"PRIuZ,
ctx->parse_ctx.line_num);
memcpy(hunk->hunk.header, header_start, hunk->hunk.header_len);
hunk->hunk.header[hunk->hunk.header_len] = '\0';
return 0;
fail:
git_error_set(GIT_ERROR_PATCH, "invalid patch hunk header at line %"PRIuZ,
ctx->parse_ctx.line_num);
return -1;
}
static int eof_for_origin(int origin) {
if (origin == GIT_DIFF_LINE_ADDITION)
return GIT_DIFF_LINE_ADD_EOFNL;
if (origin == GIT_DIFF_LINE_DELETION)
return GIT_DIFF_LINE_DEL_EOFNL;
return GIT_DIFF_LINE_CONTEXT_EOFNL;
}
static int parse_hunk_body(
git_patch_parsed *patch,
git_patch_hunk *hunk,
git_patch_parse_ctx *ctx)
{
git_diff_line *line;
int error = 0;
int oldlines = hunk->hunk.old_lines;
int newlines = hunk->hunk.new_lines;
int last_origin = 0;
for (;
ctx->parse_ctx.remain_len > 1 &&
(oldlines || newlines) &&
!git_parse_ctx_contains_s(&ctx->parse_ctx, "@@ -");
git_parse_advance_line(&ctx->parse_ctx)) {
int old_lineno, new_lineno, origin, prefix = 1;
char c;
if (git__add_int_overflow(&old_lineno, hunk->hunk.old_start, hunk->hunk.old_lines) ||
git__sub_int_overflow(&old_lineno, old_lineno, oldlines) ||
git__add_int_overflow(&new_lineno, hunk->hunk.new_start, hunk->hunk.new_lines) ||
git__sub_int_overflow(&new_lineno, new_lineno, newlines)) {
error = git_parse_err("unrepresentable line count at line %"PRIuZ,
ctx->parse_ctx.line_num);
goto done;
}
if (ctx->parse_ctx.line_len == 0 || ctx->parse_ctx.line[ctx->parse_ctx.line_len - 1] != '\n') {
error = git_parse_err("invalid patch instruction at line %"PRIuZ,
ctx->parse_ctx.line_num);
goto done;
}
git_parse_peek(&c, &ctx->parse_ctx, 0);
switch (c) {
case '\n':
prefix = 0;
/* fall through */
case ' ':
origin = GIT_DIFF_LINE_CONTEXT;
oldlines--;
newlines--;
break;
case '-':
origin = GIT_DIFF_LINE_DELETION;
oldlines--;
new_lineno = -1;
break;
case '+':
origin = GIT_DIFF_LINE_ADDITION;
newlines--;
old_lineno = -1;
break;
case '\\':
/*
* If there are no oldlines left, then this is probably
* the "\ No newline at end of file" marker. Do not
* verify its format, as it may be localized.
*/
if (!oldlines) {
prefix = 0;
origin = eof_for_origin(last_origin);
old_lineno = -1;
new_lineno = -1;
break;
}
/* fall through */
default:
error = git_parse_err("invalid patch hunk at line %"PRIuZ, ctx->parse_ctx.line_num);
goto done;
}
line = git_array_alloc(patch->base.lines);
GIT_ERROR_CHECK_ALLOC(line);
memset(line, 0x0, sizeof(git_diff_line));
line->content_len = ctx->parse_ctx.line_len - prefix;
line->content = git__strndup(ctx->parse_ctx.line + prefix, line->content_len);
GIT_ERROR_CHECK_ALLOC(line->content);
line->content_offset = ctx->parse_ctx.content_len - ctx->parse_ctx.remain_len;
line->origin = origin;
line->num_lines = 1;
line->old_lineno = old_lineno;
line->new_lineno = new_lineno;
hunk->line_count++;
last_origin = origin;
}
if (oldlines || newlines) {
error = git_parse_err(
"invalid patch hunk, expected %d old lines and %d new lines",
hunk->hunk.old_lines, hunk->hunk.new_lines);
goto done;
}
/*
* Handle "\ No newline at end of file". Only expect the leading
* backslash, though, because the rest of the string could be
* localized. Because `diff` optimizes for the case where you
* want to apply the patch by hand.
*/
if (git_parse_ctx_contains_s(&ctx->parse_ctx, "\\ ") &&
git_array_size(patch->base.lines) > 0) {
line = git_array_get(patch->base.lines, git_array_size(patch->base.lines) - 1);
if (line->content_len < 1) {
error = git_parse_err("last line has no trailing newline");
goto done;
}
line = git_array_alloc(patch->base.lines);
GIT_ERROR_CHECK_ALLOC(line);
memset(line, 0x0, sizeof(git_diff_line));
line->content_len = ctx->parse_ctx.line_len;
line->content = git__strndup(ctx->parse_ctx.line, line->content_len);
GIT_ERROR_CHECK_ALLOC(line->content);
line->content_offset = ctx->parse_ctx.content_len - ctx->parse_ctx.remain_len;
line->origin = eof_for_origin(last_origin);
line->num_lines = 1;
line->old_lineno = -1;
line->new_lineno = -1;
hunk->line_count++;
git_parse_advance_line(&ctx->parse_ctx);
}
done:
return error;
}
static int parse_patch_header(
git_patch_parsed *patch,
git_patch_parse_ctx *ctx)
{
int error = 0;
for (; ctx->parse_ctx.remain_len > 0; git_parse_advance_line(&ctx->parse_ctx)) {
/* This line is too short to be a patch header. */
if (ctx->parse_ctx.line_len < 6)
continue;
/* This might be a hunk header without a patch header, provide a
* sensible error message. */
if (git_parse_ctx_contains_s(&ctx->parse_ctx, "@@ -")) {
size_t line_num = ctx->parse_ctx.line_num;
git_patch_hunk hunk;
/* If this cannot be parsed as a hunk header, it's just leading
* noise, continue.
*/
if (parse_hunk_header(&hunk, ctx) < 0) {
git_error_clear();
continue;
}
error = git_parse_err("invalid hunk header outside patch at line %"PRIuZ,
line_num);
goto done;
}
/* This buffer is too short to contain a patch. */
if (ctx->parse_ctx.remain_len < ctx->parse_ctx.line_len + 6)
break;
/* A proper git patch */
if (git_parse_ctx_contains_s(&ctx->parse_ctx, "diff --git ")) {
error = parse_header_git(patch, ctx);
goto done;
}
error = 0;
continue;
}
git_error_set(GIT_ERROR_PATCH, "no patch found");
error = GIT_ENOTFOUND;
done:
return error;
}
static int parse_patch_binary_side(
git_diff_binary_file *binary,
git_patch_parse_ctx *ctx)
{
git_diff_binary_t type = GIT_DIFF_BINARY_NONE;
git_buf base85 = GIT_BUF_INIT, decoded = GIT_BUF_INIT;
int64_t len;
int error = 0;
if (git_parse_ctx_contains_s(&ctx->parse_ctx, "literal ")) {
type = GIT_DIFF_BINARY_LITERAL;
git_parse_advance_chars(&ctx->parse_ctx, 8);
} else if (git_parse_ctx_contains_s(&ctx->parse_ctx, "delta ")) {
type = GIT_DIFF_BINARY_DELTA;
git_parse_advance_chars(&ctx->parse_ctx, 6);
} else {
error = git_parse_err(
"unknown binary delta type at line %"PRIuZ, ctx->parse_ctx.line_num);
goto done;
}
if (git_parse_advance_digit(&len, &ctx->parse_ctx, 10) < 0 ||
git_parse_advance_nl(&ctx->parse_ctx) < 0 || len < 0) {
error = git_parse_err("invalid binary size at line %"PRIuZ, ctx->parse_ctx.line_num);
goto done;
}
while (ctx->parse_ctx.line_len) {
char c;
size_t encoded_len, decoded_len = 0, decoded_orig = decoded.size;
git_parse_peek(&c, &ctx->parse_ctx, 0);
if (c == '\n')
break;
else if (c >= 'A' && c <= 'Z')
decoded_len = c - 'A' + 1;
else if (c >= 'a' && c <= 'z')
decoded_len = c - 'a' + (('z' - 'a') + 1) + 1;
if (!decoded_len) {
error = git_parse_err("invalid binary length at line %"PRIuZ, ctx->parse_ctx.line_num);
goto done;
}
git_parse_advance_chars(&ctx->parse_ctx, 1);
encoded_len = ((decoded_len / 4) + !!(decoded_len % 4)) * 5;
if (!encoded_len || !ctx->parse_ctx.line_len || encoded_len > ctx->parse_ctx.line_len - 1) {
error = git_parse_err("truncated binary data at line %"PRIuZ, ctx->parse_ctx.line_num);
goto done;
}
if ((error = git_buf_decode_base85(
&decoded, ctx->parse_ctx.line, encoded_len, decoded_len)) < 0)
goto done;
if (decoded.size - decoded_orig != decoded_len) {
error = git_parse_err("truncated binary data at line %"PRIuZ, ctx->parse_ctx.line_num);
goto done;
}
git_parse_advance_chars(&ctx->parse_ctx, encoded_len);
if (git_parse_advance_nl(&ctx->parse_ctx) < 0) {
error = git_parse_err("trailing data at line %"PRIuZ, ctx->parse_ctx.line_num);
goto done;
}
}
binary->type = type;
binary->inflatedlen = (size_t)len;
binary->datalen = decoded.size;
binary->data = git_buf_detach(&decoded);
done:
git_buf_dispose(&base85);
git_buf_dispose(&decoded);
return error;
}
static int parse_patch_binary(
git_patch_parsed *patch,
git_patch_parse_ctx *ctx)
{
int error;
if (git_parse_advance_expected_str(&ctx->parse_ctx, "GIT binary patch") < 0 ||
git_parse_advance_nl(&ctx->parse_ctx) < 0)
return git_parse_err("corrupt git binary header at line %"PRIuZ, ctx->parse_ctx.line_num);
/* parse old->new binary diff */
if ((error = parse_patch_binary_side(
&patch->base.binary.new_file, ctx)) < 0)
return error;
if (git_parse_advance_nl(&ctx->parse_ctx) < 0)
return git_parse_err("corrupt git binary separator at line %"PRIuZ,
ctx->parse_ctx.line_num);
/* parse new->old binary diff */
if ((error = parse_patch_binary_side(
&patch->base.binary.old_file, ctx)) < 0)
return error;
if (git_parse_advance_nl(&ctx->parse_ctx) < 0)
return git_parse_err("corrupt git binary patch separator at line %"PRIuZ,
ctx->parse_ctx.line_num);
patch->base.binary.contains_data = 1;
patch->base.delta->flags |= GIT_DIFF_FLAG_BINARY;
return 0;
}
static int parse_patch_binary_nodata(
git_patch_parsed *patch,
git_patch_parse_ctx *ctx)
{
const char *old = patch->old_path ? patch->old_path : patch->header_old_path;
const char *new = patch->new_path ? patch->new_path : patch->header_new_path;
if (!old || !new)
return git_parse_err("corrupt binary data without paths at line %"PRIuZ, ctx->parse_ctx.line_num);
if (patch->base.delta->status == GIT_DELTA_ADDED)
old = "/dev/null";
else if (patch->base.delta->status == GIT_DELTA_DELETED)
new = "/dev/null";
if (git_parse_advance_expected_str(&ctx->parse_ctx, "Binary files ") < 0 ||
git_parse_advance_expected_str(&ctx->parse_ctx, old) < 0 ||
git_parse_advance_expected_str(&ctx->parse_ctx, " and ") < 0 ||
git_parse_advance_expected_str(&ctx->parse_ctx, new) < 0 ||
git_parse_advance_expected_str(&ctx->parse_ctx, " differ") < 0 ||
git_parse_advance_nl(&ctx->parse_ctx) < 0)
return git_parse_err("corrupt git binary header at line %"PRIuZ, ctx->parse_ctx.line_num);
patch->base.binary.contains_data = 0;
patch->base.delta->flags |= GIT_DIFF_FLAG_BINARY;
return 0;
}
static int parse_patch_hunks(
git_patch_parsed *patch,
git_patch_parse_ctx *ctx)
{
git_patch_hunk *hunk;
int error = 0;
while (git_parse_ctx_contains_s(&ctx->parse_ctx, "@@ -")) {
hunk = git_array_alloc(patch->base.hunks);
GIT_ERROR_CHECK_ALLOC(hunk);
memset(hunk, 0, sizeof(git_patch_hunk));
hunk->line_start = git_array_size(patch->base.lines);
hunk->line_count = 0;
if ((error = parse_hunk_header(hunk, ctx)) < 0 ||
(error = parse_hunk_body(patch, hunk, ctx)) < 0)
goto done;
}
patch->base.delta->flags |= GIT_DIFF_FLAG_NOT_BINARY;
done:
return error;
}
static int parse_patch_body(
git_patch_parsed *patch, git_patch_parse_ctx *ctx)
{
if (git_parse_ctx_contains_s(&ctx->parse_ctx, "GIT binary patch"))
return parse_patch_binary(patch, ctx);
else if (git_parse_ctx_contains_s(&ctx->parse_ctx, "Binary files "))
return parse_patch_binary_nodata(patch, ctx);
else
return parse_patch_hunks(patch, ctx);
}
static int check_header_names(
const char *one,
const char *two,
const char *old_or_new,
bool two_null)
{
if (!one || !two)
return 0;
if (two_null && strcmp(two, "/dev/null") != 0)
return git_parse_err("expected %s path of '/dev/null'", old_or_new);
else if (!two_null && strcmp(one, two) != 0)
return git_parse_err("mismatched %s path names", old_or_new);
return 0;
}
static int check_prefix(
char **out,
size_t *out_len,
git_patch_parsed *patch,
const char *path_start)
{
const char *path = path_start;
size_t prefix_len = patch->ctx->opts.prefix_len;
size_t remain_len = prefix_len;
*out = NULL;
*out_len = 0;
if (prefix_len == 0)
goto done;
/* leading slashes do not count as part of the prefix in git apply */
while (*path == '/')
path++;
while (*path && remain_len) {
if (*path == '/')
remain_len--;
path++;
}
if (remain_len || !*path)
return git_parse_err(
"header filename does not contain %"PRIuZ" path components",
prefix_len);
done:
*out_len = (path - path_start);
*out = git__strndup(path_start, *out_len);
return (*out == NULL) ? -1 : 0;
}
static int check_filenames(git_patch_parsed *patch)
{
const char *prefixed_new, *prefixed_old;
size_t old_prefixlen = 0, new_prefixlen = 0;
bool added = (patch->base.delta->status == GIT_DELTA_ADDED);
bool deleted = (patch->base.delta->status == GIT_DELTA_DELETED);
if (patch->old_path && !patch->new_path)
return git_parse_err("missing new path");
if (!patch->old_path && patch->new_path)
return git_parse_err("missing old path");
/* Ensure (non-renamed) paths match */
if (check_header_names(patch->header_old_path, patch->old_path, "old", added) < 0 ||
check_header_names(patch->header_new_path, patch->new_path, "new", deleted) < 0)
return -1;
prefixed_old = (!added && patch->old_path) ? patch->old_path : patch->header_old_path;
prefixed_new = (!deleted && patch->new_path) ? patch->new_path : patch->header_new_path;
if ((prefixed_old && check_prefix(&patch->old_prefix, &old_prefixlen, patch, prefixed_old) < 0) ||
(prefixed_new && check_prefix(&patch->new_prefix, &new_prefixlen, patch, prefixed_new) < 0))
return -1;
/* Prefer the rename filenames as they are unambiguous and unprefixed */
if (patch->rename_old_path)
patch->base.delta->old_file.path = patch->rename_old_path;
else if (prefixed_old)
patch->base.delta->old_file.path = prefixed_old + old_prefixlen;
else
patch->base.delta->old_file.path = NULL;
if (patch->rename_new_path)
patch->base.delta->new_file.path = patch->rename_new_path;
else if (prefixed_new)
patch->base.delta->new_file.path = prefixed_new + new_prefixlen;
else
patch->base.delta->new_file.path = NULL;
if (!patch->base.delta->old_file.path &&
!patch->base.delta->new_file.path)
return git_parse_err("git diff header lacks old / new paths");
return 0;
}
static int check_patch(git_patch_parsed *patch)
{
git_diff_delta *delta = patch->base.delta;
if (check_filenames(patch) < 0)
return -1;
if (delta->old_file.path &&
delta->status != GIT_DELTA_DELETED &&
!delta->new_file.mode)
delta->new_file.mode = delta->old_file.mode;
if (delta->status == GIT_DELTA_MODIFIED &&
!(delta->flags & GIT_DIFF_FLAG_BINARY) &&
delta->new_file.mode == delta->old_file.mode &&
git_array_size(patch->base.hunks) == 0)
return git_parse_err("patch with no hunks");
if (delta->status == GIT_DELTA_ADDED) {
memset(&delta->old_file.id, 0x0, sizeof(git_oid));
delta->old_file.id_abbrev = 0;
}
if (delta->status == GIT_DELTA_DELETED) {
memset(&delta->new_file.id, 0x0, sizeof(git_oid));
delta->new_file.id_abbrev = 0;
}
return 0;
}
git_patch_parse_ctx *git_patch_parse_ctx_init(
const char *content,
size_t content_len,
const git_patch_options *opts)
{
git_patch_parse_ctx *ctx;
git_patch_options default_opts = GIT_PATCH_OPTIONS_INIT;
if ((ctx = git__calloc(1, sizeof(git_patch_parse_ctx))) == NULL)
return NULL;
if ((git_parse_ctx_init(&ctx->parse_ctx, content, content_len)) < 0) {
git__free(ctx);
return NULL;
}
if (opts)
memcpy(&ctx->opts, opts, sizeof(git_patch_options));
else
memcpy(&ctx->opts, &default_opts, sizeof(git_patch_options));
GIT_REFCOUNT_INC(ctx);
return ctx;
}
static void patch_parse_ctx_free(git_patch_parse_ctx *ctx)
{
if (!ctx)
return;
git_parse_ctx_clear(&ctx->parse_ctx);
git__free(ctx);
}
void git_patch_parse_ctx_free(git_patch_parse_ctx *ctx)
{
GIT_REFCOUNT_DEC(ctx, patch_parse_ctx_free);
}
int git_patch_parsed_from_diff(git_patch **out, git_diff *d, size_t idx)
{
git_diff_parsed *diff = (git_diff_parsed *)d;
git_patch *p;
if ((p = git_vector_get(&diff->patches, idx)) == NULL)
return -1;
GIT_REFCOUNT_INC(p);
*out = p;
return 0;
}
static void patch_parsed__free(git_patch *p)
{
git_patch_parsed *patch = (git_patch_parsed *)p;
git_diff_line *line;
size_t i;
if (!patch)
return;
git_patch_parse_ctx_free(patch->ctx);
git__free((char *)patch->base.binary.old_file.data);
git__free((char *)patch->base.binary.new_file.data);
git_array_clear(patch->base.hunks);
git_array_foreach(patch->base.lines, i, line)
git__free((char *) line->content);
git_array_clear(patch->base.lines);
git__free(patch->base.delta);
git__free(patch->old_prefix);
git__free(patch->new_prefix);
git__free(patch->header_old_path);
git__free(patch->header_new_path);
git__free(patch->rename_old_path);
git__free(patch->rename_new_path);
git__free(patch->old_path);
git__free(patch->new_path);
git__free(patch);
}
int git_patch_parse(
git_patch **out,
git_patch_parse_ctx *ctx)
{
git_patch_parsed *patch;
size_t start, used;
int error = 0;
GIT_ASSERT_ARG(out);
GIT_ASSERT_ARG(ctx);
*out = NULL;
patch = git__calloc(1, sizeof(git_patch_parsed));
GIT_ERROR_CHECK_ALLOC(patch);
patch->ctx = ctx;
GIT_REFCOUNT_INC(patch->ctx);
patch->base.free_fn = patch_parsed__free;
patch->base.delta = git__calloc(1, sizeof(git_diff_delta));
GIT_ERROR_CHECK_ALLOC(patch->base.delta);
patch->base.delta->status = GIT_DELTA_MODIFIED;
patch->base.delta->nfiles = 2;
start = ctx->parse_ctx.remain_len;
if ((error = parse_patch_header(patch, ctx)) < 0 ||
(error = parse_patch_body(patch, ctx)) < 0 ||
(error = check_patch(patch)) < 0)
goto done;
used = start - ctx->parse_ctx.remain_len;
ctx->parse_ctx.remain += used;
patch->base.diff_opts.old_prefix = patch->old_prefix;
patch->base.diff_opts.new_prefix = patch->new_prefix;
patch->base.diff_opts.flags |= GIT_DIFF_SHOW_BINARY;
GIT_REFCOUNT_INC(&patch->base);
*out = &patch->base;
done:
if (error < 0)
patch_parsed__free(&patch->base);
return error;
}
int git_patch_from_buffer(
git_patch **out,
const char *content,
size_t content_len,
const git_patch_options *opts)
{
git_patch_parse_ctx *ctx;
int error;
ctx = git_patch_parse_ctx_init(content, content_len, opts);
GIT_ERROR_CHECK_ALLOC(ctx);
error = git_patch_parse(out, ctx);
git_patch_parse_ctx_free(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/attr_file.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_attr_file_h__
#define INCLUDE_attr_file_h__
#include "common.h"
#include "git2/oid.h"
#include "git2/attr.h"
#include "vector.h"
#include "pool.h"
#include "buffer.h"
#include "futils.h"
#define GIT_ATTR_FILE ".gitattributes"
#define GIT_ATTR_FILE_INREPO "attributes"
#define GIT_ATTR_FILE_SYSTEM "gitattributes"
#define GIT_ATTR_FILE_XDG "attributes"
#define GIT_ATTR_FNMATCH_NEGATIVE (1U << 0)
#define GIT_ATTR_FNMATCH_DIRECTORY (1U << 1)
#define GIT_ATTR_FNMATCH_FULLPATH (1U << 2)
#define GIT_ATTR_FNMATCH_MACRO (1U << 3)
#define GIT_ATTR_FNMATCH_IGNORE (1U << 4)
#define GIT_ATTR_FNMATCH_HASWILD (1U << 5)
#define GIT_ATTR_FNMATCH_ALLOWSPACE (1U << 6)
#define GIT_ATTR_FNMATCH_ICASE (1U << 7)
#define GIT_ATTR_FNMATCH_MATCH_ALL (1U << 8)
#define GIT_ATTR_FNMATCH_ALLOWNEG (1U << 9)
#define GIT_ATTR_FNMATCH_ALLOWMACRO (1U << 10)
#define GIT_ATTR_FNMATCH__INCOMING \
(GIT_ATTR_FNMATCH_ALLOWSPACE | GIT_ATTR_FNMATCH_ALLOWNEG | GIT_ATTR_FNMATCH_ALLOWMACRO)
typedef enum {
GIT_ATTR_FILE_SOURCE_MEMORY = 0,
GIT_ATTR_FILE_SOURCE_FILE = 1,
GIT_ATTR_FILE_SOURCE_INDEX = 2,
GIT_ATTR_FILE_SOURCE_HEAD = 3,
GIT_ATTR_FILE_SOURCE_COMMIT = 4,
GIT_ATTR_FILE_NUM_SOURCES = 5
} git_attr_file_source_t;
typedef struct {
/* The source location for the attribute file. */
git_attr_file_source_t type;
/*
* The filename of the attribute file to read (relative to the
* given base path).
*/
const char *base;
const char *filename;
/*
* The commit ID when the given source type is a commit (or NULL
* for the repository's HEAD commit.)
*/
git_oid *commit_id;
} git_attr_file_source;
extern const char *git_attr__true;
extern const char *git_attr__false;
extern const char *git_attr__unset;
typedef struct {
char *pattern;
size_t length;
char *containing_dir;
size_t containing_dir_length;
unsigned int flags;
} git_attr_fnmatch;
typedef struct {
git_attr_fnmatch match;
git_vector assigns; /* vector of <git_attr_assignment*> */
} git_attr_rule;
typedef struct {
git_refcount unused;
const char *name;
uint32_t name_hash;
} git_attr_name;
typedef struct {
git_refcount rc; /* for macros */
char *name;
uint32_t name_hash;
const char *value;
} git_attr_assignment;
typedef struct git_attr_file_entry git_attr_file_entry;
typedef struct {
git_refcount rc;
git_mutex lock;
git_attr_file_entry *entry;
git_attr_file_source source;
git_vector rules; /* vector of <rule*> or <fnmatch*> */
git_pool pool;
unsigned int nonexistent:1;
int session_key;
union {
git_oid oid;
git_futils_filestamp stamp;
} cache_data;
} git_attr_file;
struct git_attr_file_entry {
git_attr_file *file[GIT_ATTR_FILE_NUM_SOURCES];
const char *path; /* points into fullpath */
char fullpath[GIT_FLEX_ARRAY];
};
typedef struct {
git_buf full;
char *path;
char *basename;
int is_dir;
} git_attr_path;
/* A git_attr_session can provide an "instance" of reading, to prevent cache
* invalidation during a single operation instance (like checkout).
*/
typedef struct {
int key;
unsigned int init_setup:1,
init_sysdir:1;
git_buf sysdir;
git_buf tmp;
} git_attr_session;
extern int git_attr_session__init(git_attr_session *attr_session, git_repository *repo);
extern void git_attr_session__free(git_attr_session *session);
extern int git_attr_get_many_with_session(
const char **values_out,
git_repository *repo,
git_attr_session *attr_session,
git_attr_options *opts,
const char *path,
size_t num_attr,
const char **names);
typedef int (*git_attr_file_parser)(
git_repository *repo,
git_attr_file *file,
const char *data,
bool allow_macros);
/*
* git_attr_file API
*/
int git_attr_file__new(
git_attr_file **out,
git_attr_file_entry *entry,
git_attr_file_source *source);
void git_attr_file__free(git_attr_file *file);
int git_attr_file__load(
git_attr_file **out,
git_repository *repo,
git_attr_session *attr_session,
git_attr_file_entry *ce,
git_attr_file_source *source,
git_attr_file_parser parser,
bool allow_macros);
int git_attr_file__load_standalone(
git_attr_file **out, const char *path);
int git_attr_file__out_of_date(
git_repository *repo, git_attr_session *session, git_attr_file *file, git_attr_file_source *source);
int git_attr_file__parse_buffer(
git_repository *repo, git_attr_file *attrs, const char *data, bool allow_macros);
int git_attr_file__clear_rules(
git_attr_file *file, bool need_lock);
int git_attr_file__lookup_one(
git_attr_file *file,
git_attr_path *path,
const char *attr,
const char **value);
/* loop over rules in file from bottom to top */
#define git_attr_file__foreach_matching_rule(file, path, iter, rule) \
git_vector_rforeach(&(file)->rules, (iter), (rule)) \
if (git_attr_rule__match((rule), (path)))
uint32_t git_attr_file__name_hash(const char *name);
/*
* other utilities
*/
extern int git_attr_fnmatch__parse(
git_attr_fnmatch *spec,
git_pool *pool,
const char *source,
const char **base);
extern bool git_attr_fnmatch__match(
git_attr_fnmatch *rule,
git_attr_path *path);
extern void git_attr_rule__free(git_attr_rule *rule);
extern bool git_attr_rule__match(
git_attr_rule *rule,
git_attr_path *path);
extern git_attr_assignment *git_attr_rule__lookup_assignment(
git_attr_rule *rule, const char *name);
typedef enum { GIT_DIR_FLAG_TRUE = 1, GIT_DIR_FLAG_FALSE = 0, GIT_DIR_FLAG_UNKNOWN = -1 } git_dir_flag;
extern int git_attr_path__init(
git_attr_path *out,
const char *path,
const char *base,
git_dir_flag is_dir);
extern void git_attr_path__free(git_attr_path *info);
extern int git_attr_assignment__parse(
git_repository *repo, /* needed to expand macros */
git_pool *pool,
git_vector *assigns,
const char **scan);
#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-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_tree_cache_h__
#define INCLUDE_tree_cache_h__
#include "common.h"
#include "pool.h"
#include "buffer.h"
#include "git2/oid.h"
typedef struct git_tree_cache {
struct git_tree_cache **children;
size_t children_count;
ssize_t entry_count;
git_oid oid;
size_t namelen;
char name[GIT_FLEX_ARRAY];
} git_tree_cache;
int git_tree_cache_write(git_buf *out, git_tree_cache *tree);
int git_tree_cache_read(git_tree_cache **tree, const char *buffer, size_t buffer_size, git_pool *pool);
void git_tree_cache_invalidate_path(git_tree_cache *tree, const char *path);
const git_tree_cache *git_tree_cache_get(const git_tree_cache *tree, const char *path);
int git_tree_cache_new(git_tree_cache **out, const char *name, git_pool *pool);
/**
* Read a tree as the root of the tree cache (like for `git read-tree`)
*/
int git_tree_cache_read_tree(git_tree_cache **out, const git_tree *tree, git_pool *pool);
void git_tree_cache_free(git_tree_cache *tree);
#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/message.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_message_h__
#define INCLUDE_message_h__
#include "common.h"
#include "git2/message.h"
#include "buffer.h"
int git_message__prettify(git_buf *message_out, const char *message, int strip_comments);
#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.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 "odb.h"
#include <zlib.h>
#include "git2/object.h"
#include "git2/sys/odb_backend.h"
#include "futils.h"
#include "hash.h"
#include "delta.h"
#include "filter.h"
#include "repository.h"
#include "blob.h"
#include "git2/odb_backend.h"
#include "git2/oid.h"
#include "git2/oidarray.h"
#define GIT_ALTERNATES_FILE "info/alternates"
#define GIT_ALTERNATES_MAX_DEPTH 5
/*
* We work under the assumption that most objects for long-running
* operations will be packed
*/
int git_odb__loose_priority = GIT_ODB_DEFAULT_LOOSE_PRIORITY;
int git_odb__packed_priority = GIT_ODB_DEFAULT_PACKED_PRIORITY;
bool git_odb__strict_hash_verification = true;
typedef struct
{
git_odb_backend *backend;
int priority;
bool is_alternate;
ino_t disk_inode;
} backend_internal;
static git_cache *odb_cache(git_odb *odb)
{
git_repository *owner = GIT_REFCOUNT_OWNER(odb);
if (owner != NULL) {
return &owner->objects;
}
return &odb->own_cache;
}
static int odb_otype_fast(git_object_t *type_p, git_odb *db, const git_oid *id);
static int load_alternates(git_odb *odb, const char *objects_dir, int alternate_depth);
static int error_null_oid(int error, const char *message);
static git_object_t odb_hardcoded_type(const git_oid *id)
{
static git_oid empty_tree = {{ 0x4b, 0x82, 0x5d, 0xc6, 0x42, 0xcb, 0x6e, 0xb9, 0xa0, 0x60,
0xe5, 0x4b, 0xf8, 0xd6, 0x92, 0x88, 0xfb, 0xee, 0x49, 0x04 }};
if (!git_oid_cmp(id, &empty_tree))
return GIT_OBJECT_TREE;
return GIT_OBJECT_INVALID;
}
static int odb_read_hardcoded(bool *found, git_rawobj *raw, const git_oid *id)
{
git_object_t type;
*found = false;
if ((type = odb_hardcoded_type(id)) == GIT_OBJECT_INVALID)
return 0;
raw->type = type;
raw->len = 0;
raw->data = git__calloc(1, sizeof(uint8_t));
GIT_ERROR_CHECK_ALLOC(raw->data);
*found = true;
return 0;
}
int git_odb__format_object_header(
size_t *written,
char *hdr,
size_t hdr_size,
git_object_size_t obj_len,
git_object_t obj_type)
{
const char *type_str = git_object_type2string(obj_type);
int hdr_max = (hdr_size > INT_MAX-2) ? (INT_MAX-2) : (int)hdr_size;
int len;
len = p_snprintf(hdr, hdr_max, "%s %"PRId64, type_str, (int64_t)obj_len);
if (len < 0 || len >= hdr_max) {
git_error_set(GIT_ERROR_OS, "object header creation failed");
return -1;
}
*written = (size_t)(len + 1);
return 0;
}
int git_odb__hashobj(git_oid *id, git_rawobj *obj)
{
git_buf_vec vec[2];
char header[64];
size_t hdrlen;
int error;
GIT_ASSERT_ARG(id);
GIT_ASSERT_ARG(obj);
if (!git_object_typeisloose(obj->type)) {
git_error_set(GIT_ERROR_INVALID, "invalid object type");
return -1;
}
if (!obj->data && obj->len != 0) {
git_error_set(GIT_ERROR_INVALID, "invalid object");
return -1;
}
if ((error = git_odb__format_object_header(&hdrlen,
header, sizeof(header), obj->len, obj->type)) < 0)
return error;
vec[0].data = header;
vec[0].len = hdrlen;
vec[1].data = obj->data;
vec[1].len = obj->len;
return git_hash_vec(id, vec, 2);
}
static git_odb_object *odb_object__alloc(const git_oid *oid, git_rawobj *source)
{
git_odb_object *object = git__calloc(1, sizeof(git_odb_object));
if (object != NULL) {
git_oid_cpy(&object->cached.oid, oid);
object->cached.type = source->type;
object->cached.size = source->len;
object->buffer = source->data;
}
return object;
}
void git_odb_object__free(void *object)
{
if (object != NULL) {
git__free(((git_odb_object *)object)->buffer);
git__free(object);
}
}
const git_oid *git_odb_object_id(git_odb_object *object)
{
return &object->cached.oid;
}
const void *git_odb_object_data(git_odb_object *object)
{
return object->buffer;
}
size_t git_odb_object_size(git_odb_object *object)
{
return object->cached.size;
}
git_object_t git_odb_object_type(git_odb_object *object)
{
return object->cached.type;
}
int git_odb_object_dup(git_odb_object **dest, git_odb_object *source)
{
git_cached_obj_incref(source);
*dest = source;
return 0;
}
void git_odb_object_free(git_odb_object *object)
{
if (object == NULL)
return;
git_cached_obj_decref(object);
}
int git_odb__hashfd(git_oid *out, git_file fd, size_t size, git_object_t type)
{
size_t hdr_len;
char hdr[64], buffer[FILEIO_BUFSIZE];
git_hash_ctx ctx;
ssize_t read_len = 0;
int error = 0;
if (!git_object_typeisloose(type)) {
git_error_set(GIT_ERROR_INVALID, "invalid object type for hash");
return -1;
}
if ((error = git_hash_ctx_init(&ctx)) < 0)
return error;
if ((error = git_odb__format_object_header(&hdr_len, hdr,
sizeof(hdr), size, type)) < 0)
goto done;
if ((error = git_hash_update(&ctx, hdr, hdr_len)) < 0)
goto done;
while (size > 0 && (read_len = p_read(fd, buffer, sizeof(buffer))) > 0) {
if ((error = git_hash_update(&ctx, buffer, read_len)) < 0)
goto done;
size -= read_len;
}
/* If p_read returned an error code, the read obviously failed.
* If size is not zero, the file was truncated after we originally
* stat'd it, so we consider this a read failure too */
if (read_len < 0 || size > 0) {
git_error_set(GIT_ERROR_OS, "error reading file for hashing");
error = -1;
goto done;
}
error = git_hash_final(out, &ctx);
done:
git_hash_ctx_cleanup(&ctx);
return error;
}
int git_odb__hashfd_filtered(
git_oid *out, git_file fd, size_t size, git_object_t type, git_filter_list *fl)
{
int error;
git_buf raw = GIT_BUF_INIT;
if (!fl)
return git_odb__hashfd(out, fd, size, type);
/* size of data is used in header, so we have to read the whole file
* into memory to apply filters before beginning to calculate the hash
*/
if (!(error = git_futils_readbuffer_fd(&raw, fd, size))) {
git_buf post = GIT_BUF_INIT;
error = git_filter_list__convert_buf(&post, fl, &raw);
if (!error)
error = git_odb_hash(out, post.ptr, post.size, type);
git_buf_dispose(&post);
}
return error;
}
int git_odb__hashlink(git_oid *out, const char *path)
{
struct stat st;
int size;
int result;
if (git_path_lstat(path, &st) < 0)
return -1;
if (!git__is_int(st.st_size) || (int)st.st_size < 0) {
git_error_set(GIT_ERROR_FILESYSTEM, "file size overflow for 32-bit systems");
return -1;
}
size = (int)st.st_size;
if (S_ISLNK(st.st_mode)) {
char *link_data;
int read_len;
size_t alloc_size;
GIT_ERROR_CHECK_ALLOC_ADD(&alloc_size, size, 1);
link_data = git__malloc(alloc_size);
GIT_ERROR_CHECK_ALLOC(link_data);
read_len = p_readlink(path, link_data, size);
if (read_len == -1) {
git_error_set(GIT_ERROR_OS, "failed to read symlink data for '%s'", path);
git__free(link_data);
return -1;
}
GIT_ASSERT(read_len <= size);
link_data[read_len] = '\0';
result = git_odb_hash(out, link_data, read_len, GIT_OBJECT_BLOB);
git__free(link_data);
} else {
int fd = git_futils_open_ro(path);
if (fd < 0)
return -1;
result = git_odb__hashfd(out, fd, size, GIT_OBJECT_BLOB);
p_close(fd);
}
return result;
}
int git_odb_hashfile(git_oid *out, const char *path, git_object_t type)
{
uint64_t size;
int fd, error = 0;
if ((fd = git_futils_open_ro(path)) < 0)
return fd;
if ((error = git_futils_filesize(&size, fd)) < 0)
goto done;
if (!git__is_sizet(size)) {
git_error_set(GIT_ERROR_OS, "file size overflow for 32-bit systems");
error = -1;
goto done;
}
error = git_odb__hashfd(out, fd, (size_t)size, type);
done:
p_close(fd);
return error;
}
int git_odb_hash(git_oid *id, const void *data, size_t len, git_object_t type)
{
git_rawobj raw;
GIT_ASSERT_ARG(id);
raw.data = (void *)data;
raw.len = len;
raw.type = type;
return git_odb__hashobj(id, &raw);
}
/**
* FAKE WSTREAM
*/
typedef struct {
git_odb_stream stream;
char *buffer;
size_t size, written;
git_object_t type;
} fake_wstream;
static int fake_wstream__fwrite(git_odb_stream *_stream, const git_oid *oid)
{
fake_wstream *stream = (fake_wstream *)_stream;
return _stream->backend->write(_stream->backend, oid, stream->buffer, stream->size, stream->type);
}
static int fake_wstream__write(git_odb_stream *_stream, const char *data, size_t len)
{
fake_wstream *stream = (fake_wstream *)_stream;
GIT_ASSERT(stream->written + len <= stream->size);
memcpy(stream->buffer + stream->written, data, len);
stream->written += len;
return 0;
}
static void fake_wstream__free(git_odb_stream *_stream)
{
fake_wstream *stream = (fake_wstream *)_stream;
git__free(stream->buffer);
git__free(stream);
}
static int init_fake_wstream(git_odb_stream **stream_p, git_odb_backend *backend, git_object_size_t size, git_object_t type)
{
fake_wstream *stream;
size_t blobsize;
GIT_ERROR_CHECK_BLOBSIZE(size);
blobsize = (size_t)size;
stream = git__calloc(1, sizeof(fake_wstream));
GIT_ERROR_CHECK_ALLOC(stream);
stream->size = blobsize;
stream->type = type;
stream->buffer = git__malloc(blobsize);
if (stream->buffer == NULL) {
git__free(stream);
return -1;
}
stream->stream.backend = backend;
stream->stream.read = NULL; /* read only */
stream->stream.write = &fake_wstream__write;
stream->stream.finalize_write = &fake_wstream__fwrite;
stream->stream.free = &fake_wstream__free;
stream->stream.mode = GIT_STREAM_WRONLY;
*stream_p = (git_odb_stream *)stream;
return 0;
}
/***********************************************************
*
* OBJECT DATABASE PUBLIC API
*
* Public calls for the ODB functionality
*
***********************************************************/
static int backend_sort_cmp(const void *a, const void *b)
{
const backend_internal *backend_a = (const backend_internal *)(a);
const backend_internal *backend_b = (const backend_internal *)(b);
if (backend_b->priority == backend_a->priority) {
if (backend_a->is_alternate)
return -1;
if (backend_b->is_alternate)
return 1;
return 0;
}
return (backend_b->priority - backend_a->priority);
}
int git_odb_new(git_odb **out)
{
git_odb *db = git__calloc(1, sizeof(*db));
GIT_ERROR_CHECK_ALLOC(db);
if (git_mutex_init(&db->lock) < 0) {
git__free(db);
return -1;
}
if (git_cache_init(&db->own_cache) < 0) {
git_mutex_free(&db->lock);
git__free(db);
return -1;
}
if (git_vector_init(&db->backends, 4, backend_sort_cmp) < 0) {
git_cache_dispose(&db->own_cache);
git_mutex_free(&db->lock);
git__free(db);
return -1;
}
*out = db;
GIT_REFCOUNT_INC(db);
return 0;
}
static int add_backend_internal(
git_odb *odb, git_odb_backend *backend,
int priority, bool is_alternate, ino_t disk_inode)
{
backend_internal *internal;
GIT_ASSERT_ARG(odb);
GIT_ASSERT_ARG(backend);
GIT_ERROR_CHECK_VERSION(backend, GIT_ODB_BACKEND_VERSION, "git_odb_backend");
/* Check if the backend is already owned by another ODB */
GIT_ASSERT(!backend->odb || backend->odb == odb);
internal = git__malloc(sizeof(backend_internal));
GIT_ERROR_CHECK_ALLOC(internal);
internal->backend = backend;
internal->priority = priority;
internal->is_alternate = is_alternate;
internal->disk_inode = disk_inode;
if (git_mutex_lock(&odb->lock) < 0) {
git_error_set(GIT_ERROR_ODB, "failed to acquire the odb lock");
return -1;
}
if (git_vector_insert(&odb->backends, internal) < 0) {
git_mutex_unlock(&odb->lock);
git__free(internal);
return -1;
}
git_vector_sort(&odb->backends);
internal->backend->odb = odb;
git_mutex_unlock(&odb->lock);
return 0;
}
int git_odb_add_backend(git_odb *odb, git_odb_backend *backend, int priority)
{
return add_backend_internal(odb, backend, priority, false, 0);
}
int git_odb_add_alternate(git_odb *odb, git_odb_backend *backend, int priority)
{
return add_backend_internal(odb, backend, priority, true, 0);
}
size_t git_odb_num_backends(git_odb *odb)
{
size_t length;
bool locked = true;
GIT_ASSERT_ARG(odb);
if (git_mutex_lock(&odb->lock) < 0) {
git_error_set(GIT_ERROR_ODB, "failed to acquire the odb lock");
locked = false;
}
length = odb->backends.length;
if (locked)
git_mutex_unlock(&odb->lock);
return length;
}
static int git_odb__error_unsupported_in_backend(const char *action)
{
git_error_set(GIT_ERROR_ODB,
"cannot %s - unsupported in the loaded odb backends", action);
return -1;
}
int git_odb_get_backend(git_odb_backend **out, git_odb *odb, size_t pos)
{
backend_internal *internal;
int error;
GIT_ASSERT_ARG(out);
GIT_ASSERT_ARG(odb);
if ((error = git_mutex_lock(&odb->lock)) < 0) {
git_error_set(GIT_ERROR_ODB, "failed to acquire the odb lock");
return error;
}
internal = git_vector_get(&odb->backends, pos);
if (!internal || !internal->backend) {
git_mutex_unlock(&odb->lock);
git_error_set(GIT_ERROR_ODB, "no ODB backend loaded at index %" PRIuZ, pos);
return GIT_ENOTFOUND;
}
*out = internal->backend;
git_mutex_unlock(&odb->lock);
return 0;
}
int git_odb__add_default_backends(
git_odb *db, const char *objects_dir,
bool as_alternates, int alternate_depth)
{
size_t i = 0;
struct stat st;
ino_t inode;
git_odb_backend *loose, *packed;
/* TODO: inodes are not really relevant on Win32, so we need to find
* a cross-platform workaround for this */
#ifdef GIT_WIN32
GIT_UNUSED(i);
GIT_UNUSED(&st);
inode = 0;
#else
if (p_stat(objects_dir, &st) < 0) {
if (as_alternates)
/* this should warn */
return 0;
git_error_set(GIT_ERROR_ODB, "failed to load object database in '%s'", objects_dir);
return -1;
}
inode = st.st_ino;
if (git_mutex_lock(&db->lock) < 0) {
git_error_set(GIT_ERROR_ODB, "failed to acquire the odb lock");
return -1;
}
for (i = 0; i < db->backends.length; ++i) {
backend_internal *backend = git_vector_get(&db->backends, i);
if (backend->disk_inode == inode) {
git_mutex_unlock(&db->lock);
return 0;
}
}
git_mutex_unlock(&db->lock);
#endif
/* add the loose object backend */
if (git_odb_backend_loose(&loose, objects_dir, -1, db->do_fsync, 0, 0) < 0 ||
add_backend_internal(db, loose, git_odb__loose_priority, as_alternates, inode) < 0)
return -1;
/* add the packed file backend */
if (git_odb_backend_pack(&packed, objects_dir) < 0 ||
add_backend_internal(db, packed, git_odb__packed_priority, as_alternates, inode) < 0)
return -1;
if (git_mutex_lock(&db->lock) < 0) {
git_error_set(GIT_ERROR_ODB, "failed to acquire the odb lock");
return -1;
}
if (!db->cgraph && git_commit_graph_new(&db->cgraph, objects_dir, false) < 0) {
git_mutex_unlock(&db->lock);
return -1;
}
git_mutex_unlock(&db->lock);
return load_alternates(db, objects_dir, alternate_depth);
}
static int load_alternates(git_odb *odb, const char *objects_dir, int alternate_depth)
{
git_buf alternates_path = GIT_BUF_INIT;
git_buf alternates_buf = GIT_BUF_INIT;
char *buffer;
const char *alternate;
int result = 0;
/* Git reports an error, we just ignore anything deeper */
if (alternate_depth > GIT_ALTERNATES_MAX_DEPTH)
return 0;
if (git_buf_joinpath(&alternates_path, objects_dir, GIT_ALTERNATES_FILE) < 0)
return -1;
if (git_path_exists(alternates_path.ptr) == false) {
git_buf_dispose(&alternates_path);
return 0;
}
if (git_futils_readbuffer(&alternates_buf, alternates_path.ptr) < 0) {
git_buf_dispose(&alternates_path);
return -1;
}
buffer = (char *)alternates_buf.ptr;
/* add each alternate as a new backend; one alternate per line */
while ((alternate = git__strtok(&buffer, "\r\n")) != NULL) {
if (*alternate == '\0' || *alternate == '#')
continue;
/*
* Relative path: build based on the current `objects`
* folder. However, relative paths are only allowed in
* the current repository.
*/
if (*alternate == '.' && !alternate_depth) {
if ((result = git_buf_joinpath(&alternates_path, objects_dir, alternate)) < 0)
break;
alternate = git_buf_cstr(&alternates_path);
}
if ((result = git_odb__add_default_backends(odb, alternate, true, alternate_depth + 1)) < 0)
break;
}
git_buf_dispose(&alternates_path);
git_buf_dispose(&alternates_buf);
return result;
}
int git_odb_add_disk_alternate(git_odb *odb, const char *path)
{
return git_odb__add_default_backends(odb, path, true, 0);
}
int git_odb_set_commit_graph(git_odb *odb, git_commit_graph *cgraph)
{
int error = 0;
GIT_ASSERT_ARG(odb);
if ((error = git_mutex_lock(&odb->lock)) < 0) {
git_error_set(GIT_ERROR_ODB, "failed to acquire the db lock");
return error;
}
git_commit_graph_free(odb->cgraph);
odb->cgraph = cgraph;
git_mutex_unlock(&odb->lock);
return error;
}
int git_odb_open(git_odb **out, const char *objects_dir)
{
git_odb *db;
GIT_ASSERT_ARG(out);
GIT_ASSERT_ARG(objects_dir);
*out = NULL;
if (git_odb_new(&db) < 0)
return -1;
if (git_odb__add_default_backends(db, objects_dir, 0, 0) < 0) {
git_odb_free(db);
return -1;
}
*out = db;
return 0;
}
int git_odb__set_caps(git_odb *odb, int caps)
{
if (caps == GIT_ODB_CAP_FROM_OWNER) {
git_repository *repo = GIT_REFCOUNT_OWNER(odb);
int val;
if (!repo) {
git_error_set(GIT_ERROR_ODB, "cannot access repository to set odb caps");
return -1;
}
if (!git_repository__configmap_lookup(&val, repo, GIT_CONFIGMAP_FSYNCOBJECTFILES))
odb->do_fsync = !!val;
}
return 0;
}
static void odb_free(git_odb *db)
{
size_t i;
bool locked = true;
if (git_mutex_lock(&db->lock) < 0) {
git_error_set(GIT_ERROR_ODB, "failed to acquire the odb lock");
locked = false;
}
for (i = 0; i < db->backends.length; ++i) {
backend_internal *internal = git_vector_get(&db->backends, i);
git_odb_backend *backend = internal->backend;
backend->free(backend);
git__free(internal);
}
if (locked)
git_mutex_unlock(&db->lock);
git_commit_graph_free(db->cgraph);
git_vector_free(&db->backends);
git_cache_dispose(&db->own_cache);
git_mutex_free(&db->lock);
git__memzero(db, sizeof(*db));
git__free(db);
}
void git_odb_free(git_odb *db)
{
if (db == NULL)
return;
GIT_REFCOUNT_DEC(db, odb_free);
}
static int odb_exists_1(
git_odb *db,
const git_oid *id,
bool only_refreshed)
{
size_t i;
bool found = false;
int error;
if ((error = git_mutex_lock(&db->lock)) < 0) {
git_error_set(GIT_ERROR_ODB, "failed to acquire the odb lock");
return error;
}
for (i = 0; i < db->backends.length && !found; ++i) {
backend_internal *internal = git_vector_get(&db->backends, i);
git_odb_backend *b = internal->backend;
if (only_refreshed && !b->refresh)
continue;
if (b->exists != NULL)
found = (bool)b->exists(b, id);
}
git_mutex_unlock(&db->lock);
return (int)found;
}
int git_odb__get_commit_graph_file(git_commit_graph_file **out, git_odb *db)
{
int error = 0;
git_commit_graph_file *result = NULL;
if ((error = git_mutex_lock(&db->lock)) < 0) {
git_error_set(GIT_ERROR_ODB, "failed to acquire the db lock");
return error;
}
if (!db->cgraph) {
error = GIT_ENOTFOUND;
goto done;
}
error = git_commit_graph_get_file(&result, db->cgraph);
if (error)
goto done;
*out = result;
done:
git_mutex_unlock(&db->lock);
return error;
}
static int odb_freshen_1(
git_odb *db,
const git_oid *id,
bool only_refreshed)
{
size_t i;
bool found = false;
int error;
if ((error = git_mutex_lock(&db->lock)) < 0) {
git_error_set(GIT_ERROR_ODB, "failed to acquire the odb lock");
return error;
}
for (i = 0; i < db->backends.length && !found; ++i) {
backend_internal *internal = git_vector_get(&db->backends, i);
git_odb_backend *b = internal->backend;
if (only_refreshed && !b->refresh)
continue;
if (b->freshen != NULL)
found = !b->freshen(b, id);
else if (b->exists != NULL)
found = b->exists(b, id);
}
git_mutex_unlock(&db->lock);
return (int)found;
}
int git_odb__freshen(git_odb *db, const git_oid *id)
{
GIT_ASSERT_ARG(db);
GIT_ASSERT_ARG(id);
if (odb_freshen_1(db, id, false))
return 1;
if (!git_odb_refresh(db))
return odb_freshen_1(db, id, true);
/* Failed to refresh, hence not found */
return 0;
}
int git_odb_exists(git_odb *db, const git_oid *id)
{
git_odb_object *object;
GIT_ASSERT_ARG(db);
GIT_ASSERT_ARG(id);
if (git_oid_is_zero(id))
return 0;
if ((object = git_cache_get_raw(odb_cache(db), id)) != NULL) {
git_odb_object_free(object);
return 1;
}
if (odb_exists_1(db, id, false))
return 1;
if (!git_odb_refresh(db))
return odb_exists_1(db, id, true);
/* Failed to refresh, hence not found */
return 0;
}
static int odb_exists_prefix_1(git_oid *out, git_odb *db,
const git_oid *key, size_t len, bool only_refreshed)
{
size_t i;
int error = GIT_ENOTFOUND, num_found = 0;
git_oid last_found = {{0}}, found;
if ((error = git_mutex_lock(&db->lock)) < 0) {
git_error_set(GIT_ERROR_ODB, "failed to acquire the odb lock");
return error;
}
error = GIT_ENOTFOUND;
for (i = 0; i < db->backends.length; ++i) {
backend_internal *internal = git_vector_get(&db->backends, i);
git_odb_backend *b = internal->backend;
if (only_refreshed && !b->refresh)
continue;
if (!b->exists_prefix)
continue;
error = b->exists_prefix(&found, b, key, len);
if (error == GIT_ENOTFOUND || error == GIT_PASSTHROUGH)
continue;
if (error) {
git_mutex_unlock(&db->lock);
return error;
}
/* make sure found item doesn't introduce ambiguity */
if (num_found) {
if (git_oid__cmp(&last_found, &found)) {
git_mutex_unlock(&db->lock);
return git_odb__error_ambiguous("multiple matches for prefix");
}
} else {
git_oid_cpy(&last_found, &found);
num_found++;
}
}
git_mutex_unlock(&db->lock);
if (!num_found)
return GIT_ENOTFOUND;
if (out)
git_oid_cpy(out, &last_found);
return 0;
}
int git_odb_exists_prefix(
git_oid *out, git_odb *db, const git_oid *short_id, size_t len)
{
int error;
git_oid key = {{0}};
GIT_ASSERT_ARG(db);
GIT_ASSERT_ARG(short_id);
if (len < GIT_OID_MINPREFIXLEN)
return git_odb__error_ambiguous("prefix length too short");
if (len >= GIT_OID_HEXSZ) {
if (git_odb_exists(db, short_id)) {
if (out)
git_oid_cpy(out, short_id);
return 0;
} else {
return git_odb__error_notfound(
"no match for id prefix", short_id, len);
}
}
git_oid__cpy_prefix(&key, short_id, len);
error = odb_exists_prefix_1(out, db, &key, len, false);
if (error == GIT_ENOTFOUND && !git_odb_refresh(db))
error = odb_exists_prefix_1(out, db, &key, len, true);
if (error == GIT_ENOTFOUND)
return git_odb__error_notfound("no match for id prefix", &key, len);
return error;
}
int git_odb_expand_ids(
git_odb *db,
git_odb_expand_id *ids,
size_t count)
{
size_t i;
GIT_ASSERT_ARG(db);
GIT_ASSERT_ARG(ids);
for (i = 0; i < count; i++) {
git_odb_expand_id *query = &ids[i];
int error = GIT_EAMBIGUOUS;
if (!query->type)
query->type = GIT_OBJECT_ANY;
/* if we have a short OID, expand it first */
if (query->length >= GIT_OID_MINPREFIXLEN && query->length < GIT_OID_HEXSZ) {
git_oid actual_id;
error = odb_exists_prefix_1(&actual_id, db, &query->id, query->length, false);
if (!error) {
git_oid_cpy(&query->id, &actual_id);
query->length = GIT_OID_HEXSZ;
}
}
/*
* now we ought to have a 40-char OID, either because we've expanded it
* or because the user passed a full OID. Ensure its type is right.
*/
if (query->length >= GIT_OID_HEXSZ) {
git_object_t actual_type;
error = odb_otype_fast(&actual_type, db, &query->id);
if (!error) {
if (query->type != GIT_OBJECT_ANY && query->type != actual_type)
error = GIT_ENOTFOUND;
else
query->type = actual_type;
}
}
switch (error) {
/* no errors, so we've successfully expanded the OID */
case 0:
continue;
/* the object is missing or ambiguous */
case GIT_ENOTFOUND:
case GIT_EAMBIGUOUS:
memset(&query->id, 0, sizeof(git_oid));
query->length = 0;
query->type = 0;
break;
/* something went very wrong with the ODB; bail hard */
default:
return error;
}
}
git_error_clear();
return 0;
}
int git_odb_read_header(size_t *len_p, git_object_t *type_p, git_odb *db, const git_oid *id)
{
int error;
git_odb_object *object;
error = git_odb__read_header_or_object(&object, len_p, type_p, db, id);
if (object)
git_odb_object_free(object);
return error;
}
static int odb_read_header_1(
size_t *len_p, git_object_t *type_p, git_odb *db,
const git_oid *id, bool only_refreshed)
{
size_t i;
git_object_t ht;
bool passthrough = false;
int error;
if (!only_refreshed && (ht = odb_hardcoded_type(id)) != GIT_OBJECT_INVALID) {
*type_p = ht;
*len_p = 0;
return 0;
}
if ((error = git_mutex_lock(&db->lock)) < 0) {
git_error_set(GIT_ERROR_ODB, "failed to acquire the odb lock");
return error;
}
for (i = 0; i < db->backends.length; ++i) {
backend_internal *internal = git_vector_get(&db->backends, i);
git_odb_backend *b = internal->backend;
if (only_refreshed && !b->refresh)
continue;
if (!b->read_header) {
passthrough = true;
continue;
}
error = b->read_header(len_p, type_p, b, id);
switch (error) {
case GIT_PASSTHROUGH:
passthrough = true;
break;
case GIT_ENOTFOUND:
break;
default:
git_mutex_unlock(&db->lock);
return error;
}
}
git_mutex_unlock(&db->lock);
return passthrough ? GIT_PASSTHROUGH : GIT_ENOTFOUND;
}
int git_odb__read_header_or_object(
git_odb_object **out, size_t *len_p, git_object_t *type_p,
git_odb *db, const git_oid *id)
{
int error = GIT_ENOTFOUND;
git_odb_object *object;
GIT_ASSERT_ARG(db);
GIT_ASSERT_ARG(id);
GIT_ASSERT_ARG(out);
GIT_ASSERT_ARG(len_p);
GIT_ASSERT_ARG(type_p);
*out = NULL;
if (git_oid_is_zero(id))
return error_null_oid(GIT_ENOTFOUND, "cannot read object");
if ((object = git_cache_get_raw(odb_cache(db), id)) != NULL) {
*len_p = object->cached.size;
*type_p = object->cached.type;
*out = object;
return 0;
}
error = odb_read_header_1(len_p, type_p, db, id, false);
if (error == GIT_ENOTFOUND && !git_odb_refresh(db))
error = odb_read_header_1(len_p, type_p, db, id, true);
if (error == GIT_ENOTFOUND)
return git_odb__error_notfound("cannot read header for", id, GIT_OID_HEXSZ);
/* we found the header; return early */
if (!error)
return 0;
if (error == GIT_PASSTHROUGH) {
/*
* no backend has header-reading functionality
* so try using `git_odb_read` instead
*/
error = git_odb_read(&object, db, id);
if (!error) {
*len_p = object->cached.size;
*type_p = object->cached.type;
*out = object;
}
}
return error;
}
static int odb_read_1(git_odb_object **out, git_odb *db, const git_oid *id,
bool only_refreshed)
{
size_t i;
git_rawobj raw;
git_odb_object *object;
git_oid hashed;
bool found = false;
int error = 0;
if (!only_refreshed) {
if ((error = odb_read_hardcoded(&found, &raw, id)) < 0)
return error;
}
if ((error = git_mutex_lock(&db->lock)) < 0) {
git_error_set(GIT_ERROR_ODB, "failed to acquire the odb lock");
return error;
}
for (i = 0; i < db->backends.length && !found; ++i) {
backend_internal *internal = git_vector_get(&db->backends, i);
git_odb_backend *b = internal->backend;
if (only_refreshed && !b->refresh)
continue;
if (b->read != NULL) {
error = b->read(&raw.data, &raw.len, &raw.type, b, id);
if (error == GIT_PASSTHROUGH || error == GIT_ENOTFOUND)
continue;
if (error < 0) {
git_mutex_unlock(&db->lock);
return error;
}
found = true;
}
}
git_mutex_unlock(&db->lock);
if (!found)
return GIT_ENOTFOUND;
if (git_odb__strict_hash_verification) {
if ((error = git_odb_hash(&hashed, raw.data, raw.len, raw.type)) < 0)
goto out;
if (!git_oid_equal(id, &hashed)) {
error = git_odb__error_mismatch(id, &hashed);
goto out;
}
}
git_error_clear();
if ((object = odb_object__alloc(id, &raw)) == NULL) {
error = -1;
goto out;
}
*out = git_cache_store_raw(odb_cache(db), object);
out:
if (error)
git__free(raw.data);
return error;
}
int git_odb_read(git_odb_object **out, git_odb *db, const git_oid *id)
{
int error;
GIT_ASSERT_ARG(out);
GIT_ASSERT_ARG(db);
GIT_ASSERT_ARG(id);
if (git_oid_is_zero(id))
return error_null_oid(GIT_ENOTFOUND, "cannot read object");
*out = git_cache_get_raw(odb_cache(db), id);
if (*out != NULL)
return 0;
error = odb_read_1(out, db, id, false);
if (error == GIT_ENOTFOUND && !git_odb_refresh(db))
error = odb_read_1(out, db, id, true);
if (error == GIT_ENOTFOUND)
return git_odb__error_notfound("no match for id", id, GIT_OID_HEXSZ);
return error;
}
static int odb_otype_fast(git_object_t *type_p, git_odb *db, const git_oid *id)
{
git_odb_object *object;
size_t _unused;
int error;
if (git_oid_is_zero(id))
return error_null_oid(GIT_ENOTFOUND, "cannot get object type");
if ((object = git_cache_get_raw(odb_cache(db), id)) != NULL) {
*type_p = object->cached.type;
git_odb_object_free(object);
return 0;
}
error = odb_read_header_1(&_unused, type_p, db, id, false);
if (error == GIT_PASSTHROUGH) {
error = odb_read_1(&object, db, id, false);
if (!error)
*type_p = object->cached.type;
git_odb_object_free(object);
}
return error;
}
static int read_prefix_1(git_odb_object **out, git_odb *db,
const git_oid *key, size_t len, bool only_refreshed)
{
size_t i;
int error = 0;
git_oid found_full_oid = {{0}};
git_rawobj raw = {0};
void *data = NULL;
bool found = false;
git_odb_object *object;
if ((error = git_mutex_lock(&db->lock)) < 0) {
git_error_set(GIT_ERROR_ODB, "failed to acquire the odb lock");
return error;
}
for (i = 0; i < db->backends.length; ++i) {
backend_internal *internal = git_vector_get(&db->backends, i);
git_odb_backend *b = internal->backend;
if (only_refreshed && !b->refresh)
continue;
if (b->read_prefix != NULL) {
git_oid full_oid;
error = b->read_prefix(&full_oid, &raw.data, &raw.len, &raw.type, b, key, len);
if (error == GIT_ENOTFOUND || error == GIT_PASSTHROUGH) {
error = 0;
continue;
}
if (error) {
git_mutex_unlock(&db->lock);
goto out;
}
git__free(data);
data = raw.data;
if (found && git_oid__cmp(&full_oid, &found_full_oid)) {
git_buf buf = GIT_BUF_INIT;
git_buf_printf(&buf, "multiple matches for prefix: %s",
git_oid_tostr_s(&full_oid));
git_buf_printf(&buf, " %s",
git_oid_tostr_s(&found_full_oid));
error = git_odb__error_ambiguous(buf.ptr);
git_buf_dispose(&buf);
git_mutex_unlock(&db->lock);
goto out;
}
found_full_oid = full_oid;
found = true;
}
}
git_mutex_unlock(&db->lock);
if (!found)
return GIT_ENOTFOUND;
if (git_odb__strict_hash_verification) {
git_oid hash;
if ((error = git_odb_hash(&hash, raw.data, raw.len, raw.type)) < 0)
goto out;
if (!git_oid_equal(&found_full_oid, &hash)) {
error = git_odb__error_mismatch(&found_full_oid, &hash);
goto out;
}
}
if ((object = odb_object__alloc(&found_full_oid, &raw)) == NULL) {
error = -1;
goto out;
}
*out = git_cache_store_raw(odb_cache(db), object);
out:
if (error)
git__free(raw.data);
return error;
}
int git_odb_read_prefix(
git_odb_object **out, git_odb *db, const git_oid *short_id, size_t len)
{
git_oid key = {{0}};
int error;
GIT_ASSERT_ARG(out);
GIT_ASSERT_ARG(db);
if (len < GIT_OID_MINPREFIXLEN)
return git_odb__error_ambiguous("prefix length too short");
if (len > GIT_OID_HEXSZ)
len = GIT_OID_HEXSZ;
if (len == GIT_OID_HEXSZ) {
*out = git_cache_get_raw(odb_cache(db), short_id);
if (*out != NULL)
return 0;
}
git_oid__cpy_prefix(&key, short_id, len);
error = read_prefix_1(out, db, &key, len, false);
if (error == GIT_ENOTFOUND && !git_odb_refresh(db))
error = read_prefix_1(out, db, &key, len, true);
if (error == GIT_ENOTFOUND)
return git_odb__error_notfound("no match for prefix", &key, len);
return error;
}
int git_odb_foreach(git_odb *db, git_odb_foreach_cb cb, void *payload)
{
unsigned int i;
git_vector backends = GIT_VECTOR_INIT;
backend_internal *internal;
int error = 0;
/* Make a copy of the backends vector to invoke the callback without holding the lock. */
if ((error = git_mutex_lock(&db->lock)) < 0) {
git_error_set(GIT_ERROR_ODB, "failed to acquire the odb lock");
goto cleanup;
}
error = git_vector_dup(&backends, &db->backends, NULL);
git_mutex_unlock(&db->lock);
if (error < 0)
goto cleanup;
git_vector_foreach(&backends, i, internal) {
git_odb_backend *b = internal->backend;
error = b->foreach(b, cb, payload);
if (error != 0)
goto cleanup;
}
cleanup:
git_vector_free(&backends);
return error;
}
int git_odb_write(
git_oid *oid, git_odb *db, const void *data, size_t len, git_object_t type)
{
size_t i;
int error;
git_odb_stream *stream;
GIT_ASSERT_ARG(oid);
GIT_ASSERT_ARG(db);
if ((error = git_odb_hash(oid, data, len, type)) < 0)
return error;
if (git_oid_is_zero(oid))
return error_null_oid(GIT_EINVALID, "cannot write object");
if (git_odb__freshen(db, oid))
return 0;
if ((error = git_mutex_lock(&db->lock)) < 0) {
git_error_set(GIT_ERROR_ODB, "failed to acquire the odb lock");
return error;
}
for (i = 0, error = GIT_ERROR; i < db->backends.length && error < 0; ++i) {
backend_internal *internal = git_vector_get(&db->backends, i);
git_odb_backend *b = internal->backend;
/* we don't write in alternates! */
if (internal->is_alternate)
continue;
if (b->write != NULL)
error = b->write(b, oid, data, len, type);
}
git_mutex_unlock(&db->lock);
if (!error || error == GIT_PASSTHROUGH)
return 0;
/* if no backends were able to write the object directly, we try a
* streaming write to the backends; just write the whole object into the
* stream in one push
*/
if ((error = git_odb_open_wstream(&stream, db, len, type)) != 0)
return error;
stream->write(stream, data, len);
error = stream->finalize_write(stream, oid);
git_odb_stream_free(stream);
return error;
}
static int hash_header(git_hash_ctx *ctx, git_object_size_t size, git_object_t type)
{
char header[64];
size_t hdrlen;
int error;
if ((error = git_odb__format_object_header(&hdrlen,
header, sizeof(header), size, type)) < 0)
return error;
return git_hash_update(ctx, header, hdrlen);
}
int git_odb_open_wstream(
git_odb_stream **stream, git_odb *db, git_object_size_t size, git_object_t type)
{
size_t i, writes = 0;
int error = GIT_ERROR;
git_hash_ctx *ctx = NULL;
GIT_ASSERT_ARG(stream);
GIT_ASSERT_ARG(db);
if ((error = git_mutex_lock(&db->lock)) < 0) {
git_error_set(GIT_ERROR_ODB, "failed to acquire the odb lock");
return error;
}
error = GIT_ERROR;
for (i = 0; i < db->backends.length && error < 0; ++i) {
backend_internal *internal = git_vector_get(&db->backends, i);
git_odb_backend *b = internal->backend;
/* we don't write in alternates! */
if (internal->is_alternate)
continue;
if (b->writestream != NULL) {
++writes;
error = b->writestream(stream, b, size, type);
} else if (b->write != NULL) {
++writes;
error = init_fake_wstream(stream, b, size, type);
}
}
git_mutex_unlock(&db->lock);
if (error < 0) {
if (error == GIT_PASSTHROUGH)
error = 0;
else if (!writes)
error = git_odb__error_unsupported_in_backend("write object");
goto done;
}
ctx = git__malloc(sizeof(git_hash_ctx));
GIT_ERROR_CHECK_ALLOC(ctx);
if ((error = git_hash_ctx_init(ctx)) < 0 ||
(error = hash_header(ctx, size, type)) < 0)
goto done;
(*stream)->hash_ctx = ctx;
(*stream)->declared_size = size;
(*stream)->received_bytes = 0;
done:
if (error)
git__free(ctx);
return error;
}
static int git_odb_stream__invalid_length(
const git_odb_stream *stream,
const char *action)
{
git_error_set(GIT_ERROR_ODB,
"cannot %s - "
"Invalid length. %"PRId64" was expected. The "
"total size of the received chunks amounts to %"PRId64".",
action, stream->declared_size, stream->received_bytes);
return -1;
}
int git_odb_stream_write(git_odb_stream *stream, const char *buffer, size_t len)
{
git_hash_update(stream->hash_ctx, buffer, len);
stream->received_bytes += len;
if (stream->received_bytes > stream->declared_size)
return git_odb_stream__invalid_length(stream,
"stream_write()");
return stream->write(stream, buffer, len);
}
int git_odb_stream_finalize_write(git_oid *out, git_odb_stream *stream)
{
if (stream->received_bytes != stream->declared_size)
return git_odb_stream__invalid_length(stream,
"stream_finalize_write()");
git_hash_final(out, stream->hash_ctx);
if (git_odb__freshen(stream->backend->odb, out))
return 0;
return stream->finalize_write(stream, out);
}
int git_odb_stream_read(git_odb_stream *stream, char *buffer, size_t len)
{
return stream->read(stream, buffer, len);
}
void git_odb_stream_free(git_odb_stream *stream)
{
if (stream == NULL)
return;
git_hash_ctx_cleanup(stream->hash_ctx);
git__free(stream->hash_ctx);
stream->free(stream);
}
int git_odb_open_rstream(
git_odb_stream **stream,
size_t *len,
git_object_t *type,
git_odb *db,
const git_oid *oid)
{
size_t i, reads = 0;
int error = GIT_ERROR;
GIT_ASSERT_ARG(stream);
GIT_ASSERT_ARG(db);
if ((error = git_mutex_lock(&db->lock)) < 0) {
git_error_set(GIT_ERROR_ODB, "failed to acquire the odb lock");
return error;
}
error = GIT_ERROR;
for (i = 0; i < db->backends.length && error < 0; ++i) {
backend_internal *internal = git_vector_get(&db->backends, i);
git_odb_backend *b = internal->backend;
if (b->readstream != NULL) {
++reads;
error = b->readstream(stream, len, type, b, oid);
}
}
git_mutex_unlock(&db->lock);
if (error == GIT_PASSTHROUGH)
error = 0;
if (error < 0 && !reads)
error = git_odb__error_unsupported_in_backend("read object streamed");
return error;
}
int git_odb_write_pack(struct git_odb_writepack **out, git_odb *db, git_indexer_progress_cb progress_cb, void *progress_payload)
{
size_t i, writes = 0;
int error = GIT_ERROR;
GIT_ASSERT_ARG(out);
GIT_ASSERT_ARG(db);
if ((error = git_mutex_lock(&db->lock)) < 0) {
git_error_set(GIT_ERROR_ODB, "failed to acquire the odb lock");
return error;
}
error = GIT_ERROR;
for (i = 0; i < db->backends.length && error < 0; ++i) {
backend_internal *internal = git_vector_get(&db->backends, i);
git_odb_backend *b = internal->backend;
/* we don't write in alternates! */
if (internal->is_alternate)
continue;
if (b->writepack != NULL) {
++writes;
error = b->writepack(out, b, db, progress_cb, progress_payload);
}
}
git_mutex_unlock(&db->lock);
if (error == GIT_PASSTHROUGH)
error = 0;
if (error < 0 && !writes)
error = git_odb__error_unsupported_in_backend("write pack");
return error;
}
int git_odb_write_multi_pack_index(git_odb *db)
{
size_t i, writes = 0;
int error = GIT_ERROR;
GIT_ASSERT_ARG(db);
for (i = 0; i < db->backends.length && error < 0; ++i) {
backend_internal *internal = git_vector_get(&db->backends, i);
git_odb_backend *b = internal->backend;
/* we don't write in alternates! */
if (internal->is_alternate)
continue;
if (b->writemidx != NULL) {
++writes;
error = b->writemidx(b);
}
}
if (error == GIT_PASSTHROUGH)
error = 0;
if (error < 0 && !writes)
error = git_odb__error_unsupported_in_backend("write multi-pack-index");
return error;
}
void *git_odb_backend_data_alloc(git_odb_backend *backend, size_t len)
{
GIT_UNUSED(backend);
return git__malloc(len);
}
#ifndef GIT_DEPRECATE_HARD
void *git_odb_backend_malloc(git_odb_backend *backend, size_t len)
{
return git_odb_backend_data_alloc(backend, len);
}
#endif
void git_odb_backend_data_free(git_odb_backend *backend, void *data)
{
GIT_UNUSED(backend);
git__free(data);
}
int git_odb_refresh(struct git_odb *db)
{
size_t i;
int error;
GIT_ASSERT_ARG(db);
if ((error = git_mutex_lock(&db->lock)) < 0) {
git_error_set(GIT_ERROR_ODB, "failed to acquire the odb lock");
return error;
}
for (i = 0; i < db->backends.length; ++i) {
backend_internal *internal = git_vector_get(&db->backends, i);
git_odb_backend *b = internal->backend;
if (b->refresh != NULL) {
int error = b->refresh(b);
if (error < 0) {
git_mutex_unlock(&db->lock);
return error;
}
}
}
if (db->cgraph)
git_commit_graph_refresh(db->cgraph);
git_mutex_unlock(&db->lock);
return 0;
}
int git_odb__error_mismatch(const git_oid *expected, const git_oid *actual)
{
char expected_oid[GIT_OID_HEXSZ + 1], actual_oid[GIT_OID_HEXSZ + 1];
git_oid_tostr(expected_oid, sizeof(expected_oid), expected);
git_oid_tostr(actual_oid, sizeof(actual_oid), actual);
git_error_set(GIT_ERROR_ODB, "object hash mismatch - expected %s but got %s",
expected_oid, actual_oid);
return GIT_EMISMATCH;
}
int git_odb__error_notfound(
const char *message, const git_oid *oid, size_t oid_len)
{
if (oid != NULL) {
char oid_str[GIT_OID_HEXSZ + 1];
git_oid_tostr(oid_str, oid_len+1, oid);
git_error_set(GIT_ERROR_ODB, "object not found - %s (%.*s)",
message, (int) oid_len, oid_str);
} else
git_error_set(GIT_ERROR_ODB, "object not found - %s", message);
return GIT_ENOTFOUND;
}
static int error_null_oid(int error, const char *message)
{
git_error_set(GIT_ERROR_ODB, "odb: %s: null OID cannot exist", message);
return error;
}
int git_odb__error_ambiguous(const char *message)
{
git_error_set(GIT_ERROR_ODB, "ambiguous SHA1 prefix - %s", message);
return GIT_EAMBIGUOUS;
}
int git_odb_init_backend(git_odb_backend *backend, unsigned int version)
{
GIT_INIT_STRUCTURE_FROM_TEMPLATE(
backend, version, git_odb_backend, GIT_ODB_BACKEND_INIT);
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/net.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_net_h__
#define INCLUDE_net_h__
#include "common.h"
typedef struct git_net_url {
char *scheme;
char *host;
char *port;
char *path;
char *query;
char *username;
char *password;
} git_net_url;
#define GIT_NET_URL_INIT { NULL }
/** Duplicate a URL */
extern int git_net_url_dup(git_net_url *out, git_net_url *in);
/** Parses a string containing a URL into a structure. */
extern int git_net_url_parse(git_net_url *url, const char *str);
/** Appends a path and/or query string to the given URL */
extern int git_net_url_joinpath(
git_net_url *out,
git_net_url *in,
const char *path);
/** Ensures that a URL is minimally valid (contains a host, port and path) */
extern bool git_net_url_valid(git_net_url *url);
/** Returns true if the URL is on the default port. */
extern bool git_net_url_is_default_port(git_net_url *url);
/** Returns true if the host portion of the URL is an ipv6 address. */
extern bool git_net_url_is_ipv6(git_net_url *url);
/* Applies a redirect to the URL with a git-aware service suffix. */
extern int git_net_url_apply_redirect(
git_net_url *url,
const char *redirect_location,
const char *service_suffix);
/** Swaps the contents of one URL for another. */
extern void git_net_url_swap(git_net_url *a, git_net_url *b);
/** Places the URL into the given buffer. */
extern int git_net_url_fmt(git_buf *out, git_net_url *url);
/** Place the path and query string into the given buffer. */
extern int git_net_url_fmt_path(git_buf *buf, git_net_url *url);
/** Determines if the url matches given pattern or pattern list */
extern bool git_net_url_matches_pattern(
git_net_url *url,
const char *pattern);
extern bool git_net_url_matches_pattern_list(
git_net_url *url,
const char *pattern_list);
/** Disposes the contents of the structure. */
extern void git_net_url_dispose(git_net_url *url);
#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/blame.h
|
#ifndef INCLUDE_blame_h__
#define INCLUDE_blame_h__
#include "common.h"
#include "git2/blame.h"
#include "vector.h"
#include "diff.h"
#include "array.h"
#include "git2/oid.h"
/*
* One blob in a commit that is being suspected
*/
typedef struct git_blame__origin {
int refcnt;
struct git_blame__origin *previous;
git_commit *commit;
git_blob *blob;
char path[GIT_FLEX_ARRAY];
} git_blame__origin;
/*
* Each group of lines is described by a git_blame__entry; it can be split
* as we pass blame to the parents. They form a linked list in the
* scoreboard structure, sorted by the target line number.
*/
typedef struct git_blame__entry {
struct git_blame__entry *prev;
struct git_blame__entry *next;
/* the first line of this group in the final image;
* internally all line numbers are 0 based.
*/
size_t lno;
/* how many lines this group has */
size_t num_lines;
/* the commit that introduced this group into the final image */
git_blame__origin *suspect;
/* true if the suspect is truly guilty; false while we have not
* checked if the group came from one of its parents.
*/
bool guilty;
/* true if the entry has been scanned for copies in the current parent
*/
bool scanned;
/* the line number of the first line of this group in the
* suspect's file; internally all line numbers are 0 based.
*/
size_t s_lno;
/* how significant this entry is -- cached to avoid
* scanning the lines over and over.
*/
unsigned score;
/* Whether this entry has been tracked to a boundary commit.
*/
bool is_boundary;
} git_blame__entry;
struct git_blame {
char *path;
git_repository *repository;
git_mailmap *mailmap;
git_blame_options options;
git_vector hunks;
git_vector paths;
git_blob *final_blob;
git_array_t(size_t) line_index;
size_t current_diff_line;
git_blame_hunk *current_hunk;
/* Scoreboard fields */
git_commit *final;
git_blame__entry *ent;
int num_lines;
const char *final_buf;
size_t final_buf_size;
};
git_blame *git_blame__alloc(
git_repository *repo,
git_blame_options opts,
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/revwalk.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 "revwalk.h"
#include "commit.h"
#include "odb.h"
#include "pool.h"
#include "git2/revparse.h"
#include "merge.h"
#include "vector.h"
static int get_revision(git_commit_list_node **out, git_revwalk *walk, git_commit_list **list);
git_commit_list_node *git_revwalk__commit_lookup(
git_revwalk *walk, const git_oid *oid)
{
git_commit_list_node *commit;
/* lookup and reserve space if not already present */
if ((commit = git_oidmap_get(walk->commits, oid)) != NULL)
return commit;
commit = git_commit_list_alloc_node(walk);
if (commit == NULL)
return NULL;
git_oid_cpy(&commit->oid, oid);
if ((git_oidmap_set(walk->commits, &commit->oid, commit)) < 0)
return NULL;
return commit;
}
int git_revwalk__push_commit(git_revwalk *walk, const git_oid *oid, const git_revwalk__push_options *opts)
{
git_oid commit_id;
int error;
git_object *obj, *oobj;
git_commit_list_node *commit;
git_commit_list *list;
if ((error = git_object_lookup(&oobj, walk->repo, oid, GIT_OBJECT_ANY)) < 0)
return error;
error = git_object_peel(&obj, oobj, GIT_OBJECT_COMMIT);
git_object_free(oobj);
if (error == GIT_ENOTFOUND || error == GIT_EINVALIDSPEC || error == GIT_EPEEL) {
/* If this comes from e.g. push_glob("tags"), ignore this */
if (opts->from_glob)
return 0;
git_error_set(GIT_ERROR_INVALID, "object is not a committish");
return error;
}
if (error < 0)
return error;
git_oid_cpy(&commit_id, git_object_id(obj));
git_object_free(obj);
commit = git_revwalk__commit_lookup(walk, &commit_id);
if (commit == NULL)
return -1; /* error already reported by failed lookup */
/* A previous hide already told us we don't want this commit */
if (commit->uninteresting)
return 0;
if (opts->uninteresting) {
walk->limited = 1;
walk->did_hide = 1;
} else {
walk->did_push = 1;
}
commit->uninteresting = opts->uninteresting;
list = walk->user_input;
if ((opts->insert_by_date &&
git_commit_list_insert_by_date(commit, &list) == NULL) ||
git_commit_list_insert(commit, &list) == NULL) {
git_error_set_oom();
return -1;
}
walk->user_input = list;
return 0;
}
int git_revwalk_push(git_revwalk *walk, const git_oid *oid)
{
git_revwalk__push_options opts = GIT_REVWALK__PUSH_OPTIONS_INIT;
GIT_ASSERT_ARG(walk);
GIT_ASSERT_ARG(oid);
return git_revwalk__push_commit(walk, oid, &opts);
}
int git_revwalk_hide(git_revwalk *walk, const git_oid *oid)
{
git_revwalk__push_options opts = GIT_REVWALK__PUSH_OPTIONS_INIT;
GIT_ASSERT_ARG(walk);
GIT_ASSERT_ARG(oid);
opts.uninteresting = 1;
return git_revwalk__push_commit(walk, oid, &opts);
}
int git_revwalk__push_ref(git_revwalk *walk, const char *refname, const git_revwalk__push_options *opts)
{
git_oid oid;
if (git_reference_name_to_id(&oid, walk->repo, refname) < 0)
return -1;
return git_revwalk__push_commit(walk, &oid, opts);
}
int git_revwalk__push_glob(git_revwalk *walk, const char *glob, const git_revwalk__push_options *given_opts)
{
git_revwalk__push_options opts = GIT_REVWALK__PUSH_OPTIONS_INIT;
int error = 0;
git_buf buf = GIT_BUF_INIT;
git_reference *ref;
git_reference_iterator *iter;
size_t wildcard;
GIT_ASSERT_ARG(walk);
GIT_ASSERT_ARG(glob);
if (given_opts)
memcpy(&opts, given_opts, sizeof(opts));
/* refs/ is implied if not given in the glob */
if (git__prefixcmp(glob, GIT_REFS_DIR) != 0)
git_buf_joinpath(&buf, GIT_REFS_DIR, glob);
else
git_buf_puts(&buf, glob);
GIT_ERROR_CHECK_ALLOC_BUF(&buf);
/* If no '?', '*' or '[' exist, we append '/ *' to the glob */
wildcard = strcspn(glob, "?*[");
if (!glob[wildcard])
git_buf_put(&buf, "/*", 2);
if ((error = git_reference_iterator_glob_new(&iter, walk->repo, buf.ptr)) < 0)
goto out;
opts.from_glob = true;
while ((error = git_reference_next(&ref, iter)) == 0) {
error = git_revwalk__push_ref(walk, git_reference_name(ref), &opts);
git_reference_free(ref);
if (error < 0)
break;
}
git_reference_iterator_free(iter);
if (error == GIT_ITEROVER)
error = 0;
out:
git_buf_dispose(&buf);
return error;
}
int git_revwalk_push_glob(git_revwalk *walk, const char *glob)
{
git_revwalk__push_options opts = GIT_REVWALK__PUSH_OPTIONS_INIT;
GIT_ASSERT_ARG(walk);
GIT_ASSERT_ARG(glob);
return git_revwalk__push_glob(walk, glob, &opts);
}
int git_revwalk_hide_glob(git_revwalk *walk, const char *glob)
{
git_revwalk__push_options opts = GIT_REVWALK__PUSH_OPTIONS_INIT;
GIT_ASSERT_ARG(walk);
GIT_ASSERT_ARG(glob);
opts.uninteresting = 1;
return git_revwalk__push_glob(walk, glob, &opts);
}
int git_revwalk_push_head(git_revwalk *walk)
{
git_revwalk__push_options opts = GIT_REVWALK__PUSH_OPTIONS_INIT;
GIT_ASSERT_ARG(walk);
return git_revwalk__push_ref(walk, GIT_HEAD_FILE, &opts);
}
int git_revwalk_hide_head(git_revwalk *walk)
{
git_revwalk__push_options opts = GIT_REVWALK__PUSH_OPTIONS_INIT;
GIT_ASSERT_ARG(walk);
opts.uninteresting = 1;
return git_revwalk__push_ref(walk, GIT_HEAD_FILE, &opts);
}
int git_revwalk_push_ref(git_revwalk *walk, const char *refname)
{
git_revwalk__push_options opts = GIT_REVWALK__PUSH_OPTIONS_INIT;
GIT_ASSERT_ARG(walk);
GIT_ASSERT_ARG(refname);
return git_revwalk__push_ref(walk, refname, &opts);
}
int git_revwalk_push_range(git_revwalk *walk, const char *range)
{
git_revwalk__push_options opts = GIT_REVWALK__PUSH_OPTIONS_INIT;
git_revspec revspec;
int error = 0;
if ((error = git_revparse(&revspec, walk->repo, range)))
return error;
if (!revspec.to) {
git_error_set(GIT_ERROR_INVALID, "invalid revspec: range not provided");
error = GIT_EINVALIDSPEC;
goto out;
}
if (revspec.flags & GIT_REVSPEC_MERGE_BASE) {
/* TODO: support "<commit>...<commit>" */
git_error_set(GIT_ERROR_INVALID, "symmetric differences not implemented in revwalk");
error = GIT_EINVALIDSPEC;
goto out;
}
opts.uninteresting = 1;
if ((error = git_revwalk__push_commit(walk, git_object_id(revspec.from), &opts)))
goto out;
opts.uninteresting = 0;
error = git_revwalk__push_commit(walk, git_object_id(revspec.to), &opts);
out:
git_object_free(revspec.from);
git_object_free(revspec.to);
return error;
}
int git_revwalk_hide_ref(git_revwalk *walk, const char *refname)
{
git_revwalk__push_options opts = GIT_REVWALK__PUSH_OPTIONS_INIT;
GIT_ASSERT_ARG(walk);
GIT_ASSERT_ARG(refname);
opts.uninteresting = 1;
return git_revwalk__push_ref(walk, refname, &opts);
}
static int revwalk_enqueue_timesort(git_revwalk *walk, git_commit_list_node *commit)
{
return git_pqueue_insert(&walk->iterator_time, commit);
}
static int revwalk_enqueue_unsorted(git_revwalk *walk, git_commit_list_node *commit)
{
return git_commit_list_insert(commit, &walk->iterator_rand) ? 0 : -1;
}
static int revwalk_next_timesort(git_commit_list_node **object_out, git_revwalk *walk)
{
git_commit_list_node *next;
while ((next = git_pqueue_pop(&walk->iterator_time)) != NULL) {
/* Some commits might become uninteresting after being added to the list */
if (!next->uninteresting) {
*object_out = next;
return 0;
}
}
git_error_clear();
return GIT_ITEROVER;
}
static int revwalk_next_unsorted(git_commit_list_node **object_out, git_revwalk *walk)
{
int error;
git_commit_list_node *next;
while (!(error = get_revision(&next, walk, &walk->iterator_rand))) {
/* Some commits might become uninteresting after being added to the list */
if (!next->uninteresting) {
*object_out = next;
return 0;
}
}
return error;
}
static int revwalk_next_toposort(git_commit_list_node **object_out, git_revwalk *walk)
{
int error;
git_commit_list_node *next;
while (!(error = get_revision(&next, walk, &walk->iterator_topo))) {
/* Some commits might become uninteresting after being added to the list */
if (!next->uninteresting) {
*object_out = next;
return 0;
}
}
return error;
}
static int revwalk_next_reverse(git_commit_list_node **object_out, git_revwalk *walk)
{
*object_out = git_commit_list_pop(&walk->iterator_reverse);
return *object_out ? 0 : GIT_ITEROVER;
}
static void mark_parents_uninteresting(git_commit_list_node *commit)
{
unsigned short i;
git_commit_list *parents = NULL;
for (i = 0; i < commit->out_degree; i++)
git_commit_list_insert(commit->parents[i], &parents);
while (parents) {
commit = git_commit_list_pop(&parents);
while (commit) {
if (commit->uninteresting)
break;
commit->uninteresting = 1;
/*
* If we've reached this commit some other way
* already, we need to mark its parents uninteresting
* as well.
*/
if (!commit->parents)
break;
for (i = 0; i < commit->out_degree; i++)
git_commit_list_insert(commit->parents[i], &parents);
commit = commit->parents[0];
}
}
}
static int add_parents_to_list(git_revwalk *walk, git_commit_list_node *commit, git_commit_list **list)
{
unsigned short i;
int error;
if (commit->added)
return 0;
commit->added = 1;
/*
* Go full on in the uninteresting case as we want to include
* as many of these as we can.
*
* Usually we haven't parsed the parent of a parent, but if we
* have it we reached it via other means so we want to mark
* its parents recursively too.
*/
if (commit->uninteresting) {
for (i = 0; i < commit->out_degree; i++) {
git_commit_list_node *p = commit->parents[i];
p->uninteresting = 1;
/* git does it gently here, but we don't like missing objects */
if ((error = git_commit_list_parse(walk, p)) < 0)
return error;
if (p->parents)
mark_parents_uninteresting(p);
p->seen = 1;
git_commit_list_insert_by_date(p, list);
}
return 0;
}
/*
* Now on to what we do if the commit is indeed
* interesting. Here we do want things like first-parent take
* effect as this is what we'll be showing.
*/
for (i = 0; i < commit->out_degree; i++) {
git_commit_list_node *p = commit->parents[i];
if ((error = git_commit_list_parse(walk, p)) < 0)
return error;
if (walk->hide_cb && walk->hide_cb(&p->oid, walk->hide_cb_payload))
continue;
if (!p->seen) {
p->seen = 1;
git_commit_list_insert_by_date(p, list);
}
if (walk->first_parent)
break;
}
return 0;
}
/* How many unintersting commits we want to look at after we run out of interesting ones */
#define SLOP 5
static int still_interesting(git_commit_list *list, int64_t time, int slop)
{
/* The empty list is pretty boring */
if (!list)
return 0;
/*
* If the destination list has commits with an earlier date than our
* source, we want to reset the slop counter as we're not done.
*/
if (time <= list->item->time)
return SLOP;
for (; list; list = list->next) {
/*
* If the destination list still contains interesting commits we
* want to continue looking.
*/
if (!list->item->uninteresting || list->item->time > time)
return SLOP;
}
/* Everything's uninteresting, reduce the count */
return slop - 1;
}
static int limit_list(git_commit_list **out, git_revwalk *walk, git_commit_list *commits)
{
int error, slop = SLOP;
int64_t time = INT64_MAX;
git_commit_list *list = commits;
git_commit_list *newlist = NULL;
git_commit_list **p = &newlist;
while (list) {
git_commit_list_node *commit = git_commit_list_pop(&list);
if ((error = add_parents_to_list(walk, commit, &list)) < 0)
return error;
if (commit->uninteresting) {
mark_parents_uninteresting(commit);
slop = still_interesting(list, time, slop);
if (slop)
continue;
break;
}
if (walk->hide_cb && walk->hide_cb(&commit->oid, walk->hide_cb_payload))
continue;
time = commit->time;
p = &git_commit_list_insert(commit, p)->next;
}
git_commit_list_free(&list);
*out = newlist;
return 0;
}
static int get_revision(git_commit_list_node **out, git_revwalk *walk, git_commit_list **list)
{
int error;
git_commit_list_node *commit;
commit = git_commit_list_pop(list);
if (!commit) {
git_error_clear();
return GIT_ITEROVER;
}
/*
* If we did not run limit_list and we must add parents to the
* list ourselves.
*/
if (!walk->limited) {
if ((error = add_parents_to_list(walk, commit, list)) < 0)
return error;
}
*out = commit;
return 0;
}
static int sort_in_topological_order(git_commit_list **out, git_revwalk *walk, git_commit_list *list)
{
git_commit_list *ll = NULL, *newlist, **pptr;
git_commit_list_node *next;
git_pqueue queue;
git_vector_cmp queue_cmp = NULL;
unsigned short i;
int error;
if (walk->sorting & GIT_SORT_TIME)
queue_cmp = git_commit_list_time_cmp;
if ((error = git_pqueue_init(&queue, 0, 8, queue_cmp)))
return error;
/*
* Start by resetting the in-degree to 1 for the commits in
* our list. We want to go through this list again, so we
* store it in the commit list as we extract it from the lower
* machinery.
*/
for (ll = list; ll; ll = ll->next) {
ll->item->in_degree = 1;
}
/*
* Count up how many children each commit has. We limit
* ourselves to those commits in the original list (in-degree
* of 1) avoiding setting it for any parent that was hidden.
*/
for(ll = list; ll; ll = ll->next) {
for (i = 0; i < ll->item->out_degree; ++i) {
git_commit_list_node *parent = ll->item->parents[i];
if (parent->in_degree)
parent->in_degree++;
}
}
/*
* Now we find the tips i.e. those not reachable from any other node
* i.e. those which still have an in-degree of 1.
*/
for(ll = list; ll; ll = ll->next) {
if (ll->item->in_degree == 1) {
if ((error = git_pqueue_insert(&queue, ll->item)))
goto cleanup;
}
}
/*
* We need to output the tips in the order that they came out of the
* traversal, so if we're not doing time-sorting, we need to reverse the
* pqueue in order to get them to come out as we inserted them.
*/
if ((walk->sorting & GIT_SORT_TIME) == 0)
git_pqueue_reverse(&queue);
pptr = &newlist;
newlist = NULL;
while ((next = git_pqueue_pop(&queue)) != NULL) {
for (i = 0; i < next->out_degree; ++i) {
git_commit_list_node *parent = next->parents[i];
if (parent->in_degree == 0)
continue;
if (--parent->in_degree == 1) {
if ((error = git_pqueue_insert(&queue, parent)))
goto cleanup;
}
}
/* All the children of 'item' have been emitted (since we got to it via the priority queue) */
next->in_degree = 0;
pptr = &git_commit_list_insert(next, pptr)->next;
}
*out = newlist;
error = 0;
cleanup:
git_pqueue_free(&queue);
return error;
}
static int prepare_walk(git_revwalk *walk)
{
int error = 0;
git_commit_list *list, *commits = NULL;
git_commit_list_node *next;
/* If there were no pushes, we know that the walk is already over */
if (!walk->did_push) {
git_error_clear();
return GIT_ITEROVER;
}
for (list = walk->user_input; list; list = list->next) {
git_commit_list_node *commit = list->item;
if ((error = git_commit_list_parse(walk, commit)) < 0)
return error;
if (commit->uninteresting)
mark_parents_uninteresting(commit);
if (!commit->seen) {
commit->seen = 1;
git_commit_list_insert(commit, &commits);
}
}
if (walk->limited && (error = limit_list(&commits, walk, commits)) < 0)
return error;
if (walk->sorting & GIT_SORT_TOPOLOGICAL) {
error = sort_in_topological_order(&walk->iterator_topo, walk, commits);
git_commit_list_free(&commits);
if (error < 0)
return error;
walk->get_next = &revwalk_next_toposort;
} else if (walk->sorting & GIT_SORT_TIME) {
for (list = commits; list && !error; list = list->next)
error = walk->enqueue(walk, list->item);
git_commit_list_free(&commits);
if (error < 0)
return error;
} else {
walk->iterator_rand = commits;
walk->get_next = revwalk_next_unsorted;
}
if (walk->sorting & GIT_SORT_REVERSE) {
while ((error = walk->get_next(&next, walk)) == 0)
if (git_commit_list_insert(next, &walk->iterator_reverse) == NULL)
return -1;
if (error != GIT_ITEROVER)
return error;
walk->get_next = &revwalk_next_reverse;
}
walk->walking = 1;
return 0;
}
int git_revwalk_new(git_revwalk **revwalk_out, git_repository *repo)
{
git_revwalk *walk = git__calloc(1, sizeof(git_revwalk));
GIT_ERROR_CHECK_ALLOC(walk);
if (git_oidmap_new(&walk->commits) < 0 ||
git_pqueue_init(&walk->iterator_time, 0, 8, git_commit_list_time_cmp) < 0 ||
git_pool_init(&walk->commit_pool, COMMIT_ALLOC) < 0)
return -1;
walk->get_next = &revwalk_next_unsorted;
walk->enqueue = &revwalk_enqueue_unsorted;
walk->repo = repo;
if (git_repository_odb(&walk->odb, repo) < 0) {
git_revwalk_free(walk);
return -1;
}
*revwalk_out = walk;
return 0;
}
void git_revwalk_free(git_revwalk *walk)
{
if (walk == NULL)
return;
git_revwalk_reset(walk);
git_odb_free(walk->odb);
git_oidmap_free(walk->commits);
git_pool_clear(&walk->commit_pool);
git_pqueue_free(&walk->iterator_time);
git__free(walk);
}
git_repository *git_revwalk_repository(git_revwalk *walk)
{
GIT_ASSERT_ARG_WITH_RETVAL(walk, NULL);
return walk->repo;
}
int git_revwalk_sorting(git_revwalk *walk, unsigned int sort_mode)
{
GIT_ASSERT_ARG(walk);
if (walk->walking)
git_revwalk_reset(walk);
walk->sorting = sort_mode;
if (walk->sorting & GIT_SORT_TIME) {
walk->get_next = &revwalk_next_timesort;
walk->enqueue = &revwalk_enqueue_timesort;
} else {
walk->get_next = &revwalk_next_unsorted;
walk->enqueue = &revwalk_enqueue_unsorted;
}
if (walk->sorting != GIT_SORT_NONE)
walk->limited = 1;
return 0;
}
int git_revwalk_simplify_first_parent(git_revwalk *walk)
{
walk->first_parent = 1;
return 0;
}
int git_revwalk_next(git_oid *oid, git_revwalk *walk)
{
int error;
git_commit_list_node *next;
GIT_ASSERT_ARG(walk);
GIT_ASSERT_ARG(oid);
if (!walk->walking) {
if ((error = prepare_walk(walk)) < 0)
return error;
}
error = walk->get_next(&next, walk);
if (error == GIT_ITEROVER) {
git_revwalk_reset(walk);
git_error_clear();
return GIT_ITEROVER;
}
if (!error)
git_oid_cpy(oid, &next->oid);
return error;
}
int git_revwalk_reset(git_revwalk *walk)
{
git_commit_list_node *commit;
GIT_ASSERT_ARG(walk);
git_oidmap_foreach_value(walk->commits, commit, {
commit->seen = 0;
commit->in_degree = 0;
commit->topo_delay = 0;
commit->uninteresting = 0;
commit->added = 0;
commit->flags = 0;
});
git_pqueue_clear(&walk->iterator_time);
git_commit_list_free(&walk->iterator_topo);
git_commit_list_free(&walk->iterator_rand);
git_commit_list_free(&walk->iterator_reverse);
git_commit_list_free(&walk->user_input);
walk->first_parent = 0;
walk->walking = 0;
walk->limited = 0;
walk->did_push = walk->did_hide = 0;
walk->sorting = GIT_SORT_NONE;
return 0;
}
int git_revwalk_add_hide_cb(
git_revwalk *walk,
git_revwalk_hide_cb hide_cb,
void *payload)
{
GIT_ASSERT_ARG(walk);
if (walk->walking)
git_revwalk_reset(walk);
walk->hide_cb = hide_cb;
walk->hide_cb_payload = payload;
if (hide_cb)
walk->limited = 1;
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.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_hash_h__
#define INCLUDE_hash_h__
#include "common.h"
#include "git2/oid.h"
typedef struct {
void *data;
size_t len;
} git_buf_vec;
typedef enum {
GIT_HASH_ALGO_UNKNOWN = 0,
GIT_HASH_ALGO_SHA1,
} git_hash_algo_t;
#include "hash/sha1.h"
typedef struct git_hash_ctx {
union {
git_hash_sha1_ctx sha1;
} ctx;
git_hash_algo_t algo;
} git_hash_ctx;
int git_hash_global_init(void);
int git_hash_ctx_init(git_hash_ctx *ctx);
void git_hash_ctx_cleanup(git_hash_ctx *ctx);
int git_hash_init(git_hash_ctx *c);
int git_hash_update(git_hash_ctx *c, const void *data, size_t len);
int git_hash_final(git_oid *out, git_hash_ctx *c);
int git_hash_buf(git_oid *out, const void *data, size_t len);
int git_hash_vec(git_oid *out, git_buf_vec *vec, size_t n);
#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/varint.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_varint_h__
#define INCLUDE_varint_h__
#include "common.h"
#include <stdint.h>
extern int git_encode_varint(unsigned char *, size_t, uintmax_t);
extern uintmax_t git_decode_varint(const unsigned char *, 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/utf8.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 "utf8.h"
#include "common.h"
/*
* git_utf8_iterate is taken from the utf8proc project,
* http://www.public-software-group.org/utf8proc
*
* Copyright (c) 2009 Public Software Group e. V., Berlin, Germany
*
* 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.
*/
static const uint8_t utf8proc_utf8class[256] = {
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
4, 4, 4, 4, 4, 4, 4, 4, 0, 0, 0, 0, 0, 0, 0, 0
};
static int utf8_charlen(const uint8_t *str, size_t str_len)
{
uint8_t length;
size_t i;
length = utf8proc_utf8class[str[0]];
if (!length)
return -1;
if (str_len > 0 && length > str_len)
return -1;
for (i = 1; i < length; i++) {
if ((str[i] & 0xC0) != 0x80)
return -1;
}
return (int)length;
}
int git_utf8_iterate(uint32_t *out, const char *_str, size_t str_len)
{
const uint8_t *str = (const uint8_t *)_str;
uint32_t uc = 0;
int length;
*out = 0;
if ((length = utf8_charlen(str, str_len)) < 0)
return -1;
switch (length) {
case 1:
uc = str[0];
break;
case 2:
uc = ((str[0] & 0x1F) << 6) + (str[1] & 0x3F);
if (uc < 0x80) uc = -1;
break;
case 3:
uc = ((str[0] & 0x0F) << 12) + ((str[1] & 0x3F) << 6)
+ (str[2] & 0x3F);
if (uc < 0x800 || (uc >= 0xD800 && uc < 0xE000) ||
(uc >= 0xFDD0 && uc < 0xFDF0)) uc = -1;
break;
case 4:
uc = ((str[0] & 0x07) << 18) + ((str[1] & 0x3F) << 12)
+ ((str[2] & 0x3F) << 6) + (str[3] & 0x3F);
if (uc < 0x10000 || uc >= 0x110000) uc = -1;
break;
default:
return -1;
}
if ((uc & 0xFFFF) >= 0xFFFE)
return -1;
*out = uc;
return length;
}
size_t git_utf8_char_length(const char *_str, size_t str_len)
{
const uint8_t *str = (const uint8_t *)_str;
size_t offset = 0, count = 0;
while (offset < str_len) {
int length = utf8_charlen(str + offset, str_len - offset);
if (length < 0)
length = 1;
offset += length;
count++;
}
return count;
}
size_t git_utf8_valid_buf_length(const char *_str, size_t str_len)
{
const uint8_t *str = (const uint8_t *)_str;
size_t offset = 0;
while (offset < str_len) {
int length = utf8_charlen(str + offset, str_len - offset);
if (length < 0)
break;
offset += length;
}
return offset;
}
|
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.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_apply_h__
#define INCLUDE_apply_h__
#include "common.h"
#include "git2/patch.h"
#include "git2/apply.h"
#include "buffer.h"
extern int git_apply__patch(
git_buf *out,
char **filename,
unsigned int *mode,
const char *source,
size_t source_len,
git_patch *patch,
const git_apply_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/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 "commit.h"
#include "git2/common.h"
#include "git2/object.h"
#include "git2/repository.h"
#include "git2/signature.h"
#include "git2/mailmap.h"
#include "git2/sys/commit.h"
#include "odb.h"
#include "commit.h"
#include "signature.h"
#include "message.h"
#include "refs.h"
#include "object.h"
#include "array.h"
#include "oidarray.h"
void git_commit__free(void *_commit)
{
git_commit *commit = _commit;
git_array_clear(commit->parent_ids);
git_signature_free(commit->author);
git_signature_free(commit->committer);
git__free(commit->raw_header);
git__free(commit->raw_message);
git__free(commit->message_encoding);
git__free(commit->summary);
git__free(commit->body);
git__free(commit);
}
static int git_commit__create_buffer_internal(
git_buf *out,
const git_signature *author,
const git_signature *committer,
const char *message_encoding,
const char *message,
const git_oid *tree,
git_array_oid_t *parents)
{
size_t i = 0;
const git_oid *parent;
GIT_ASSERT_ARG(out);
GIT_ASSERT_ARG(tree);
git_oid__writebuf(out, "tree ", tree);
for (i = 0; i < git_array_size(*parents); i++) {
parent = git_array_get(*parents, i);
git_oid__writebuf(out, "parent ", parent);
}
git_signature__writebuf(out, "author ", author);
git_signature__writebuf(out, "committer ", committer);
if (message_encoding != NULL)
git_buf_printf(out, "encoding %s\n", message_encoding);
git_buf_putc(out, '\n');
if (git_buf_puts(out, message) < 0)
goto on_error;
return 0;
on_error:
git_buf_dispose(out);
return -1;
}
static int validate_tree_and_parents(git_array_oid_t *parents, git_repository *repo, const git_oid *tree,
git_commit_parent_callback parent_cb, void *parent_payload,
const git_oid *current_id, bool validate)
{
size_t i;
int error;
git_oid *parent_cpy;
const git_oid *parent;
if (validate && !git_object__is_valid(repo, tree, GIT_OBJECT_TREE))
return -1;
i = 0;
while ((parent = parent_cb(i, parent_payload)) != NULL) {
if (validate && !git_object__is_valid(repo, parent, GIT_OBJECT_COMMIT)) {
error = -1;
goto on_error;
}
parent_cpy = git_array_alloc(*parents);
GIT_ERROR_CHECK_ALLOC(parent_cpy);
git_oid_cpy(parent_cpy, parent);
i++;
}
if (current_id && (parents->size == 0 || git_oid_cmp(current_id, git_array_get(*parents, 0)))) {
git_error_set(GIT_ERROR_OBJECT, "failed to create commit: current tip is not the first parent");
error = GIT_EMODIFIED;
goto on_error;
}
return 0;
on_error:
git_array_clear(*parents);
return error;
}
static int git_commit__create_internal(
git_oid *id,
git_repository *repo,
const char *update_ref,
const git_signature *author,
const git_signature *committer,
const char *message_encoding,
const char *message,
const git_oid *tree,
git_commit_parent_callback parent_cb,
void *parent_payload,
bool validate)
{
int error;
git_odb *odb;
git_reference *ref = NULL;
git_buf buf = GIT_BUF_INIT;
const git_oid *current_id = NULL;
git_array_oid_t parents = GIT_ARRAY_INIT;
if (update_ref) {
error = git_reference_lookup_resolved(&ref, repo, update_ref, 10);
if (error < 0 && error != GIT_ENOTFOUND)
return error;
}
git_error_clear();
if (ref)
current_id = git_reference_target(ref);
if ((error = validate_tree_and_parents(&parents, repo, tree, parent_cb, parent_payload, current_id, validate)) < 0)
goto cleanup;
error = git_commit__create_buffer_internal(&buf, author, committer,
message_encoding, message, tree,
&parents);
if (error < 0)
goto cleanup;
if (git_repository_odb__weakptr(&odb, repo) < 0)
goto cleanup;
if (git_odb__freshen(odb, tree) < 0)
goto cleanup;
if (git_odb_write(id, odb, buf.ptr, buf.size, GIT_OBJECT_COMMIT) < 0)
goto cleanup;
if (update_ref != NULL) {
error = git_reference__update_for_commit(
repo, ref, update_ref, id, "commit");
goto cleanup;
}
cleanup:
git_array_clear(parents);
git_reference_free(ref);
git_buf_dispose(&buf);
return error;
}
int git_commit_create_from_callback(
git_oid *id,
git_repository *repo,
const char *update_ref,
const git_signature *author,
const git_signature *committer,
const char *message_encoding,
const char *message,
const git_oid *tree,
git_commit_parent_callback parent_cb,
void *parent_payload)
{
return git_commit__create_internal(
id, repo, update_ref, author, committer, message_encoding, message,
tree, parent_cb, parent_payload, true);
}
typedef struct {
size_t total;
va_list args;
} commit_parent_varargs;
static const git_oid *commit_parent_from_varargs(size_t curr, void *payload)
{
commit_parent_varargs *data = payload;
const git_commit *commit;
if (curr >= data->total)
return NULL;
commit = va_arg(data->args, const git_commit *);
return commit ? git_commit_id(commit) : NULL;
}
int git_commit_create_v(
git_oid *id,
git_repository *repo,
const char *update_ref,
const git_signature *author,
const git_signature *committer,
const char *message_encoding,
const char *message,
const git_tree *tree,
size_t parent_count,
...)
{
int error = 0;
commit_parent_varargs data;
GIT_ASSERT_ARG(tree);
GIT_ASSERT_ARG(git_tree_owner(tree) == repo);
data.total = parent_count;
va_start(data.args, parent_count);
error = git_commit__create_internal(
id, repo, update_ref, author, committer,
message_encoding, message, git_tree_id(tree),
commit_parent_from_varargs, &data, false);
va_end(data.args);
return error;
}
typedef struct {
size_t total;
const git_oid **parents;
} commit_parent_oids;
static const git_oid *commit_parent_from_ids(size_t curr, void *payload)
{
commit_parent_oids *data = payload;
return (curr < data->total) ? data->parents[curr] : NULL;
}
int git_commit_create_from_ids(
git_oid *id,
git_repository *repo,
const char *update_ref,
const git_signature *author,
const git_signature *committer,
const char *message_encoding,
const char *message,
const git_oid *tree,
size_t parent_count,
const git_oid *parents[])
{
commit_parent_oids data = { parent_count, parents };
return git_commit__create_internal(
id, repo, update_ref, author, committer,
message_encoding, message, tree,
commit_parent_from_ids, &data, true);
}
typedef struct {
size_t total;
const git_commit **parents;
git_repository *repo;
} commit_parent_data;
static const git_oid *commit_parent_from_array(size_t curr, void *payload)
{
commit_parent_data *data = payload;
const git_commit *commit;
if (curr >= data->total)
return NULL;
commit = data->parents[curr];
if (git_commit_owner(commit) != data->repo)
return NULL;
return git_commit_id(commit);
}
int git_commit_create(
git_oid *id,
git_repository *repo,
const char *update_ref,
const git_signature *author,
const git_signature *committer,
const char *message_encoding,
const char *message,
const git_tree *tree,
size_t parent_count,
const git_commit *parents[])
{
commit_parent_data data = { parent_count, parents, repo };
GIT_ASSERT_ARG(tree);
GIT_ASSERT_ARG(git_tree_owner(tree) == repo);
return git_commit__create_internal(
id, repo, update_ref, author, committer,
message_encoding, message, git_tree_id(tree),
commit_parent_from_array, &data, false);
}
static const git_oid *commit_parent_for_amend(size_t curr, void *payload)
{
const git_commit *commit_to_amend = payload;
if (curr >= git_array_size(commit_to_amend->parent_ids))
return NULL;
return git_array_get(commit_to_amend->parent_ids, curr);
}
int git_commit_amend(
git_oid *id,
const git_commit *commit_to_amend,
const char *update_ref,
const git_signature *author,
const git_signature *committer,
const char *message_encoding,
const char *message,
const git_tree *tree)
{
git_repository *repo;
git_oid tree_id;
git_reference *ref;
int error;
GIT_ASSERT_ARG(id);
GIT_ASSERT_ARG(commit_to_amend);
repo = git_commit_owner(commit_to_amend);
if (!author)
author = git_commit_author(commit_to_amend);
if (!committer)
committer = git_commit_committer(commit_to_amend);
if (!message_encoding)
message_encoding = git_commit_message_encoding(commit_to_amend);
if (!message)
message = git_commit_message(commit_to_amend);
if (!tree) {
git_tree *old_tree;
GIT_ERROR_CHECK_ERROR( git_commit_tree(&old_tree, commit_to_amend) );
git_oid_cpy(&tree_id, git_tree_id(old_tree));
git_tree_free(old_tree);
} else {
GIT_ASSERT_ARG(git_tree_owner(tree) == repo);
git_oid_cpy(&tree_id, git_tree_id(tree));
}
if (update_ref) {
if ((error = git_reference_lookup_resolved(&ref, repo, update_ref, 5)) < 0)
return error;
if (git_oid_cmp(git_commit_id(commit_to_amend), git_reference_target(ref))) {
git_reference_free(ref);
git_error_set(GIT_ERROR_REFERENCE, "commit to amend is not the tip of the given branch");
return -1;
}
}
error = git_commit__create_internal(
id, repo, NULL, author, committer, message_encoding, message,
&tree_id, commit_parent_for_amend, (void *)commit_to_amend, false);
if (!error && update_ref) {
error = git_reference__update_for_commit(
repo, ref, NULL, id, "commit");
git_reference_free(ref);
}
return error;
}
static int commit_parse(git_commit *commit, const char *data, size_t size, unsigned int flags)
{
const char *buffer_start = data, *buffer;
const char *buffer_end = buffer_start + size;
git_oid parent_id;
size_t header_len;
git_signature dummy_sig;
GIT_ASSERT_ARG(commit);
GIT_ASSERT_ARG(data);
buffer = buffer_start;
/* Allocate for one, which will allow not to realloc 90% of the time */
git_array_init_to_size(commit->parent_ids, 1);
GIT_ERROR_CHECK_ARRAY(commit->parent_ids);
/* The tree is always the first field */
if (!(flags & GIT_COMMIT_PARSE_QUICK)) {
if (git_oid__parse(&commit->tree_id, &buffer, buffer_end, "tree ") < 0)
goto bad_buffer;
} else {
size_t tree_len = strlen("tree ") + GIT_OID_HEXSZ + 1;
if (buffer + tree_len > buffer_end)
goto bad_buffer;
buffer += tree_len;
}
/*
* TODO: commit grafts!
*/
while (git_oid__parse(&parent_id, &buffer, buffer_end, "parent ") == 0) {
git_oid *new_id = git_array_alloc(commit->parent_ids);
GIT_ERROR_CHECK_ALLOC(new_id);
git_oid_cpy(new_id, &parent_id);
}
if (!(flags & GIT_COMMIT_PARSE_QUICK)) {
commit->author = git__malloc(sizeof(git_signature));
GIT_ERROR_CHECK_ALLOC(commit->author);
if (git_signature__parse(commit->author, &buffer, buffer_end, "author ", '\n') < 0)
return -1;
}
/* Some tools create multiple author fields, ignore the extra ones */
while (!git__prefixncmp(buffer, buffer_end - buffer, "author ")) {
if (git_signature__parse(&dummy_sig, &buffer, buffer_end, "author ", '\n') < 0)
return -1;
git__free(dummy_sig.name);
git__free(dummy_sig.email);
}
/* Always parse the committer; we need the commit time */
commit->committer = git__malloc(sizeof(git_signature));
GIT_ERROR_CHECK_ALLOC(commit->committer);
if (git_signature__parse(commit->committer, &buffer, buffer_end, "committer ", '\n') < 0)
return -1;
if (flags & GIT_COMMIT_PARSE_QUICK)
return 0;
/* Parse add'l header entries */
while (buffer < buffer_end) {
const char *eoln = buffer;
if (buffer[-1] == '\n' && buffer[0] == '\n')
break;
while (eoln < buffer_end && *eoln != '\n')
++eoln;
if (git__prefixncmp(buffer, buffer_end - buffer, "encoding ") == 0) {
buffer += strlen("encoding ");
commit->message_encoding = git__strndup(buffer, eoln - buffer);
GIT_ERROR_CHECK_ALLOC(commit->message_encoding);
}
if (eoln < buffer_end && *eoln == '\n')
++eoln;
buffer = eoln;
}
header_len = buffer - buffer_start;
commit->raw_header = git__strndup(buffer_start, header_len);
GIT_ERROR_CHECK_ALLOC(commit->raw_header);
/* point "buffer" to data after header, +1 for the final LF */
buffer = buffer_start + header_len + 1;
/* extract commit message */
if (buffer <= buffer_end)
commit->raw_message = git__strndup(buffer, buffer_end - buffer);
else
commit->raw_message = git__strdup("");
GIT_ERROR_CHECK_ALLOC(commit->raw_message);
return 0;
bad_buffer:
git_error_set(GIT_ERROR_OBJECT, "failed to parse bad commit object");
return -1;
}
int git_commit__parse_raw(void *commit, const char *data, size_t size)
{
return commit_parse(commit, data, size, 0);
}
int git_commit__parse_ext(git_commit *commit, git_odb_object *odb_obj, unsigned int flags)
{
return commit_parse(commit, git_odb_object_data(odb_obj), git_odb_object_size(odb_obj), flags);
}
int git_commit__parse(void *_commit, git_odb_object *odb_obj)
{
return git_commit__parse_ext(_commit, odb_obj, 0);
}
#define GIT_COMMIT_GETTER(_rvalue, _name, _return, _invalid) \
_rvalue git_commit_##_name(const git_commit *commit) \
{\
GIT_ASSERT_ARG_WITH_RETVAL(commit, _invalid); \
return _return; \
}
GIT_COMMIT_GETTER(const git_signature *, author, commit->author, NULL)
GIT_COMMIT_GETTER(const git_signature *, committer, commit->committer, NULL)
GIT_COMMIT_GETTER(const char *, message_raw, commit->raw_message, NULL)
GIT_COMMIT_GETTER(const char *, message_encoding, commit->message_encoding, NULL)
GIT_COMMIT_GETTER(const char *, raw_header, commit->raw_header, NULL)
GIT_COMMIT_GETTER(git_time_t, time, commit->committer->when.time, INT64_MIN)
GIT_COMMIT_GETTER(int, time_offset, commit->committer->when.offset, -1)
GIT_COMMIT_GETTER(unsigned int, parentcount, (unsigned int)git_array_size(commit->parent_ids), 0)
GIT_COMMIT_GETTER(const git_oid *, tree_id, &commit->tree_id, NULL)
const char *git_commit_message(const git_commit *commit)
{
const char *message;
GIT_ASSERT_ARG_WITH_RETVAL(commit, NULL);
message = commit->raw_message;
/* trim leading newlines from raw message */
while (*message && *message == '\n')
++message;
return message;
}
const char *git_commit_summary(git_commit *commit)
{
git_buf summary = GIT_BUF_INIT;
const char *msg, *space;
bool space_contains_newline = false;
GIT_ASSERT_ARG_WITH_RETVAL(commit, NULL);
if (!commit->summary) {
for (msg = git_commit_message(commit), space = NULL; *msg; ++msg) {
char next_character = msg[0];
/* stop processing at the end of the first paragraph */
if (next_character == '\n' && (!msg[1] || msg[1] == '\n'))
break;
/* record the beginning of contiguous whitespace runs */
else if (git__isspace(next_character)) {
if(space == NULL) {
space = msg;
space_contains_newline = false;
}
space_contains_newline |= next_character == '\n';
}
/* the next character is non-space */
else {
/* process any recorded whitespace */
if (space) {
if(space_contains_newline)
git_buf_putc(&summary, ' '); /* if the space contains a newline, collapse to ' ' */
else
git_buf_put(&summary, space, (msg - space)); /* otherwise copy it */
space = NULL;
}
/* copy the next character */
git_buf_putc(&summary, next_character);
}
}
commit->summary = git_buf_detach(&summary);
if (!commit->summary)
commit->summary = git__strdup("");
}
return commit->summary;
}
const char *git_commit_body(git_commit *commit)
{
const char *msg, *end;
GIT_ASSERT_ARG_WITH_RETVAL(commit, NULL);
if (!commit->body) {
/* search for end of summary */
for (msg = git_commit_message(commit); *msg; ++msg)
if (msg[0] == '\n' && (!msg[1] || msg[1] == '\n'))
break;
/* trim leading and trailing whitespace */
for (; *msg; ++msg)
if (!git__isspace(*msg))
break;
for (end = msg + strlen(msg) - 1; msg <= end; --end)
if (!git__isspace(*end))
break;
if (*msg)
commit->body = git__strndup(msg, end - msg + 1);
}
return commit->body;
}
int git_commit_tree(git_tree **tree_out, const git_commit *commit)
{
GIT_ASSERT_ARG(commit);
return git_tree_lookup(tree_out, commit->object.repo, &commit->tree_id);
}
const git_oid *git_commit_parent_id(
const git_commit *commit, unsigned int n)
{
GIT_ASSERT_ARG_WITH_RETVAL(commit, NULL);
return git_array_get(commit->parent_ids, n);
}
int git_commit_parent(
git_commit **parent, const git_commit *commit, unsigned int n)
{
const git_oid *parent_id;
GIT_ASSERT_ARG(commit);
parent_id = git_commit_parent_id(commit, n);
if (parent_id == NULL) {
git_error_set(GIT_ERROR_INVALID, "parent %u does not exist", n);
return GIT_ENOTFOUND;
}
return git_commit_lookup(parent, commit->object.repo, parent_id);
}
int git_commit_nth_gen_ancestor(
git_commit **ancestor,
const git_commit *commit,
unsigned int n)
{
git_commit *current, *parent = NULL;
int error;
GIT_ASSERT_ARG(ancestor);
GIT_ASSERT_ARG(commit);
if (git_commit_dup(¤t, (git_commit *)commit) < 0)
return -1;
if (n == 0) {
*ancestor = current;
return 0;
}
while (n--) {
error = git_commit_parent(&parent, current, 0);
git_commit_free(current);
if (error < 0)
return error;
current = parent;
}
*ancestor = parent;
return 0;
}
int git_commit_header_field(git_buf *out, const git_commit *commit, const char *field)
{
const char *eol, *buf = commit->raw_header;
git_buf_clear(out);
while ((eol = strchr(buf, '\n'))) {
/* We can skip continuations here */
if (buf[0] == ' ') {
buf = eol + 1;
continue;
}
/* Skip until we find the field we're after */
if (git__prefixcmp(buf, field)) {
buf = eol + 1;
continue;
}
buf += strlen(field);
/* Check that we're not matching a prefix but the field itself */
if (buf[0] != ' ') {
buf = eol + 1;
continue;
}
buf++; /* skip the SP */
git_buf_put(out, buf, eol - buf);
if (git_buf_oom(out))
goto oom;
/* If the next line starts with SP, it's multi-line, we must continue */
while (eol[1] == ' ') {
git_buf_putc(out, '\n');
buf = eol + 2;
eol = strchr(buf, '\n');
if (!eol)
goto malformed;
git_buf_put(out, buf, eol - buf);
}
if (git_buf_oom(out))
goto oom;
return 0;
}
git_error_set(GIT_ERROR_OBJECT, "no such field '%s'", field);
return GIT_ENOTFOUND;
malformed:
git_error_set(GIT_ERROR_OBJECT, "malformed header");
return -1;
oom:
git_error_set_oom();
return -1;
}
int git_commit_extract_signature(git_buf *signature, git_buf *signed_data, git_repository *repo, git_oid *commit_id, const char *field)
{
git_odb_object *obj;
git_odb *odb;
const char *buf;
const char *h, *eol;
int error;
git_buf_clear(signature);
git_buf_clear(signed_data);
if (!field)
field = "gpgsig";
if ((error = git_repository_odb__weakptr(&odb, repo)) < 0)
return error;
if ((error = git_odb_read(&obj, odb, commit_id)) < 0)
return error;
if (obj->cached.type != GIT_OBJECT_COMMIT) {
git_error_set(GIT_ERROR_INVALID, "the requested type does not match the type in the ODB");
error = GIT_ENOTFOUND;
goto cleanup;
}
buf = git_odb_object_data(obj);
while ((h = strchr(buf, '\n')) && h[1] != '\0') {
h++;
if (git__prefixcmp(buf, field)) {
if (git_buf_put(signed_data, buf, h - buf) < 0)
return -1;
buf = h;
continue;
}
h = buf;
h += strlen(field);
eol = strchr(h, '\n');
if (h[0] != ' ') {
buf = h;
continue;
}
if (!eol)
goto malformed;
h++; /* skip the SP */
git_buf_put(signature, h, eol - h);
if (git_buf_oom(signature))
goto oom;
/* If the next line starts with SP, it's multi-line, we must continue */
while (eol[1] == ' ') {
git_buf_putc(signature, '\n');
h = eol + 2;
eol = strchr(h, '\n');
if (!eol)
goto malformed;
git_buf_put(signature, h, eol - h);
}
if (git_buf_oom(signature))
goto oom;
error = git_buf_puts(signed_data, eol+1);
git_odb_object_free(obj);
return error;
}
git_error_set(GIT_ERROR_OBJECT, "this commit is not signed");
error = GIT_ENOTFOUND;
goto cleanup;
malformed:
git_error_set(GIT_ERROR_OBJECT, "malformed header");
error = -1;
goto cleanup;
oom:
git_error_set_oom();
error = -1;
goto cleanup;
cleanup:
git_odb_object_free(obj);
git_buf_clear(signature);
git_buf_clear(signed_data);
return error;
}
int git_commit_create_buffer(git_buf *out,
git_repository *repo,
const git_signature *author,
const git_signature *committer,
const char *message_encoding,
const char *message,
const git_tree *tree,
size_t parent_count,
const git_commit *parents[])
{
int error;
commit_parent_data data = { parent_count, parents, repo };
git_array_oid_t parents_arr = GIT_ARRAY_INIT;
const git_oid *tree_id;
GIT_ASSERT_ARG(tree);
GIT_ASSERT_ARG(git_tree_owner(tree) == repo);
tree_id = git_tree_id(tree);
if ((error = validate_tree_and_parents(&parents_arr, repo, tree_id, commit_parent_from_array, &data, NULL, true)) < 0)
return error;
error = git_commit__create_buffer_internal(
out, author, committer,
message_encoding, message, tree_id,
&parents_arr);
git_array_clear(parents_arr);
return error;
}
/**
* Append to 'out' properly marking continuations when there's a newline in 'content'
*/
static int format_header_field(git_buf *out, const char *field, const char *content)
{
const char *lf;
GIT_ASSERT_ARG(out);
GIT_ASSERT_ARG(field);
GIT_ASSERT_ARG(content);
git_buf_puts(out, field);
git_buf_putc(out, ' ');
while ((lf = strchr(content, '\n')) != NULL) {
git_buf_put(out, content, lf - content);
git_buf_puts(out, "\n ");
content = lf + 1;
}
git_buf_puts(out, content);
git_buf_putc(out, '\n');
return git_buf_oom(out) ? -1 : 0;
}
static const git_oid *commit_parent_from_commit(size_t n, void *payload)
{
const git_commit *commit = (const git_commit *) payload;
return git_array_get(commit->parent_ids, n);
}
int git_commit_create_with_signature(
git_oid *out,
git_repository *repo,
const char *commit_content,
const char *signature,
const char *signature_field)
{
git_odb *odb;
int error = 0;
const char *field;
const char *header_end;
git_buf commit = GIT_BUF_INIT;
git_commit *parsed;
git_array_oid_t parents = GIT_ARRAY_INIT;
/* The first step is to verify that all the tree and parents exist */
parsed = git__calloc(1, sizeof(git_commit));
GIT_ERROR_CHECK_ALLOC(parsed);
if ((error = commit_parse(parsed, commit_content, strlen(commit_content), 0)) < 0)
goto cleanup;
if ((error = validate_tree_and_parents(&parents, repo, &parsed->tree_id, commit_parent_from_commit, parsed, NULL, true)) < 0)
goto cleanup;
git_array_clear(parents);
/* Then we start appending by identifying the end of the commit header */
header_end = strstr(commit_content, "\n\n");
if (!header_end) {
git_error_set(GIT_ERROR_INVALID, "malformed commit contents");
error = -1;
goto cleanup;
}
/* The header ends after the first LF */
header_end++;
git_buf_put(&commit, commit_content, header_end - commit_content);
if (signature != NULL) {
field = signature_field ? signature_field : "gpgsig";
if ((error = format_header_field(&commit, field, signature)) < 0)
goto cleanup;
}
git_buf_puts(&commit, header_end);
if (git_buf_oom(&commit))
return -1;
if ((error = git_repository_odb__weakptr(&odb, repo)) < 0)
goto cleanup;
if ((error = git_odb_write(out, odb, commit.ptr, commit.size, GIT_OBJECT_COMMIT)) < 0)
goto cleanup;
cleanup:
git_commit__free(parsed);
git_buf_dispose(&commit);
return error;
}
int git_commit_committer_with_mailmap(
git_signature **out, const git_commit *commit, const git_mailmap *mailmap)
{
return git_mailmap_resolve_signature(out, mailmap, commit->committer);
}
int git_commit_author_with_mailmap(
git_signature **out, const git_commit *commit, const git_mailmap *mailmap)
{
return git_mailmap_resolve_signature(out, mailmap, commit->author);
}
|
0 |
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2
|
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2/src/errors.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 "threadstate.h"
#include "posix.h"
#include "buffer.h"
#include "libgit2.h"
/********************************************
* New error handling
********************************************/
static git_error g_git_oom_error = {
"Out of memory",
GIT_ERROR_NOMEMORY
};
static git_error g_git_uninitialized_error = {
"libgit2 has not been initialized; you must call git_libgit2_init",
GIT_ERROR_INVALID
};
static void set_error_from_buffer(int error_class)
{
git_error *error = &GIT_THREADSTATE->error_t;
git_buf *buf = &GIT_THREADSTATE->error_buf;
error->message = buf->ptr;
error->klass = error_class;
GIT_THREADSTATE->last_error = error;
}
static void set_error(int error_class, char *string)
{
git_buf *buf = &GIT_THREADSTATE->error_buf;
git_buf_clear(buf);
if (string) {
git_buf_puts(buf, string);
git__free(string);
}
set_error_from_buffer(error_class);
}
void git_error_set_oom(void)
{
GIT_THREADSTATE->last_error = &g_git_oom_error;
}
void git_error_set(int error_class, const char *fmt, ...)
{
va_list ap;
va_start(ap, fmt);
git_error_vset(error_class, fmt, ap);
va_end(ap);
}
void git_error_vset(int error_class, const char *fmt, va_list ap)
{
#ifdef GIT_WIN32
DWORD win32_error_code = (error_class == GIT_ERROR_OS) ? GetLastError() : 0;
#endif
int error_code = (error_class == GIT_ERROR_OS) ? errno : 0;
git_buf *buf = &GIT_THREADSTATE->error_buf;
git_buf_clear(buf);
if (fmt) {
git_buf_vprintf(buf, fmt, ap);
if (error_class == GIT_ERROR_OS)
git_buf_PUTS(buf, ": ");
}
if (error_class == GIT_ERROR_OS) {
#ifdef GIT_WIN32
char * win32_error = git_win32_get_error_message(win32_error_code);
if (win32_error) {
git_buf_puts(buf, win32_error);
git__free(win32_error);
SetLastError(0);
}
else
#endif
if (error_code)
git_buf_puts(buf, strerror(error_code));
if (error_code)
errno = 0;
}
if (!git_buf_oom(buf))
set_error_from_buffer(error_class);
}
int git_error_set_str(int error_class, const char *string)
{
git_buf *buf = &GIT_THREADSTATE->error_buf;
GIT_ASSERT_ARG(string);
git_buf_clear(buf);
git_buf_puts(buf, string);
if (git_buf_oom(buf))
return -1;
set_error_from_buffer(error_class);
return 0;
}
void git_error_clear(void)
{
if (GIT_THREADSTATE->last_error != NULL) {
set_error(0, NULL);
GIT_THREADSTATE->last_error = NULL;
}
errno = 0;
#ifdef GIT_WIN32
SetLastError(0);
#endif
}
const git_error *git_error_last(void)
{
/* If the library is not initialized, return a static error. */
if (!git_libgit2_init_count())
return &g_git_uninitialized_error;
return GIT_THREADSTATE->last_error;
}
int git_error_state_capture(git_error_state *state, int error_code)
{
git_error *error = GIT_THREADSTATE->last_error;
git_buf *error_buf = &GIT_THREADSTATE->error_buf;
memset(state, 0, sizeof(git_error_state));
if (!error_code)
return 0;
state->error_code = error_code;
state->oom = (error == &g_git_oom_error);
if (error) {
state->error_msg.klass = error->klass;
if (state->oom)
state->error_msg.message = g_git_oom_error.message;
else
state->error_msg.message = git_buf_detach(error_buf);
}
git_error_clear();
return error_code;
}
int git_error_state_restore(git_error_state *state)
{
int ret = 0;
git_error_clear();
if (state && state->error_msg.message) {
if (state->oom)
git_error_set_oom();
else
set_error(state->error_msg.klass, state->error_msg.message);
ret = state->error_code;
memset(state, 0, sizeof(git_error_state));
}
return ret;
}
void git_error_state_free(git_error_state *state)
{
if (!state)
return;
if (!state->oom)
git__free(state->error_msg.message);
memset(state, 0, sizeof(git_error_state));
}
int git_error_system_last(void)
{
#ifdef GIT_WIN32
return GetLastError();
#else
return errno;
#endif
}
void git_error_system_set(int code)
{
#ifdef GIT_WIN32
SetLastError(code);
#else
errno = code;
#endif
}
/* Deprecated error values and functions */
#ifndef GIT_DEPRECATE_HARD
const git_error *giterr_last(void)
{
return git_error_last();
}
void giterr_clear(void)
{
git_error_clear();
}
void giterr_set_str(int error_class, const char *string)
{
git_error_set_str(error_class, string);
}
void giterr_set_oom(void)
{
git_error_set_oom();
}
#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-objects.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_objects_h__
#define INCLUDE_pack_objects_h__
#include "common.h"
#include "buffer.h"
#include "hash.h"
#include "oidmap.h"
#include "netops.h"
#include "zstream.h"
#include "pool.h"
#include "indexer.h"
#include "git2/oid.h"
#include "git2/pack.h"
#define GIT_PACK_WINDOW 10 /* number of objects to possibly delta against */
#define GIT_PACK_DEPTH 50 /* max delta depth */
#define GIT_PACK_DELTA_CACHE_SIZE (256 * 1024 * 1024)
#define GIT_PACK_DELTA_CACHE_LIMIT 1000
#define GIT_PACK_BIG_FILE_THRESHOLD (512 * 1024 * 1024)
typedef struct git_pobject {
git_oid id;
git_object_t type;
off64_t offset;
size_t size;
unsigned int hash; /* name hint hash */
struct git_pobject *delta; /* delta base object */
struct git_pobject *delta_child; /* deltified objects who bases me */
struct git_pobject *delta_sibling; /* other deltified objects
* who uses the same base as
* me */
void *delta_data;
size_t delta_size;
size_t z_delta_size;
int written:1,
recursing:1,
tagged:1,
filled:1;
} git_pobject;
struct git_packbuilder {
git_repository *repo; /* associated repository */
git_odb *odb; /* associated object database */
git_hash_ctx ctx;
git_zstream zstream;
uint32_t nr_objects,
nr_deltified,
nr_written,
nr_remaining;
size_t nr_alloc;
git_pobject *object_list;
git_oidmap *object_ix;
git_oidmap *walk_objects;
git_pool object_pool;
git_oid pack_oid; /* hash of written pack */
/* synchronization objects */
git_mutex cache_mutex;
git_mutex progress_mutex;
git_cond progress_cond;
/* configs */
size_t delta_cache_size;
size_t max_delta_cache_size;
size_t cache_max_small_delta_size;
size_t big_file_threshold;
size_t window_memory_limit;
unsigned int nr_threads; /* nr of threads to use */
git_packbuilder_progress progress_cb;
void *progress_cb_payload;
double last_progress_report_time; /* the time progress was last reported */
bool done;
};
int git_packbuilder_write_buf(git_buf *buf, git_packbuilder *pb);
#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/pqueue.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 "pqueue.h"
#include "util.h"
#define PQUEUE_LCHILD_OF(I) (((I)<<1)+1)
#define PQUEUE_RCHILD_OF(I) (((I)<<1)+2)
#define PQUEUE_PARENT_OF(I) (((I)-1)>>1)
int git_pqueue_init(
git_pqueue *pq,
uint32_t flags,
size_t init_size,
git_vector_cmp cmp)
{
int error = git_vector_init(pq, init_size, cmp);
if (!error) {
/* mix in our flags */
pq->flags |= flags;
/* if fixed size heap, pretend vector is exactly init_size elements */
if ((flags & GIT_PQUEUE_FIXED_SIZE) && init_size > 0)
pq->_alloc_size = init_size;
}
return error;
}
static void pqueue_up(git_pqueue *pq, size_t el)
{
size_t parent_el = PQUEUE_PARENT_OF(el);
void *kid = git_vector_get(pq, el);
while (el > 0) {
void *parent = pq->contents[parent_el];
if (pq->_cmp(parent, kid) <= 0)
break;
pq->contents[el] = parent;
el = parent_el;
parent_el = PQUEUE_PARENT_OF(el);
}
pq->contents[el] = kid;
}
static void pqueue_down(git_pqueue *pq, size_t el)
{
void *parent = git_vector_get(pq, el), *kid, *rkid;
while (1) {
size_t kid_el = PQUEUE_LCHILD_OF(el);
if ((kid = git_vector_get(pq, kid_el)) == NULL)
break;
if ((rkid = git_vector_get(pq, kid_el + 1)) != NULL &&
pq->_cmp(kid, rkid) > 0) {
kid = rkid;
kid_el += 1;
}
if (pq->_cmp(parent, kid) <= 0)
break;
pq->contents[el] = kid;
el = kid_el;
}
pq->contents[el] = parent;
}
int git_pqueue_insert(git_pqueue *pq, void *item)
{
int error = 0;
/* if heap is full, pop the top element if new one should replace it */
if ((pq->flags & GIT_PQUEUE_FIXED_SIZE) != 0 &&
pq->length >= pq->_alloc_size)
{
/* skip this item if below min item in heap or if
* we do not have a comparison function */
if (!pq->_cmp || pq->_cmp(item, git_vector_get(pq, 0)) <= 0)
return 0;
/* otherwise remove the min item before inserting new */
(void)git_pqueue_pop(pq);
}
if (!(error = git_vector_insert(pq, item)) && pq->_cmp)
pqueue_up(pq, pq->length - 1);
return error;
}
void *git_pqueue_pop(git_pqueue *pq)
{
void *rval;
if (!pq->_cmp) {
rval = git_vector_last(pq);
} else {
rval = git_pqueue_get(pq, 0);
}
if (git_pqueue_size(pq) > 1 && pq->_cmp) {
/* move last item to top of heap, shrink, and push item down */
pq->contents[0] = git_vector_last(pq);
git_vector_pop(pq);
pqueue_down(pq, 0);
} else {
/* all we need to do is shrink the heap in this case */
git_vector_pop(pq);
}
return rval;
}
|
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.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 "futils.h"
#include "runtime.h"
#include "strmap.h"
#include "hash.h"
#include <ctype.h>
#if GIT_WIN32
#include "win32/findfile.h"
#endif
int git_futils_mkpath2file(const char *file_path, const mode_t mode)
{
return git_futils_mkdir(
file_path, mode,
GIT_MKDIR_PATH | GIT_MKDIR_SKIP_LAST | GIT_MKDIR_VERIFY_DIR);
}
int git_futils_mktmp(git_buf *path_out, const char *filename, mode_t mode)
{
int fd;
mode_t mask;
p_umask(mask = p_umask(0));
git_buf_sets(path_out, filename);
git_buf_puts(path_out, "_git2_XXXXXX");
if (git_buf_oom(path_out))
return -1;
if ((fd = p_mkstemp(path_out->ptr)) < 0) {
git_error_set(GIT_ERROR_OS,
"failed to create temporary file '%s'", path_out->ptr);
return -1;
}
if (p_chmod(path_out->ptr, (mode & ~mask))) {
git_error_set(GIT_ERROR_OS,
"failed to set permissions on file '%s'", path_out->ptr);
return -1;
}
return fd;
}
int git_futils_creat_withpath(const char *path, const mode_t dirmode, const mode_t mode)
{
int fd;
if (git_futils_mkpath2file(path, dirmode) < 0)
return -1;
fd = p_creat(path, mode);
if (fd < 0) {
git_error_set(GIT_ERROR_OS, "failed to create file '%s'", path);
return -1;
}
return fd;
}
int git_futils_creat_locked(const char *path, const mode_t mode)
{
int fd = p_open(path, O_WRONLY | O_CREAT | O_EXCL | O_BINARY | O_CLOEXEC,
mode);
if (fd < 0) {
int error = errno;
git_error_set(GIT_ERROR_OS, "failed to create locked file '%s'", path);
switch (error) {
case EEXIST:
return GIT_ELOCKED;
case ENOENT:
return GIT_ENOTFOUND;
default:
return -1;
}
}
return fd;
}
int git_futils_creat_locked_withpath(const char *path, const mode_t dirmode, const mode_t mode)
{
if (git_futils_mkpath2file(path, dirmode) < 0)
return -1;
return git_futils_creat_locked(path, mode);
}
int git_futils_open_ro(const char *path)
{
int fd = p_open(path, O_RDONLY);
if (fd < 0)
return git_path_set_error(errno, path, "open");
return fd;
}
int git_futils_truncate(const char *path, int mode)
{
int fd = p_open(path, O_WRONLY | O_CREAT | O_TRUNC | O_CLOEXEC, mode);
if (fd < 0)
return git_path_set_error(errno, path, "open");
close(fd);
return 0;
}
int git_futils_filesize(uint64_t *out, git_file fd)
{
struct stat sb;
if (p_fstat(fd, &sb)) {
git_error_set(GIT_ERROR_OS, "failed to stat file descriptor");
return -1;
}
if (sb.st_size < 0) {
git_error_set(GIT_ERROR_INVALID, "invalid file size");
return -1;
}
*out = sb.st_size;
return 0;
}
mode_t git_futils_canonical_mode(mode_t raw_mode)
{
if (S_ISREG(raw_mode))
return S_IFREG | GIT_PERMS_CANONICAL(raw_mode);
else if (S_ISLNK(raw_mode))
return S_IFLNK;
else if (S_ISGITLINK(raw_mode))
return S_IFGITLINK;
else if (S_ISDIR(raw_mode))
return S_IFDIR;
else
return 0;
}
int git_futils_readbuffer_fd(git_buf *buf, git_file fd, size_t len)
{
ssize_t read_size = 0;
size_t alloc_len;
git_buf_clear(buf);
if (!git__is_ssizet(len)) {
git_error_set(GIT_ERROR_INVALID, "read too large");
return -1;
}
GIT_ERROR_CHECK_ALLOC_ADD(&alloc_len, len, 1);
if (git_buf_grow(buf, alloc_len) < 0)
return -1;
/* p_read loops internally to read len bytes */
read_size = p_read(fd, buf->ptr, len);
if (read_size != (ssize_t)len) {
git_error_set(GIT_ERROR_OS, "failed to read descriptor");
git_buf_dispose(buf);
return -1;
}
buf->ptr[read_size] = '\0';
buf->size = read_size;
return 0;
}
int git_futils_readbuffer_updated(
git_buf *out, const char *path, git_oid *checksum, int *updated)
{
int error;
git_file fd;
struct stat st;
git_buf buf = GIT_BUF_INIT;
git_oid checksum_new;
GIT_ASSERT_ARG(out);
GIT_ASSERT_ARG(path && *path);
if (updated != NULL)
*updated = 0;
if (p_stat(path, &st) < 0)
return git_path_set_error(errno, path, "stat");
if (S_ISDIR(st.st_mode)) {
git_error_set(GIT_ERROR_INVALID, "requested file is a directory");
return GIT_ENOTFOUND;
}
if (!git__is_sizet(st.st_size+1)) {
git_error_set(GIT_ERROR_OS, "invalid regular file stat for '%s'", path);
return -1;
}
if ((fd = git_futils_open_ro(path)) < 0)
return fd;
if (git_futils_readbuffer_fd(&buf, fd, (size_t)st.st_size) < 0) {
p_close(fd);
return -1;
}
p_close(fd);
if (checksum) {
if ((error = git_hash_buf(&checksum_new, buf.ptr, buf.size)) < 0) {
git_buf_dispose(&buf);
return error;
}
/*
* If we were given a checksum, we only want to use it if it's different
*/
if (!git_oid__cmp(checksum, &checksum_new)) {
git_buf_dispose(&buf);
if (updated)
*updated = 0;
return 0;
}
git_oid_cpy(checksum, &checksum_new);
}
/*
* If we're here, the file did change, or the user didn't have an old version
*/
if (updated != NULL)
*updated = 1;
git_buf_swap(out, &buf);
git_buf_dispose(&buf);
return 0;
}
int git_futils_readbuffer(git_buf *buf, const char *path)
{
return git_futils_readbuffer_updated(buf, path, NULL, NULL);
}
int git_futils_writebuffer(
const git_buf *buf, const char *path, int flags, mode_t mode)
{
int fd, do_fsync = 0, error = 0;
if (!flags)
flags = O_CREAT | O_TRUNC | O_WRONLY;
if ((flags & O_FSYNC) != 0)
do_fsync = 1;
flags &= ~O_FSYNC;
if (!mode)
mode = GIT_FILEMODE_BLOB;
if ((fd = p_open(path, flags, mode)) < 0) {
git_error_set(GIT_ERROR_OS, "could not open '%s' for writing", path);
return fd;
}
if ((error = p_write(fd, git_buf_cstr(buf), git_buf_len(buf))) < 0) {
git_error_set(GIT_ERROR_OS, "could not write to '%s'", path);
(void)p_close(fd);
return error;
}
if (do_fsync && (error = p_fsync(fd)) < 0) {
git_error_set(GIT_ERROR_OS, "could not fsync '%s'", path);
p_close(fd);
return error;
}
if ((error = p_close(fd)) < 0) {
git_error_set(GIT_ERROR_OS, "error while closing '%s'", path);
return error;
}
if (do_fsync && (flags & O_CREAT))
error = git_futils_fsync_parent(path);
return error;
}
int git_futils_mv_withpath(const char *from, const char *to, const mode_t dirmode)
{
if (git_futils_mkpath2file(to, dirmode) < 0)
return -1;
if (p_rename(from, to) < 0) {
git_error_set(GIT_ERROR_OS, "failed to rename '%s' to '%s'", from, to);
return -1;
}
return 0;
}
int git_futils_mmap_ro(git_map *out, git_file fd, off64_t begin, size_t len)
{
return p_mmap(out, len, GIT_PROT_READ, GIT_MAP_SHARED, fd, begin);
}
int git_futils_mmap_ro_file(git_map *out, const char *path)
{
git_file fd = git_futils_open_ro(path);
uint64_t len;
int result;
if (fd < 0)
return fd;
if ((result = git_futils_filesize(&len, fd)) < 0)
goto out;
if (!git__is_sizet(len)) {
git_error_set(GIT_ERROR_OS, "file `%s` too large to mmap", path);
result = -1;
goto out;
}
result = git_futils_mmap_ro(out, fd, 0, (size_t)len);
out:
p_close(fd);
return result;
}
void git_futils_mmap_free(git_map *out)
{
p_munmap(out);
}
GIT_INLINE(int) mkdir_validate_dir(
const char *path,
struct stat *st,
mode_t mode,
uint32_t flags,
struct git_futils_mkdir_options *opts)
{
/* with exclusive create, existing dir is an error */
if ((flags & GIT_MKDIR_EXCL) != 0) {
git_error_set(GIT_ERROR_FILESYSTEM,
"failed to make directory '%s': directory exists", path);
return GIT_EEXISTS;
}
if ((S_ISREG(st->st_mode) && (flags & GIT_MKDIR_REMOVE_FILES)) ||
(S_ISLNK(st->st_mode) && (flags & GIT_MKDIR_REMOVE_SYMLINKS))) {
if (p_unlink(path) < 0) {
git_error_set(GIT_ERROR_OS, "failed to remove %s '%s'",
S_ISLNK(st->st_mode) ? "symlink" : "file", path);
return GIT_EEXISTS;
}
opts->perfdata.mkdir_calls++;
if (p_mkdir(path, mode) < 0) {
git_error_set(GIT_ERROR_OS, "failed to make directory '%s'", path);
return GIT_EEXISTS;
}
}
else if (S_ISLNK(st->st_mode)) {
/* Re-stat the target, make sure it's a directory */
opts->perfdata.stat_calls++;
if (p_stat(path, st) < 0) {
git_error_set(GIT_ERROR_OS, "failed to make directory '%s'", path);
return GIT_EEXISTS;
}
}
else if (!S_ISDIR(st->st_mode)) {
git_error_set(GIT_ERROR_FILESYSTEM,
"failed to make directory '%s': directory exists", path);
return GIT_EEXISTS;
}
return 0;
}
GIT_INLINE(int) mkdir_validate_mode(
const char *path,
struct stat *st,
bool terminal_path,
mode_t mode,
uint32_t flags,
struct git_futils_mkdir_options *opts)
{
if (((terminal_path && (flags & GIT_MKDIR_CHMOD) != 0) ||
(flags & GIT_MKDIR_CHMOD_PATH) != 0) && st->st_mode != mode) {
opts->perfdata.chmod_calls++;
if (p_chmod(path, mode) < 0) {
git_error_set(GIT_ERROR_OS, "failed to set permissions on '%s'", path);
return -1;
}
}
return 0;
}
GIT_INLINE(int) mkdir_canonicalize(
git_buf *path,
uint32_t flags)
{
ssize_t root_len;
if (path->size == 0) {
git_error_set(GIT_ERROR_OS, "attempt to create empty path");
return -1;
}
/* Trim trailing slashes (except the root) */
if ((root_len = git_path_root(path->ptr)) < 0)
root_len = 0;
else
root_len++;
while (path->size > (size_t)root_len && path->ptr[path->size - 1] == '/')
path->ptr[--path->size] = '\0';
/* if we are not supposed to made the last element, truncate it */
if ((flags & GIT_MKDIR_SKIP_LAST2) != 0) {
git_path_dirname_r(path, path->ptr);
flags |= GIT_MKDIR_SKIP_LAST;
}
if ((flags & GIT_MKDIR_SKIP_LAST) != 0) {
git_path_dirname_r(path, path->ptr);
}
/* We were either given the root path (or trimmed it to
* the root), we don't have anything to do.
*/
if (path->size <= (size_t)root_len)
git_buf_clear(path);
return 0;
}
int git_futils_mkdir(
const char *path,
mode_t mode,
uint32_t flags)
{
git_buf make_path = GIT_BUF_INIT, parent_path = GIT_BUF_INIT;
const char *relative;
struct git_futils_mkdir_options opts = { 0 };
struct stat st;
size_t depth = 0;
int len = 0, root_len, error;
if ((error = git_buf_puts(&make_path, path)) < 0 ||
(error = mkdir_canonicalize(&make_path, flags)) < 0 ||
(error = git_buf_puts(&parent_path, make_path.ptr)) < 0 ||
make_path.size == 0)
goto done;
root_len = git_path_root(make_path.ptr);
/* find the first parent directory that exists. this will be used
* as the base to dirname_relative.
*/
for (relative = make_path.ptr; parent_path.size; ) {
error = p_lstat(parent_path.ptr, &st);
if (error == 0) {
break;
} else if (errno != ENOENT) {
git_error_set(GIT_ERROR_OS, "failed to stat '%s'", parent_path.ptr);
error = -1;
goto done;
}
depth++;
/* examine the parent of the current path */
if ((len = git_path_dirname_r(&parent_path, parent_path.ptr)) < 0) {
error = len;
goto done;
}
GIT_ASSERT(len);
/*
* We've walked all the given path's parents and it's either relative
* (the parent is simply '.') or rooted (the length is less than or
* equal to length of the root path). The path may be less than the
* root path length on Windows, where `C:` == `C:/`.
*/
if ((len == 1 && parent_path.ptr[0] == '.') ||
(len == 1 && parent_path.ptr[0] == '/') ||
len <= root_len) {
relative = make_path.ptr;
break;
}
relative = make_path.ptr + len + 1;
/* not recursive? just make this directory relative to its parent. */
if ((flags & GIT_MKDIR_PATH) == 0)
break;
}
/* we found an item at the location we're trying to create,
* validate it.
*/
if (depth == 0) {
error = mkdir_validate_dir(make_path.ptr, &st, mode, flags, &opts);
if (!error)
error = mkdir_validate_mode(
make_path.ptr, &st, true, mode, flags, &opts);
goto done;
}
/* we already took `SKIP_LAST` and `SKIP_LAST2` into account when
* canonicalizing `make_path`.
*/
flags &= ~(GIT_MKDIR_SKIP_LAST2 | GIT_MKDIR_SKIP_LAST);
error = git_futils_mkdir_relative(relative,
parent_path.size ? parent_path.ptr : NULL, mode, flags, &opts);
done:
git_buf_dispose(&make_path);
git_buf_dispose(&parent_path);
return error;
}
int git_futils_mkdir_r(const char *path, const mode_t mode)
{
return git_futils_mkdir(path, mode, GIT_MKDIR_PATH);
}
int git_futils_mkdir_relative(
const char *relative_path,
const char *base,
mode_t mode,
uint32_t flags,
struct git_futils_mkdir_options *opts)
{
git_buf make_path = GIT_BUF_INIT;
ssize_t root = 0, min_root_len;
char lastch = '/', *tail;
struct stat st;
struct git_futils_mkdir_options empty_opts = {0};
int error;
if (!opts)
opts = &empty_opts;
/* build path and find "root" where we should start calling mkdir */
if (git_path_join_unrooted(&make_path, relative_path, base, &root) < 0)
return -1;
if ((error = mkdir_canonicalize(&make_path, flags)) < 0 ||
make_path.size == 0)
goto done;
/* if we are not supposed to make the whole path, reset root */
if ((flags & GIT_MKDIR_PATH) == 0)
root = git_buf_rfind(&make_path, '/');
/* advance root past drive name or network mount prefix */
min_root_len = git_path_root(make_path.ptr);
if (root < min_root_len)
root = min_root_len;
while (root >= 0 && make_path.ptr[root] == '/')
++root;
/* clip root to make_path length */
if (root > (ssize_t)make_path.size)
root = (ssize_t)make_path.size; /* i.e. NUL byte of string */
if (root < 0)
root = 0;
/* walk down tail of path making each directory */
for (tail = &make_path.ptr[root]; *tail; *tail = lastch) {
bool mkdir_attempted = false;
/* advance tail to include next path component */
while (*tail == '/')
tail++;
while (*tail && *tail != '/')
tail++;
/* truncate path at next component */
lastch = *tail;
*tail = '\0';
st.st_mode = 0;
if (opts->dir_map && git_strmap_exists(opts->dir_map, make_path.ptr))
continue;
/* See what's going on with this path component */
opts->perfdata.stat_calls++;
retry_lstat:
if (p_lstat(make_path.ptr, &st) < 0) {
if (mkdir_attempted || errno != ENOENT) {
git_error_set(GIT_ERROR_OS, "cannot access component in path '%s'", make_path.ptr);
error = -1;
goto done;
}
git_error_clear();
opts->perfdata.mkdir_calls++;
mkdir_attempted = true;
if (p_mkdir(make_path.ptr, mode) < 0) {
if (errno == EEXIST)
goto retry_lstat;
git_error_set(GIT_ERROR_OS, "failed to make directory '%s'", make_path.ptr);
error = -1;
goto done;
}
} else {
if ((error = mkdir_validate_dir(
make_path.ptr, &st, mode, flags, opts)) < 0)
goto done;
}
/* chmod if requested and necessary */
if ((error = mkdir_validate_mode(
make_path.ptr, &st, (lastch == '\0'), mode, flags, opts)) < 0)
goto done;
if (opts->dir_map && opts->pool) {
char *cache_path;
size_t alloc_size;
GIT_ERROR_CHECK_ALLOC_ADD(&alloc_size, make_path.size, 1);
cache_path = git_pool_malloc(opts->pool, alloc_size);
GIT_ERROR_CHECK_ALLOC(cache_path);
memcpy(cache_path, make_path.ptr, make_path.size + 1);
if ((error = git_strmap_set(opts->dir_map, cache_path, cache_path)) < 0)
goto done;
}
}
error = 0;
/* check that full path really is a directory if requested & needed */
if ((flags & GIT_MKDIR_VERIFY_DIR) != 0 &&
lastch != '\0') {
opts->perfdata.stat_calls++;
if (p_stat(make_path.ptr, &st) < 0 || !S_ISDIR(st.st_mode)) {
git_error_set(GIT_ERROR_OS, "path is not a directory '%s'",
make_path.ptr);
error = GIT_ENOTFOUND;
}
}
done:
git_buf_dispose(&make_path);
return error;
}
typedef struct {
const char *base;
size_t baselen;
uint32_t flags;
int depth;
} futils__rmdir_data;
#define FUTILS_MAX_DEPTH 100
static int futils__error_cannot_rmdir(const char *path, const char *filemsg)
{
if (filemsg)
git_error_set(GIT_ERROR_OS, "could not remove directory '%s': %s",
path, filemsg);
else
git_error_set(GIT_ERROR_OS, "could not remove directory '%s'", path);
return -1;
}
static int futils__rm_first_parent(git_buf *path, const char *ceiling)
{
int error = GIT_ENOTFOUND;
struct stat st;
while (error == GIT_ENOTFOUND) {
git_buf_rtruncate_at_char(path, '/');
if (!path->size || git__prefixcmp(path->ptr, ceiling) != 0)
error = 0;
else if (p_lstat_posixly(path->ptr, &st) == 0) {
if (S_ISREG(st.st_mode) || S_ISLNK(st.st_mode))
error = p_unlink(path->ptr);
else if (!S_ISDIR(st.st_mode))
error = -1; /* fail to remove non-regular file */
} else if (errno != ENOTDIR)
error = -1;
}
if (error)
futils__error_cannot_rmdir(path->ptr, "cannot remove parent");
return error;
}
static int futils__rmdir_recurs_foreach(void *opaque, git_buf *path)
{
int error = 0;
futils__rmdir_data *data = opaque;
struct stat st;
if (data->depth > FUTILS_MAX_DEPTH)
error = futils__error_cannot_rmdir(
path->ptr, "directory nesting too deep");
else if ((error = p_lstat_posixly(path->ptr, &st)) < 0) {
if (errno == ENOENT)
error = 0;
else if (errno == ENOTDIR) {
/* asked to remove a/b/c/d/e and a/b is a normal file */
if ((data->flags & GIT_RMDIR_REMOVE_BLOCKERS) != 0)
error = futils__rm_first_parent(path, data->base);
else
futils__error_cannot_rmdir(
path->ptr, "parent is not directory");
}
else
error = git_path_set_error(errno, path->ptr, "rmdir");
}
else if (S_ISDIR(st.st_mode)) {
data->depth++;
error = git_path_direach(path, 0, futils__rmdir_recurs_foreach, data);
data->depth--;
if (error < 0)
return error;
if (data->depth == 0 && (data->flags & GIT_RMDIR_SKIP_ROOT) != 0)
return error;
if ((error = p_rmdir(path->ptr)) < 0) {
if ((data->flags & GIT_RMDIR_SKIP_NONEMPTY) != 0 &&
(errno == ENOTEMPTY || errno == EEXIST || errno == EBUSY))
error = 0;
else
error = git_path_set_error(errno, path->ptr, "rmdir");
}
}
else if ((data->flags & GIT_RMDIR_REMOVE_FILES) != 0) {
if (p_unlink(path->ptr) < 0)
error = git_path_set_error(errno, path->ptr, "remove");
}
else if ((data->flags & GIT_RMDIR_SKIP_NONEMPTY) == 0)
error = futils__error_cannot_rmdir(path->ptr, "still present");
return error;
}
static int futils__rmdir_empty_parent(void *opaque, const char *path)
{
futils__rmdir_data *data = opaque;
int error = 0;
if (strlen(path) <= data->baselen)
error = GIT_ITEROVER;
else if (p_rmdir(path) < 0) {
int en = errno;
if (en == ENOENT || en == ENOTDIR) {
/* do nothing */
} else if ((data->flags & GIT_RMDIR_SKIP_NONEMPTY) == 0 &&
en == EBUSY) {
error = git_path_set_error(errno, path, "rmdir");
} else if (en == ENOTEMPTY || en == EEXIST || en == EBUSY) {
error = GIT_ITEROVER;
} else {
error = git_path_set_error(errno, path, "rmdir");
}
}
return error;
}
int git_futils_rmdir_r(
const char *path, const char *base, uint32_t flags)
{
int error;
git_buf fullpath = GIT_BUF_INIT;
futils__rmdir_data data;
/* build path and find "root" where we should start calling mkdir */
if (git_path_join_unrooted(&fullpath, path, base, NULL) < 0)
return -1;
memset(&data, 0, sizeof(data));
data.base = base ? base : "";
data.baselen = base ? strlen(base) : 0;
data.flags = flags;
error = futils__rmdir_recurs_foreach(&data, &fullpath);
/* remove now-empty parents if requested */
if (!error && (flags & GIT_RMDIR_EMPTY_PARENTS) != 0)
error = git_path_walk_up(
&fullpath, base, futils__rmdir_empty_parent, &data);
if (error == GIT_ITEROVER) {
git_error_clear();
error = 0;
}
git_buf_dispose(&fullpath);
return error;
}
int git_futils_fake_symlink(const char *target, const char *path)
{
int retcode = GIT_ERROR;
int fd = git_futils_creat_withpath(path, 0755, 0644);
if (fd >= 0) {
retcode = p_write(fd, target, strlen(target));
p_close(fd);
}
return retcode;
}
static int cp_by_fd(int ifd, int ofd, bool close_fd_when_done)
{
int error = 0;
char buffer[FILEIO_BUFSIZE];
ssize_t len = 0;
while (!error && (len = p_read(ifd, buffer, sizeof(buffer))) > 0)
/* p_write() does not have the same semantics as write(). It loops
* internally and will return 0 when it has completed writing.
*/
error = p_write(ofd, buffer, len);
if (len < 0) {
git_error_set(GIT_ERROR_OS, "read error while copying file");
error = (int)len;
}
if (error < 0)
git_error_set(GIT_ERROR_OS, "write error while copying file");
if (close_fd_when_done) {
p_close(ifd);
p_close(ofd);
}
return error;
}
int git_futils_cp(const char *from, const char *to, mode_t filemode)
{
int ifd, ofd;
if ((ifd = git_futils_open_ro(from)) < 0)
return ifd;
if ((ofd = p_open(to, O_WRONLY | O_CREAT | O_EXCL, filemode)) < 0) {
p_close(ifd);
return git_path_set_error(errno, to, "open for writing");
}
return cp_by_fd(ifd, ofd, true);
}
int git_futils_touch(const char *path, time_t *when)
{
struct p_timeval times[2];
int ret;
times[0].tv_sec = times[1].tv_sec = when ? *when : time(NULL);
times[0].tv_usec = times[1].tv_usec = 0;
ret = p_utimes(path, times);
return (ret < 0) ? git_path_set_error(errno, path, "touch") : 0;
}
static int cp_link(const char *from, const char *to, size_t link_size)
{
int error = 0;
ssize_t read_len;
char *link_data;
size_t alloc_size;
GIT_ERROR_CHECK_ALLOC_ADD(&alloc_size, link_size, 1);
link_data = git__malloc(alloc_size);
GIT_ERROR_CHECK_ALLOC(link_data);
read_len = p_readlink(from, link_data, link_size);
if (read_len != (ssize_t)link_size) {
git_error_set(GIT_ERROR_OS, "failed to read symlink data for '%s'", from);
error = -1;
}
else {
link_data[read_len] = '\0';
if (p_symlink(link_data, to) < 0) {
git_error_set(GIT_ERROR_OS, "could not symlink '%s' as '%s'",
link_data, to);
error = -1;
}
}
git__free(link_data);
return error;
}
typedef struct {
const char *to_root;
git_buf to;
ssize_t from_prefix;
uint32_t flags;
uint32_t mkdir_flags;
mode_t dirmode;
} cp_r_info;
#define GIT_CPDIR__MKDIR_DONE_FOR_TO_ROOT (1u << 10)
static int _cp_r_mkdir(cp_r_info *info, git_buf *from)
{
int error = 0;
/* create root directory the first time we need to create a directory */
if ((info->flags & GIT_CPDIR__MKDIR_DONE_FOR_TO_ROOT) == 0) {
error = git_futils_mkdir(
info->to_root, info->dirmode,
(info->flags & GIT_CPDIR_CHMOD_DIRS) ? GIT_MKDIR_CHMOD : 0);
info->flags |= GIT_CPDIR__MKDIR_DONE_FOR_TO_ROOT;
}
/* create directory with root as base to prevent excess chmods */
if (!error)
error = git_futils_mkdir_relative(
from->ptr + info->from_prefix, info->to_root,
info->dirmode, info->mkdir_flags, NULL);
return error;
}
static int _cp_r_callback(void *ref, git_buf *from)
{
int error = 0;
cp_r_info *info = ref;
struct stat from_st, to_st;
bool exists = false;
if ((info->flags & GIT_CPDIR_COPY_DOTFILES) == 0 &&
from->ptr[git_path_basename_offset(from)] == '.')
return 0;
if ((error = git_buf_joinpath(
&info->to, info->to_root, from->ptr + info->from_prefix)) < 0)
return error;
if (!(error = git_path_lstat(info->to.ptr, &to_st)))
exists = true;
else if (error != GIT_ENOTFOUND)
return error;
else {
git_error_clear();
error = 0;
}
if ((error = git_path_lstat(from->ptr, &from_st)) < 0)
return error;
if (S_ISDIR(from_st.st_mode)) {
mode_t oldmode = info->dirmode;
/* if we are not chmod'ing, then overwrite dirmode */
if ((info->flags & GIT_CPDIR_CHMOD_DIRS) == 0)
info->dirmode = from_st.st_mode;
/* make directory now if CREATE_EMPTY_DIRS is requested and needed */
if (!exists && (info->flags & GIT_CPDIR_CREATE_EMPTY_DIRS) != 0)
error = _cp_r_mkdir(info, from);
/* recurse onto target directory */
if (!error && (!exists || S_ISDIR(to_st.st_mode)))
error = git_path_direach(from, 0, _cp_r_callback, info);
if (oldmode != 0)
info->dirmode = oldmode;
return error;
}
if (exists) {
if ((info->flags & GIT_CPDIR_OVERWRITE) == 0)
return 0;
if (p_unlink(info->to.ptr) < 0) {
git_error_set(GIT_ERROR_OS, "cannot overwrite existing file '%s'",
info->to.ptr);
return GIT_EEXISTS;
}
}
/* Done if this isn't a regular file or a symlink */
if (!S_ISREG(from_st.st_mode) &&
(!S_ISLNK(from_st.st_mode) ||
(info->flags & GIT_CPDIR_COPY_SYMLINKS) == 0))
return 0;
/* Make container directory on demand if needed */
if ((info->flags & GIT_CPDIR_CREATE_EMPTY_DIRS) == 0 &&
(error = _cp_r_mkdir(info, from)) < 0)
return error;
/* make symlink or regular file */
if (info->flags & GIT_CPDIR_LINK_FILES) {
if ((error = p_link(from->ptr, info->to.ptr)) < 0)
git_error_set(GIT_ERROR_OS, "failed to link '%s'", from->ptr);
} else if (S_ISLNK(from_st.st_mode)) {
error = cp_link(from->ptr, info->to.ptr, (size_t)from_st.st_size);
} else {
mode_t usemode = from_st.st_mode;
if ((info->flags & GIT_CPDIR_SIMPLE_TO_MODE) != 0)
usemode = GIT_PERMS_FOR_WRITE(usemode);
error = git_futils_cp(from->ptr, info->to.ptr, usemode);
}
return error;
}
int git_futils_cp_r(
const char *from,
const char *to,
uint32_t flags,
mode_t dirmode)
{
int error;
git_buf path = GIT_BUF_INIT;
cp_r_info info;
if (git_buf_joinpath(&path, from, "") < 0) /* ensure trailing slash */
return -1;
memset(&info, 0, sizeof(info));
info.to_root = to;
info.flags = flags;
info.dirmode = dirmode;
info.from_prefix = path.size;
git_buf_init(&info.to, 0);
/* precalculate mkdir flags */
if ((flags & GIT_CPDIR_CREATE_EMPTY_DIRS) == 0) {
/* if not creating empty dirs, then use mkdir to create the path on
* demand right before files are copied.
*/
info.mkdir_flags = GIT_MKDIR_PATH | GIT_MKDIR_SKIP_LAST;
if ((flags & GIT_CPDIR_CHMOD_DIRS) != 0)
info.mkdir_flags |= GIT_MKDIR_CHMOD_PATH;
} else {
/* otherwise, we will do simple mkdir as directories are encountered */
info.mkdir_flags =
((flags & GIT_CPDIR_CHMOD_DIRS) != 0) ? GIT_MKDIR_CHMOD : 0;
}
error = _cp_r_callback(&info, &path);
git_buf_dispose(&path);
git_buf_dispose(&info.to);
return error;
}
int git_futils_filestamp_check(
git_futils_filestamp *stamp, const char *path)
{
struct stat st;
/* if the stamp is NULL, then always reload */
if (stamp == NULL)
return 1;
if (p_stat(path, &st) < 0)
return GIT_ENOTFOUND;
if (stamp->mtime.tv_sec == st.st_mtime &&
#if defined(GIT_USE_NSEC)
stamp->mtime.tv_nsec == st.st_mtime_nsec &&
#endif
stamp->size == (uint64_t)st.st_size &&
stamp->ino == (unsigned int)st.st_ino)
return 0;
stamp->mtime.tv_sec = st.st_mtime;
#if defined(GIT_USE_NSEC)
stamp->mtime.tv_nsec = st.st_mtime_nsec;
#endif
stamp->size = (uint64_t)st.st_size;
stamp->ino = (unsigned int)st.st_ino;
return 1;
}
void git_futils_filestamp_set(
git_futils_filestamp *target, const git_futils_filestamp *source)
{
if (source)
memcpy(target, source, sizeof(*target));
else
memset(target, 0, sizeof(*target));
}
void git_futils_filestamp_set_from_stat(
git_futils_filestamp *stamp, struct stat *st)
{
if (st) {
stamp->mtime.tv_sec = st->st_mtime;
#if defined(GIT_USE_NSEC)
stamp->mtime.tv_nsec = st->st_mtime_nsec;
#else
stamp->mtime.tv_nsec = 0;
#endif
stamp->size = (uint64_t)st->st_size;
stamp->ino = (unsigned int)st->st_ino;
} else {
memset(stamp, 0, sizeof(*stamp));
}
}
int git_futils_fsync_dir(const char *path)
{
#ifdef GIT_WIN32
GIT_UNUSED(path);
return 0;
#else
int fd, error = -1;
if ((fd = p_open(path, O_RDONLY)) < 0) {
git_error_set(GIT_ERROR_OS, "failed to open directory '%s' for fsync", path);
return -1;
}
if ((error = p_fsync(fd)) < 0)
git_error_set(GIT_ERROR_OS, "failed to fsync directory '%s'", path);
p_close(fd);
return error;
#endif
}
int git_futils_fsync_parent(const char *path)
{
char *parent;
int error;
if ((parent = git_path_dirname(path)) == NULL)
return -1;
error = git_futils_fsync_dir(parent);
git__free(parent);
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/userdiff.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_userdiff_h__
#define INCLUDE_userdiff_h__
#include "regexp.h"
/*
* This file isolates the built in diff driver function name patterns.
* Most of these patterns are taken from Git (with permission from the
* original authors for relicensing to libgit2).
*/
typedef struct {
const char *name;
const char *fns;
const char *words;
int flags;
} git_diff_driver_definition;
#define WORD_DEFAULT "|[^[:space:]]|[\xc0-\xff][\x80-\xbf]+"
/*
* These builtin driver definition macros have same signature as in core
* git userdiff.c so that the data can be extracted verbatim
*/
#define PATTERNS(NAME, FN_PATS, WORD_PAT) \
{ NAME, FN_PATS, WORD_PAT WORD_DEFAULT, 0 }
#define IPATTERN(NAME, FN_PATS, WORD_PAT) \
{ NAME, FN_PATS, WORD_PAT WORD_DEFAULT, GIT_REGEXP_ICASE }
/*
* The table of diff driver patterns
*
* Function name patterns are a list of newline separated patterns that
* match a function declaration (i.e. the line you want in the hunk header),
* or a negative pattern prefixed with a '!' to reject a pattern (such as
* rejecting goto labels in C code).
*
* Word boundary patterns are just a simple pattern that will be OR'ed with
* the default value above (i.e. whitespace or non-ASCII characters).
*/
static git_diff_driver_definition builtin_defs[] = {
IPATTERN("ada",
"!^(.*[ \t])?(is[ \t]+new|renames|is[ \t]+separate)([ \t].*)?$\n"
"!^[ \t]*with[ \t].*$\n"
"^[ \t]*((procedure|function)[ \t]+.*)$\n"
"^[ \t]*((package|protected|task)[ \t]+.*)$",
/* -- */
"[a-zA-Z][a-zA-Z0-9_]*"
"|[-+]?[0-9][0-9#_.aAbBcCdDeEfF]*([eE][+-]?[0-9_]+)?"
"|=>|\\.\\.|\\*\\*|:=|/=|>=|<=|<<|>>|<>"),
IPATTERN("fortran",
"!^([C*]|[ \t]*!)\n"
"!^[ \t]*MODULE[ \t]+PROCEDURE[ \t]\n"
"^[ \t]*((END[ \t]+)?(PROGRAM|MODULE|BLOCK[ \t]+DATA"
"|([^'\" \t]+[ \t]+)*(SUBROUTINE|FUNCTION))[ \t]+[A-Z].*)$",
/* -- */
"[a-zA-Z][a-zA-Z0-9_]*"
"|\\.([Ee][Qq]|[Nn][Ee]|[Gg][TtEe]|[Ll][TtEe]|[Tt][Rr][Uu][Ee]|[Ff][Aa][Ll][Ss][Ee]|[Aa][Nn][Dd]|[Oo][Rr]|[Nn]?[Ee][Qq][Vv]|[Nn][Oo][Tt])\\."
/* numbers and format statements like 2E14.4, or ES12.6, 9X.
* Don't worry about format statements without leading digits since
* they would have been matched above as a variable anyway. */
"|[-+]?[0-9.]+([AaIiDdEeFfLlTtXx][Ss]?[-+]?[0-9.]*)?(_[a-zA-Z0-9][a-zA-Z0-9_]*)?"
"|//|\\*\\*|::|[/<>=]="),
PATTERNS("html", "^[ \t]*(<[Hh][1-6][ \t].*>.*)$",
"[^<>= \t]+"),
PATTERNS("java",
"!^[ \t]*(catch|do|for|if|instanceof|new|return|switch|throw|while)\n"
"^[ \t]*(([A-Za-z_][A-Za-z_0-9]*[ \t]+)+[A-Za-z_][A-Za-z_0-9]*[ \t]*\\([^;]*)$",
/* -- */
"[a-zA-Z_][a-zA-Z0-9_]*"
"|[-+0-9.e]+[fFlL]?|0[xXbB]?[0-9a-fA-F]+[lL]?"
"|[-+*/<>%&^|=!]="
"|--|\\+\\+|<<=?|>>>?=?|&&|\\|\\|"),
PATTERNS("matlab",
"^[[:space:]]*((classdef|function)[[:space:]].*)$|^%%[[:space:]].*$",
"[a-zA-Z_][a-zA-Z0-9_]*|[-+0-9.e]+|[=~<>]=|\\.[*/\\^']|\\|\\||&&"),
PATTERNS("objc",
/* Negate C statements that can look like functions */
"!^[ \t]*(do|for|if|else|return|switch|while)\n"
/* Objective-C methods */
"^[ \t]*([-+][ \t]*\\([ \t]*[A-Za-z_][A-Za-z_0-9* \t]*\\)[ \t]*[A-Za-z_].*)$\n"
/* C functions */
"^[ \t]*(([A-Za-z_][A-Za-z_0-9]*[ \t]+)+[A-Za-z_][A-Za-z_0-9]*[ \t]*\\([^;]*)$\n"
/* Objective-C class/protocol definitions */
"^(@(implementation|interface|protocol)[ \t].*)$",
/* -- */
"[a-zA-Z_][a-zA-Z0-9_]*"
"|[-+0-9.e]+[fFlL]?|0[xXbB]?[0-9a-fA-F]+[lL]?"
"|[-+*/<>%&^|=!]=|--|\\+\\+|<<=?|>>=?|&&|\\|\\||::|->"),
PATTERNS("pascal",
"^(((class[ \t]+)?(procedure|function)|constructor|destructor|interface|"
"implementation|initialization|finalization)[ \t]*.*)$"
"\n"
"^(.*=[ \t]*(class|record).*)$",
/* -- */
"[a-zA-Z_][a-zA-Z0-9_]*"
"|[-+0-9.e]+|0[xXbB]?[0-9a-fA-F]+"
"|<>|<=|>=|:=|\\.\\."),
PATTERNS("perl",
"^package .*\n"
"^sub [[:alnum:]_':]+[ \t]*"
"(\\([^)]*\\)[ \t]*)?" /* prototype */
/*
* Attributes. A regex can't count nested parentheses,
* so just slurp up whatever we see, taking care not
* to accept lines like "sub foo; # defined elsewhere".
*
* An attribute could contain a semicolon, but at that
* point it seems reasonable enough to give up.
*/
"(:[^;#]*)?"
"(\\{[ \t]*)?" /* brace can come here or on the next line */
"(#.*)?$\n" /* comment */
"^(BEGIN|END|INIT|CHECK|UNITCHECK|AUTOLOAD|DESTROY)[ \t]*"
"(\\{[ \t]*)?" /* brace can come here or on the next line */
"(#.*)?$\n"
"^=head[0-9] .*", /* POD */
/* -- */
"[[:alpha:]_'][[:alnum:]_']*"
"|0[xb]?[0-9a-fA-F_]*"
/* taking care not to interpret 3..5 as (3.)(.5) */
"|[0-9a-fA-F_]+(\\.[0-9a-fA-F_]+)?([eE][-+]?[0-9_]+)?"
"|=>|-[rwxoRWXOezsfdlpSugkbctTBMAC>]|~~|::"
"|&&=|\\|\\|=|//=|\\*\\*="
"|&&|\\|\\||//|\\+\\+|--|\\*\\*|\\.\\.\\.?"
"|[-+*/%.^&<>=!|]="
"|=~|!~"
"|<<|<>|<=>|>>"),
PATTERNS("python", "^[ \t]*((class|def)[ \t].*)$",
/* -- */
"[a-zA-Z_][a-zA-Z0-9_]*"
"|[-+0-9.e]+[jJlL]?|0[xX]?[0-9a-fA-F]+[lL]?"
"|[-+*/<>%&^|=!]=|//=?|<<=?|>>=?|\\*\\*=?"),
PATTERNS("ruby", "^[ \t]*((class|module|def)[ \t].*)$",
/* -- */
"(@|@@|\\$)?[a-zA-Z_][a-zA-Z0-9_]*"
"|[-+0-9.e]+|0[xXbB]?[0-9a-fA-F]+|\\?(\\\\C-)?(\\\\M-)?."
"|//=?|[-+*/<>%&^|=!]=|<<=?|>>=?|===|\\.{1,3}|::|[!=]~"),
PATTERNS("bibtex", "(@[a-zA-Z]{1,}[ \t]*\\{{0,1}[ \t]*[^ \t\"@',\\#}{~%]*).*$",
"[={}\"]|[^={}\" \t]+"),
PATTERNS("tex", "^(\\\\((sub)*section|chapter|part)\\*{0,1}\\{.*)$",
"\\\\[a-zA-Z@]+|\\\\.|[a-zA-Z0-9\x80-\xff]+"),
PATTERNS("cpp",
/* Jump targets or access declarations */
"!^[ \t]*[A-Za-z_][A-Za-z_0-9]*:[[:space:]]*($|/[/*])\n"
/* functions/methods, variables, and compounds at top level */
"^((::[[:space:]]*)?[A-Za-z_].*)$",
/* -- */
"[a-zA-Z_][a-zA-Z0-9_]*"
"|[-+0-9.e]+[fFlL]?|0[xXbB]?[0-9a-fA-F]+[lLuU]*"
"|[-+*/<>%&^|=!]=|--|\\+\\+|<<=?|>>=?|&&|\\|\\||::|->\\*?|\\.\\*"),
PATTERNS("csharp",
/* Keywords */
"!^[ \t]*(do|while|for|if|else|instanceof|new|return|switch|case|throw|catch|using)\n"
/* Methods and constructors */
"^[ \t]*(((static|public|internal|private|protected|new|virtual|sealed|override|unsafe)[ \t]+)*[][<>@.~_[:alnum:]]+[ \t]+[<>@._[:alnum:]]+[ \t]*\\(.*\\))[ \t]*$\n"
/* Properties */
"^[ \t]*(((static|public|internal|private|protected|new|virtual|sealed|override|unsafe)[ \t]+)*[][<>@.~_[:alnum:]]+[ \t]+[@._[:alnum:]]+)[ \t]*$\n"
/* Type definitions */
"^[ \t]*(((static|public|internal|private|protected|new|unsafe|sealed|abstract|partial)[ \t]+)*(class|enum|interface|struct)[ \t]+.*)$\n"
/* Namespace */
"^[ \t]*(namespace[ \t]+.*)$",
/* -- */
"[a-zA-Z_][a-zA-Z0-9_]*"
"|[-+0-9.e]+[fFlL]?|0[xXbB]?[0-9a-fA-F]+[lL]?"
"|[-+*/<>%&^|=!]=|--|\\+\\+|<<=?|>>=?|&&|\\|\\||::|->"),
PATTERNS("php",
"^[ \t]*(((public|private|protected|static|final)[ \t]+)*((class|function)[ \t].*))$",
/* -- */
"[a-zA-Z_][a-zA-Z0-9_]*"
"|[-+0-9.e]+[fFlL]?|0[xX]?[0-9a-fA-F]+[lL]?"
"|[-+*/<>%&^|=!]=|--|\\+\\+|<<=?|>>=?|&&|\\|\\||::|->"),
PATTERNS("javascript",
"([a-zA-Z_$][a-zA-Z0-9_$]*(\\.[a-zA-Z0-9_$]+)*[ \t]*=[ \t]*function([ \t][a-zA-Z_$][a-zA-Z0-9_$]*)?[^\\{]*)\n"
"([a-zA-Z_$][a-zA-Z0-9_$]*[ \t]*:[ \t]*function([ \t][a-zA-Z_$][a-zA-Z0-9_$]*)?[^\\{]*)\n"
"[^a-zA-Z0-9_\\$](function([ \t][a-zA-Z_$][a-zA-Z0-9_$]*)?[^\\{]*)",
/* -- */
"[a-zA-Z_][a-zA-Z0-9_]*"
"|[-+0-9.e]+[fFlL]?|0[xX]?[0-9a-fA-F]+[lL]?"
"|[-+*/<>%&^|=!]=|--|\\+\\+|<<=?|>>=?|&&|\\|\\||::|->"),
};
#undef IPATTERN
#undef PATTERNS
#undef WORD_DEFAULT
#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/vector.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_vector_h__
#define INCLUDE_vector_h__
#include "common.h"
typedef int (*git_vector_cmp)(const void *, const void *);
enum {
GIT_VECTOR_SORTED = (1u << 0),
GIT_VECTOR_FLAG_MAX = (1u << 1),
};
typedef struct git_vector {
size_t _alloc_size;
git_vector_cmp _cmp;
void **contents;
size_t length;
uint32_t flags;
} git_vector;
#define GIT_VECTOR_INIT {0}
GIT_WARN_UNUSED_RESULT int git_vector_init(
git_vector *v, size_t initial_size, git_vector_cmp cmp);
void git_vector_free(git_vector *v);
void git_vector_free_deep(git_vector *v); /* free each entry and self */
void git_vector_clear(git_vector *v);
GIT_WARN_UNUSED_RESULT int git_vector_dup(
git_vector *v, const git_vector *src, git_vector_cmp cmp);
void git_vector_swap(git_vector *a, git_vector *b);
int git_vector_size_hint(git_vector *v, size_t size_hint);
void **git_vector_detach(size_t *size, size_t *asize, git_vector *v);
void git_vector_sort(git_vector *v);
/** Linear search for matching entry using internal comparison function */
int git_vector_search(size_t *at_pos, const git_vector *v, const void *entry);
/** Linear search for matching entry using explicit comparison function */
int git_vector_search2(size_t *at_pos, const git_vector *v, git_vector_cmp cmp, const void *key);
/**
* Binary search for matching entry using explicit comparison function that
* returns position where item would go if not found.
*/
int git_vector_bsearch2(
size_t *at_pos, git_vector *v, git_vector_cmp cmp, const void *key);
/** Binary search for matching entry using internal comparison function */
GIT_INLINE(int) git_vector_bsearch(size_t *at_pos, git_vector *v, const void *key)
{
return git_vector_bsearch2(at_pos, v, v->_cmp, key);
}
GIT_INLINE(void *) git_vector_get(const git_vector *v, size_t position)
{
return (position < v->length) ? v->contents[position] : NULL;
}
#define GIT_VECTOR_GET(V,I) ((I) < (V)->length ? (V)->contents[(I)] : NULL)
GIT_INLINE(size_t) git_vector_length(const git_vector *v)
{
return v->length;
}
GIT_INLINE(void *) git_vector_last(const git_vector *v)
{
return (v->length > 0) ? git_vector_get(v, v->length - 1) : NULL;
}
#define git_vector_foreach(v, iter, elem) \
for ((iter) = 0; (iter) < (v)->length && ((elem) = (v)->contents[(iter)], 1); (iter)++ )
#define git_vector_rforeach(v, iter, elem) \
for ((iter) = (v)->length - 1; (iter) < SIZE_MAX && ((elem) = (v)->contents[(iter)], 1); (iter)-- )
int git_vector_insert(git_vector *v, void *element);
int git_vector_insert_sorted(git_vector *v, void *element,
int (*on_dup)(void **old, void *new));
int git_vector_remove(git_vector *v, size_t idx);
void git_vector_pop(git_vector *v);
void git_vector_uniq(git_vector *v, void (*git_free_cb)(void *));
void git_vector_remove_matching(
git_vector *v,
int (*match)(const git_vector *v, size_t idx, void *payload),
void *payload);
int git_vector_resize_to(git_vector *v, size_t new_length);
int git_vector_insert_null(git_vector *v, size_t idx, size_t insert_len);
int git_vector_remove_range(git_vector *v, size_t idx, size_t remove_len);
int git_vector_set(void **old, git_vector *v, size_t position, void *value);
/** Check if vector is sorted */
#define git_vector_is_sorted(V) (((V)->flags & GIT_VECTOR_SORTED) != 0)
/** Directly set sorted state of vector */
#define git_vector_set_sorted(V,S) do { \
(V)->flags = (S) ? ((V)->flags | GIT_VECTOR_SORTED) : \
((V)->flags & ~GIT_VECTOR_SORTED); } while (0)
/** Set the comparison function used for sorting the vector */
GIT_INLINE(void) git_vector_set_cmp(git_vector *v, git_vector_cmp cmp)
{
if (cmp != v->_cmp) {
v->_cmp = cmp;
git_vector_set_sorted(v, 0);
}
}
/* Just use this in tests, not for realz. returns -1 if not sorted */
int git_vector_verify_sorted(const git_vector *v);
/**
* Reverse the vector in-place.
*/
void git_vector_reverse(git_vector *v);
#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/push.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 "push.h"
#include "git2.h"
#include "pack.h"
#include "pack-objects.h"
#include "remote.h"
#include "vector.h"
#include "tree.h"
static int push_spec_rref_cmp(const void *a, const void *b)
{
const push_spec *push_spec_a = a, *push_spec_b = b;
return strcmp(push_spec_a->refspec.dst, push_spec_b->refspec.dst);
}
static int push_status_ref_cmp(const void *a, const void *b)
{
const push_status *push_status_a = a, *push_status_b = b;
return strcmp(push_status_a->ref, push_status_b->ref);
}
int git_push_new(git_push **out, git_remote *remote)
{
git_push *p;
*out = NULL;
p = git__calloc(1, sizeof(*p));
GIT_ERROR_CHECK_ALLOC(p);
p->repo = remote->repo;
p->remote = remote;
p->report_status = 1;
p->pb_parallelism = 1;
if (git_vector_init(&p->specs, 0, push_spec_rref_cmp) < 0) {
git__free(p);
return -1;
}
if (git_vector_init(&p->status, 0, push_status_ref_cmp) < 0) {
git_vector_free(&p->specs);
git__free(p);
return -1;
}
if (git_vector_init(&p->updates, 0, NULL) < 0) {
git_vector_free(&p->status);
git_vector_free(&p->specs);
git__free(p);
return -1;
}
*out = p;
return 0;
}
int git_push_set_options(git_push *push, const git_push_options *opts)
{
if (!push || !opts)
return -1;
GIT_ERROR_CHECK_VERSION(opts, GIT_PUSH_OPTIONS_VERSION, "git_push_options");
push->pb_parallelism = opts->pb_parallelism;
push->connection.custom_headers = &opts->custom_headers;
push->connection.proxy = &opts->proxy_opts;
return 0;
}
static void free_refspec(push_spec *spec)
{
if (spec == NULL)
return;
git_refspec__dispose(&spec->refspec);
git__free(spec);
}
static int check_rref(char *ref)
{
if (git__prefixcmp(ref, "refs/")) {
git_error_set(GIT_ERROR_INVALID, "not a valid reference '%s'", ref);
return -1;
}
return 0;
}
static int check_lref(git_push *push, char *ref)
{
/* lref must be resolvable to an existing object */
git_object *obj;
int error = git_revparse_single(&obj, push->repo, ref);
git_object_free(obj);
if (!error)
return 0;
if (error == GIT_ENOTFOUND)
git_error_set(GIT_ERROR_REFERENCE,
"src refspec '%s' does not match any existing object", ref);
else
git_error_set(GIT_ERROR_INVALID, "not a valid reference '%s'", ref);
return -1;
}
static int parse_refspec(git_push *push, push_spec **spec, const char *str)
{
push_spec *s;
*spec = NULL;
s = git__calloc(1, sizeof(*s));
GIT_ERROR_CHECK_ALLOC(s);
if (git_refspec__parse(&s->refspec, str, false) < 0) {
git_error_set(GIT_ERROR_INVALID, "invalid refspec %s", str);
goto on_error;
}
if (s->refspec.src && s->refspec.src[0] != '\0' &&
check_lref(push, s->refspec.src) < 0) {
goto on_error;
}
if (check_rref(s->refspec.dst) < 0)
goto on_error;
*spec = s;
return 0;
on_error:
free_refspec(s);
return -1;
}
int git_push_add_refspec(git_push *push, const char *refspec)
{
push_spec *spec;
if (parse_refspec(push, &spec, refspec) < 0 ||
git_vector_insert(&push->specs, spec) < 0)
return -1;
return 0;
}
int git_push_update_tips(git_push *push, const git_remote_callbacks *callbacks)
{
git_buf remote_ref_name = GIT_BUF_INIT;
size_t i, j;
git_refspec *fetch_spec;
push_spec *push_spec = NULL;
git_reference *remote_ref;
push_status *status;
int error = 0;
git_vector_foreach(&push->status, i, status) {
int fire_callback = 1;
/* Skip unsuccessful updates which have non-empty messages */
if (status->msg)
continue;
/* Find the corresponding remote ref */
fetch_spec = git_remote__matching_refspec(push->remote, status->ref);
if (!fetch_spec)
continue;
/* Clear the buffer which can be dirty from previous iteration */
git_buf_clear(&remote_ref_name);
if ((error = git_refspec_transform(&remote_ref_name, fetch_spec, status->ref)) < 0)
goto on_error;
/* Find matching push ref spec */
git_vector_foreach(&push->specs, j, push_spec) {
if (!strcmp(push_spec->refspec.dst, status->ref))
break;
}
/* Could not find the corresponding push ref spec for this push update */
if (j == push->specs.length)
continue;
/* Update the remote ref */
if (git_oid_is_zero(&push_spec->loid)) {
error = git_reference_lookup(&remote_ref, push->remote->repo, git_buf_cstr(&remote_ref_name));
if (error >= 0) {
error = git_reference_delete(remote_ref);
git_reference_free(remote_ref);
}
} else {
error = git_reference_create(NULL, push->remote->repo,
git_buf_cstr(&remote_ref_name), &push_spec->loid, 1,
"update by push");
}
if (error < 0) {
if (error != GIT_ENOTFOUND)
goto on_error;
git_error_clear();
fire_callback = 0;
}
if (fire_callback && callbacks && callbacks->update_tips) {
error = callbacks->update_tips(git_buf_cstr(&remote_ref_name),
&push_spec->roid, &push_spec->loid, callbacks->payload);
if (error < 0)
goto on_error;
}
}
error = 0;
on_error:
git_buf_dispose(&remote_ref_name);
return error;
}
/**
* Insert all tags until we find a non-tag object, which is returned
* in `out`.
*/
static int enqueue_tag(git_object **out, git_push *push, git_oid *id)
{
git_object *obj = NULL, *target = NULL;
int error;
if ((error = git_object_lookup(&obj, push->repo, id, GIT_OBJECT_TAG)) < 0)
return error;
while (git_object_type(obj) == GIT_OBJECT_TAG) {
if ((error = git_packbuilder_insert(push->pb, git_object_id(obj), NULL)) < 0)
break;
if ((error = git_tag_target(&target, (git_tag *) obj)) < 0)
break;
git_object_free(obj);
obj = target;
}
if (error < 0)
git_object_free(obj);
else
*out = obj;
return error;
}
static int queue_objects(git_push *push)
{
git_remote_head *head;
push_spec *spec;
git_revwalk *rw;
unsigned int i;
int error = -1;
if (git_revwalk_new(&rw, push->repo) < 0)
return -1;
git_revwalk_sorting(rw, GIT_SORT_TIME);
git_vector_foreach(&push->specs, i, spec) {
git_object_t type;
size_t size;
if (git_oid_is_zero(&spec->loid))
/*
* Delete reference on remote side;
* nothing to do here.
*/
continue;
if (git_oid_equal(&spec->loid, &spec->roid))
continue; /* up-to-date */
if (git_odb_read_header(&size, &type, push->repo->_odb, &spec->loid) < 0)
goto on_error;
if (type == GIT_OBJECT_TAG) {
git_object *target;
if ((error = enqueue_tag(&target, push, &spec->loid)) < 0)
goto on_error;
if (git_object_type(target) == GIT_OBJECT_COMMIT) {
if (git_revwalk_push(rw, git_object_id(target)) < 0) {
git_object_free(target);
goto on_error;
}
} else {
if (git_packbuilder_insert(
push->pb, git_object_id(target), NULL) < 0) {
git_object_free(target);
goto on_error;
}
}
git_object_free(target);
} else if (git_revwalk_push(rw, &spec->loid) < 0)
goto on_error;
if (!spec->refspec.force) {
git_oid base;
if (git_oid_is_zero(&spec->roid))
continue;
if (!git_odb_exists(push->repo->_odb, &spec->roid)) {
git_error_set(GIT_ERROR_REFERENCE,
"cannot push because a reference that you are trying to update on the remote contains commits that are not present locally.");
error = GIT_ENONFASTFORWARD;
goto on_error;
}
error = git_merge_base(&base, push->repo,
&spec->loid, &spec->roid);
if (error == GIT_ENOTFOUND ||
(!error && !git_oid_equal(&base, &spec->roid))) {
git_error_set(GIT_ERROR_REFERENCE,
"cannot push non-fastforwardable reference");
error = GIT_ENONFASTFORWARD;
goto on_error;
}
if (error < 0)
goto on_error;
}
}
git_vector_foreach(&push->remote->refs, i, head) {
if (git_oid_is_zero(&head->oid))
continue;
if ((error = git_revwalk_hide(rw, &head->oid)) < 0 &&
error != GIT_ENOTFOUND && error != GIT_EINVALIDSPEC && error != GIT_EPEEL)
goto on_error;
}
error = git_packbuilder_insert_walk(push->pb, rw);
on_error:
git_revwalk_free(rw);
return error;
}
static int add_update(git_push *push, push_spec *spec)
{
git_push_update *u = git__calloc(1, sizeof(git_push_update));
GIT_ERROR_CHECK_ALLOC(u);
u->src_refname = git__strdup(spec->refspec.src);
GIT_ERROR_CHECK_ALLOC(u->src_refname);
u->dst_refname = git__strdup(spec->refspec.dst);
GIT_ERROR_CHECK_ALLOC(u->dst_refname);
git_oid_cpy(&u->src, &spec->roid);
git_oid_cpy(&u->dst, &spec->loid);
return git_vector_insert(&push->updates, u);
}
static int calculate_work(git_push *push)
{
git_remote_head *head;
push_spec *spec;
unsigned int i, j;
/* Update local and remote oids*/
git_vector_foreach(&push->specs, i, spec) {
if (spec->refspec.src && spec->refspec.src[0]!= '\0') {
/* This is a create or update. Local ref must exist. */
if (git_reference_name_to_id(
&spec->loid, push->repo, spec->refspec.src) < 0) {
git_error_set(GIT_ERROR_REFERENCE, "no such reference '%s'", spec->refspec.src);
return -1;
}
}
/* Remote ref may or may not (e.g. during create) already exist. */
git_vector_foreach(&push->remote->refs, j, head) {
if (!strcmp(spec->refspec.dst, head->name)) {
git_oid_cpy(&spec->roid, &head->oid);
break;
}
}
if (add_update(push, spec) < 0)
return -1;
}
return 0;
}
static int do_push(git_push *push, const git_remote_callbacks *callbacks)
{
int error = 0;
git_transport *transport = push->remote->transport;
if (!transport->push) {
git_error_set(GIT_ERROR_NET, "remote transport doesn't support push");
error = -1;
goto on_error;
}
/*
* A pack-file MUST be sent if either create or update command
* is used, even if the server already has all the necessary
* objects. In this case the client MUST send an empty pack-file.
*/
if ((error = git_packbuilder_new(&push->pb, push->repo)) < 0)
goto on_error;
git_packbuilder_set_threads(push->pb, push->pb_parallelism);
if (callbacks && callbacks->pack_progress)
if ((error = git_packbuilder_set_callbacks(push->pb, callbacks->pack_progress, callbacks->payload)) < 0)
goto on_error;
if ((error = calculate_work(push)) < 0)
goto on_error;
if (callbacks && callbacks->push_negotiation &&
(error = callbacks->push_negotiation((const git_push_update **) push->updates.contents,
push->updates.length, callbacks->payload)) < 0)
goto on_error;
if ((error = queue_objects(push)) < 0 ||
(error = transport->push(transport, push, callbacks)) < 0)
goto on_error;
on_error:
git_packbuilder_free(push->pb);
return error;
}
static int filter_refs(git_remote *remote)
{
const git_remote_head **heads;
size_t heads_len, i;
git_vector_clear(&remote->refs);
if (git_remote_ls(&heads, &heads_len, remote) < 0)
return -1;
for (i = 0; i < heads_len; i++) {
if (git_vector_insert(&remote->refs, (void *)heads[i]) < 0)
return -1;
}
return 0;
}
int git_push_finish(git_push *push, const git_remote_callbacks *callbacks)
{
int error;
if (!git_remote_connected(push->remote) &&
(error = git_remote__connect(push->remote, GIT_DIRECTION_PUSH, callbacks, &push->connection)) < 0)
return error;
if ((error = filter_refs(push->remote)) < 0 ||
(error = do_push(push, callbacks)) < 0)
return error;
if (!push->unpack_ok) {
error = -1;
git_error_set(GIT_ERROR_NET, "unpacking the sent packfile failed on the remote");
}
return error;
}
int git_push_status_foreach(git_push *push,
int (*cb)(const char *ref, const char *msg, void *data),
void *data)
{
push_status *status;
unsigned int i;
git_vector_foreach(&push->status, i, status) {
int error = cb(status->ref, status->msg, data);
if (error)
return git_error_set_after_callback(error);
}
return 0;
}
void git_push_status_free(push_status *status)
{
if (status == NULL)
return;
git__free(status->msg);
git__free(status->ref);
git__free(status);
}
void git_push_free(git_push *push)
{
push_spec *spec;
push_status *status;
git_push_update *update;
unsigned int i;
if (push == NULL)
return;
git_vector_foreach(&push->specs, i, spec) {
free_refspec(spec);
}
git_vector_free(&push->specs);
git_vector_foreach(&push->status, i, status) {
git_push_status_free(status);
}
git_vector_free(&push->status);
git_vector_foreach(&push->updates, i, update) {
git__free(update->src_refname);
git__free(update->dst_refname);
git__free(update);
}
git_vector_free(&push->updates);
git__free(push);
}
int git_push_options_init(git_push_options *opts, unsigned int version)
{
GIT_INIT_STRUCTURE_FROM_TEMPLATE(
opts, version, git_push_options, GIT_PUSH_OPTIONS_INIT);
return 0;
}
#ifndef GIT_DEPRECATE_HARD
int git_push_init_options(git_push_options *opts, unsigned int version)
{
return git_push_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/signature.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 "signature.h"
#include "repository.h"
#include "git2/common.h"
#include "posix.h"
void git_signature_free(git_signature *sig)
{
if (sig == NULL)
return;
git__free(sig->name);
sig->name = NULL;
git__free(sig->email);
sig->email = NULL;
git__free(sig);
}
static int signature_error(const char *msg)
{
git_error_set(GIT_ERROR_INVALID, "failed to parse signature - %s", msg);
return -1;
}
static bool contains_angle_brackets(const char *input)
{
return strchr(input, '<') != NULL || strchr(input, '>') != NULL;
}
static bool is_crud(unsigned char c)
{
return c <= 32 ||
c == '.' ||
c == ',' ||
c == ':' ||
c == ';' ||
c == '<' ||
c == '>' ||
c == '"' ||
c == '\\' ||
c == '\'';
}
static char *extract_trimmed(const char *ptr, size_t len)
{
while (len && is_crud((unsigned char)ptr[0])) {
ptr++; len--;
}
while (len && is_crud((unsigned char)ptr[len - 1])) {
len--;
}
return git__substrdup(ptr, len);
}
int git_signature_new(git_signature **sig_out, const char *name, const char *email, git_time_t time, int offset)
{
git_signature *p = NULL;
GIT_ASSERT_ARG(name);
GIT_ASSERT_ARG(email);
*sig_out = NULL;
if (contains_angle_brackets(name) ||
contains_angle_brackets(email)) {
return signature_error(
"Neither `name` nor `email` should contain angle brackets chars.");
}
p = git__calloc(1, sizeof(git_signature));
GIT_ERROR_CHECK_ALLOC(p);
p->name = extract_trimmed(name, strlen(name));
GIT_ERROR_CHECK_ALLOC(p->name);
p->email = extract_trimmed(email, strlen(email));
GIT_ERROR_CHECK_ALLOC(p->email);
if (p->name[0] == '\0' || p->email[0] == '\0') {
git_signature_free(p);
return signature_error("Signature cannot have an empty name or email");
}
p->when.time = time;
p->when.offset = offset;
p->when.sign = (offset < 0) ? '-' : '+';
*sig_out = p;
return 0;
}
int git_signature_dup(git_signature **dest, const git_signature *source)
{
git_signature *signature;
if (source == NULL)
return 0;
signature = git__calloc(1, sizeof(git_signature));
GIT_ERROR_CHECK_ALLOC(signature);
signature->name = git__strdup(source->name);
GIT_ERROR_CHECK_ALLOC(signature->name);
signature->email = git__strdup(source->email);
GIT_ERROR_CHECK_ALLOC(signature->email);
signature->when.time = source->when.time;
signature->when.offset = source->when.offset;
signature->when.sign = source->when.sign;
*dest = signature;
return 0;
}
int git_signature__pdup(git_signature **dest, const git_signature *source, git_pool *pool)
{
git_signature *signature;
if (source == NULL)
return 0;
signature = git_pool_mallocz(pool, sizeof(git_signature));
GIT_ERROR_CHECK_ALLOC(signature);
signature->name = git_pool_strdup(pool, source->name);
GIT_ERROR_CHECK_ALLOC(signature->name);
signature->email = git_pool_strdup(pool, source->email);
GIT_ERROR_CHECK_ALLOC(signature->email);
signature->when.time = source->when.time;
signature->when.offset = source->when.offset;
signature->when.sign = source->when.sign;
*dest = signature;
return 0;
}
int git_signature_now(git_signature **sig_out, const char *name, const char *email)
{
time_t now;
time_t offset;
struct tm *utc_tm;
git_signature *sig;
struct tm _utc;
*sig_out = NULL;
/*
* Get the current time as seconds since the epoch and
* transform that into a tm struct containing the time at
* UTC. Give that to mktime which considers it a local time
* (tm_isdst = -1 asks it to take DST into account) and gives
* us that time as seconds since the epoch. The difference
* between its return value and 'now' is our offset to UTC.
*/
time(&now);
utc_tm = p_gmtime_r(&now, &_utc);
utc_tm->tm_isdst = -1;
offset = (time_t)difftime(now, mktime(utc_tm));
offset /= 60;
if (git_signature_new(&sig, name, email, now, (int)offset) < 0)
return -1;
*sig_out = sig;
return 0;
}
int git_signature_default(git_signature **out, git_repository *repo)
{
int error;
git_config *cfg;
const char *user_name, *user_email;
if ((error = git_repository_config_snapshot(&cfg, repo)) < 0)
return error;
if (!(error = git_config_get_string(&user_name, cfg, "user.name")) &&
!(error = git_config_get_string(&user_email, cfg, "user.email")))
error = git_signature_now(out, user_name, user_email);
git_config_free(cfg);
return error;
}
int git_signature__parse(git_signature *sig, const char **buffer_out,
const char *buffer_end, const char *header, char ender)
{
const char *buffer = *buffer_out;
const char *email_start, *email_end;
memset(sig, 0, sizeof(git_signature));
if (ender &&
(buffer_end = memchr(buffer, ender, buffer_end - buffer)) == NULL)
return signature_error("no newline given");
if (header) {
const size_t header_len = strlen(header);
if (buffer + header_len >= buffer_end || memcmp(buffer, header, header_len) != 0)
return signature_error("expected prefix doesn't match actual");
buffer += header_len;
}
email_start = git__memrchr(buffer, '<', buffer_end - buffer);
email_end = git__memrchr(buffer, '>', buffer_end - buffer);
if (!email_start || !email_end || email_end <= email_start)
return signature_error("malformed e-mail");
email_start += 1;
sig->name = extract_trimmed(buffer, email_start - buffer - 1);
sig->email = extract_trimmed(email_start, email_end - email_start);
/* Do we even have a time at the end of the signature? */
if (email_end + 2 < buffer_end) {
const char *time_start = email_end + 2;
const char *time_end;
if (git__strntol64(&sig->when.time, time_start,
buffer_end - time_start, &time_end, 10) < 0) {
git__free(sig->name);
git__free(sig->email);
sig->name = sig->email = NULL;
return signature_error("invalid Unix timestamp");
}
/* do we have a timezone? */
if (time_end + 1 < buffer_end) {
int offset, hours, mins;
const char *tz_start, *tz_end;
tz_start = time_end + 1;
if ((tz_start[0] != '-' && tz_start[0] != '+') ||
git__strntol32(&offset, tz_start + 1,
buffer_end - tz_start - 1, &tz_end, 10) < 0) {
/* malformed timezone, just assume it's zero */
offset = 0;
}
hours = offset / 100;
mins = offset % 100;
/*
* only store timezone if it's not overflowing;
* see http://www.worldtimezone.com/faq.html
*/
if (hours <= 14 && mins <= 59) {
sig->when.offset = (hours * 60) + mins;
sig->when.sign = tz_start[0];
if (tz_start[0] == '-')
sig->when.offset = -sig->when.offset;
}
}
}
*buffer_out = buffer_end + 1;
return 0;
}
int git_signature_from_buffer(git_signature **out, const char *buf)
{
git_signature *sig;
const char *buf_end;
int error;
GIT_ASSERT_ARG(out);
GIT_ASSERT_ARG(buf);
*out = NULL;
sig = git__calloc(1, sizeof(git_signature));
GIT_ERROR_CHECK_ALLOC(sig);
buf_end = buf + strlen(buf);
error = git_signature__parse(sig, &buf, buf_end, NULL, '\0');
if (error)
git__free(sig);
else
*out = sig;
return error;
}
void git_signature__writebuf(git_buf *buf, const char *header, const git_signature *sig)
{
int offset, hours, mins;
char sign;
offset = sig->when.offset;
sign = (sig->when.offset < 0 || sig->when.sign == '-') ? '-' : '+';
if (offset < 0)
offset = -offset;
hours = offset / 60;
mins = offset % 60;
git_buf_printf(buf, "%s%s <%s> %u %c%02d%02d\n",
header ? header : "", sig->name, sig->email,
(unsigned)sig->when.time, sign, hours, mins);
}
bool git_signature__equal(const git_signature *one, const git_signature *two)
{
GIT_ASSERT_ARG(one);
GIT_ASSERT_ARG(two);
return
git__strcmp(one->name, two->name) == 0 &&
git__strcmp(one->email, two->email) == 0 &&
one->when.time == two->when.time &&
one->when.offset == two->when.offset &&
one->when.sign == two->when.sign;
}
|
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.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_attr_h__
#define INCLUDE_attr_h__
#include "common.h"
#include "attr_file.h"
#include "attrcache.h"
#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.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 "indexer.h"
#include "git2/indexer.h"
#include "git2/object.h"
#include "commit.h"
#include "tree.h"
#include "tag.h"
#include "pack.h"
#include "mwindow.h"
#include "posix.h"
#include "pack.h"
#include "filebuf.h"
#include "oid.h"
#include "oidarray.h"
#include "oidmap.h"
#include "zstream.h"
#include "object.h"
size_t git_indexer__max_objects = UINT32_MAX;
#define UINT31_MAX (0x7FFFFFFF)
struct entry {
git_oid oid;
uint32_t crc;
uint32_t offset;
uint64_t offset_long;
};
struct git_indexer {
unsigned int parsed_header :1,
pack_committed :1,
have_stream :1,
have_delta :1,
do_fsync :1,
do_verify :1;
struct git_pack_header hdr;
struct git_pack_file *pack;
unsigned int mode;
off64_t off;
off64_t entry_start;
git_object_t entry_type;
git_buf entry_data;
git_packfile_stream stream;
size_t nr_objects;
git_vector objects;
git_vector deltas;
unsigned int fanout[256];
git_hash_ctx hash_ctx;
git_oid hash;
git_indexer_progress_cb progress_cb;
void *progress_payload;
char objbuf[8*1024];
/* OIDs referenced from pack objects. Used for verification. */
git_oidmap *expected_oids;
/* Needed to look up objects which we want to inject to fix a thin pack */
git_odb *odb;
/* Fields for calculating the packfile trailer (hash of everything before it) */
char inbuf[GIT_OID_RAWSZ];
size_t inbuf_len;
git_hash_ctx trailer;
};
struct delta_info {
off64_t delta_off;
};
const git_oid *git_indexer_hash(const git_indexer *idx)
{
return &idx->hash;
}
static int parse_header(struct git_pack_header *hdr, struct git_pack_file *pack)
{
int error;
git_map map;
if ((error = p_mmap(&map, sizeof(*hdr), GIT_PROT_READ, GIT_MAP_SHARED, pack->mwf.fd, 0)) < 0)
return error;
memcpy(hdr, map.data, sizeof(*hdr));
p_munmap(&map);
/* Verify we recognize this pack file format. */
if (hdr->hdr_signature != ntohl(PACK_SIGNATURE)) {
git_error_set(GIT_ERROR_INDEXER, "wrong pack signature");
return -1;
}
if (!pack_version_ok(hdr->hdr_version)) {
git_error_set(GIT_ERROR_INDEXER, "wrong pack version");
return -1;
}
return 0;
}
static int objects_cmp(const void *a, const void *b)
{
const struct entry *entrya = a;
const struct entry *entryb = b;
return git_oid__cmp(&entrya->oid, &entryb->oid);
}
int git_indexer_options_init(git_indexer_options *opts, unsigned int version)
{
GIT_INIT_STRUCTURE_FROM_TEMPLATE(
opts, version, git_indexer_options, GIT_INDEXER_OPTIONS_INIT);
return 0;
}
#ifndef GIT_DEPRECATE_HARD
int git_indexer_init_options(git_indexer_options *opts, unsigned int version)
{
return git_indexer_options_init(opts, version);
}
#endif
int git_indexer_new(
git_indexer **out,
const char *prefix,
unsigned int mode,
git_odb *odb,
git_indexer_options *in_opts)
{
git_indexer_options opts = GIT_INDEXER_OPTIONS_INIT;
git_indexer *idx;
git_buf path = GIT_BUF_INIT, tmp_path = GIT_BUF_INIT;
static const char suff[] = "/pack";
int error, fd = -1;
if (in_opts)
memcpy(&opts, in_opts, sizeof(opts));
idx = git__calloc(1, sizeof(git_indexer));
GIT_ERROR_CHECK_ALLOC(idx);
idx->odb = odb;
idx->progress_cb = opts.progress_cb;
idx->progress_payload = opts.progress_cb_payload;
idx->mode = mode ? mode : GIT_PACK_FILE_MODE;
git_buf_init(&idx->entry_data, 0);
if ((error = git_hash_ctx_init(&idx->hash_ctx)) < 0 ||
(error = git_hash_ctx_init(&idx->trailer)) < 0 ||
(error = git_oidmap_new(&idx->expected_oids)) < 0)
goto cleanup;
idx->do_verify = opts.verify;
if (git_repository__fsync_gitdir)
idx->do_fsync = 1;
error = git_buf_joinpath(&path, prefix, suff);
if (error < 0)
goto cleanup;
fd = git_futils_mktmp(&tmp_path, git_buf_cstr(&path), idx->mode);
git_buf_dispose(&path);
if (fd < 0)
goto cleanup;
error = git_packfile_alloc(&idx->pack, git_buf_cstr(&tmp_path));
git_buf_dispose(&tmp_path);
if (error < 0)
goto cleanup;
idx->pack->mwf.fd = fd;
if ((error = git_mwindow_file_register(&idx->pack->mwf)) < 0)
goto cleanup;
*out = idx;
return 0;
cleanup:
if (fd != -1)
p_close(fd);
if (git_buf_len(&tmp_path) > 0)
p_unlink(git_buf_cstr(&tmp_path));
if (idx->pack != NULL)
p_unlink(idx->pack->pack_name);
git_buf_dispose(&path);
git_buf_dispose(&tmp_path);
git__free(idx);
return -1;
}
void git_indexer__set_fsync(git_indexer *idx, int do_fsync)
{
idx->do_fsync = !!do_fsync;
}
/* Try to store the delta so we can try to resolve it later */
static int store_delta(git_indexer *idx)
{
struct delta_info *delta;
delta = git__calloc(1, sizeof(struct delta_info));
GIT_ERROR_CHECK_ALLOC(delta);
delta->delta_off = idx->entry_start;
if (git_vector_insert(&idx->deltas, delta) < 0)
return -1;
return 0;
}
static int hash_header(git_hash_ctx *ctx, off64_t len, git_object_t type)
{
char buffer[64];
size_t hdrlen;
int error;
if ((error = git_odb__format_object_header(&hdrlen,
buffer, sizeof(buffer), (size_t)len, type)) < 0)
return error;
return git_hash_update(ctx, buffer, hdrlen);
}
static int hash_object_stream(git_indexer*idx, git_packfile_stream *stream)
{
ssize_t read;
GIT_ASSERT_ARG(idx);
GIT_ASSERT_ARG(stream);
do {
if ((read = git_packfile_stream_read(stream, idx->objbuf, sizeof(idx->objbuf))) < 0)
break;
if (idx->do_verify)
git_buf_put(&idx->entry_data, idx->objbuf, read);
git_hash_update(&idx->hash_ctx, idx->objbuf, read);
} while (read > 0);
if (read < 0)
return (int)read;
return 0;
}
/* In order to create the packfile stream, we need to skip over the delta base description */
static int advance_delta_offset(git_indexer *idx, git_object_t type)
{
git_mwindow *w = NULL;
GIT_ASSERT_ARG(type == GIT_OBJECT_REF_DELTA || type == GIT_OBJECT_OFS_DELTA);
if (type == GIT_OBJECT_REF_DELTA) {
idx->off += GIT_OID_RAWSZ;
} else {
off64_t base_off;
int error = get_delta_base(&base_off, idx->pack, &w, &idx->off, type, idx->entry_start);
git_mwindow_close(&w);
if (error < 0)
return error;
}
return 0;
}
/* Read from the stream and discard any output */
static int read_object_stream(git_indexer *idx, git_packfile_stream *stream)
{
ssize_t read;
GIT_ASSERT_ARG(stream);
do {
read = git_packfile_stream_read(stream, idx->objbuf, sizeof(idx->objbuf));
} while (read > 0);
if (read < 0)
return (int)read;
return 0;
}
static int crc_object(uint32_t *crc_out, git_mwindow_file *mwf, off64_t start, off64_t size)
{
void *ptr;
uint32_t crc;
unsigned int left, len;
git_mwindow *w = NULL;
crc = crc32(0L, Z_NULL, 0);
while (size) {
ptr = git_mwindow_open(mwf, &w, start, (size_t)size, &left);
if (ptr == NULL)
return -1;
len = min(left, (unsigned int)size);
crc = crc32(crc, ptr, len);
size -= len;
start += len;
git_mwindow_close(&w);
}
*crc_out = htonl(crc);
return 0;
}
static int add_expected_oid(git_indexer *idx, const git_oid *oid)
{
/*
* If we know about that object because it is stored in our ODB or
* because we have already processed it as part of our pack file, we do
* not have to expect it.
*/
if ((!idx->odb || !git_odb_exists(idx->odb, oid)) &&
!git_oidmap_exists(idx->pack->idx_cache, oid) &&
!git_oidmap_exists(idx->expected_oids, oid)) {
git_oid *dup = git__malloc(sizeof(*oid));
GIT_ERROR_CHECK_ALLOC(dup);
git_oid_cpy(dup, oid);
return git_oidmap_set(idx->expected_oids, dup, dup);
}
return 0;
}
static int check_object_connectivity(git_indexer *idx, const git_rawobj *obj)
{
git_object *object;
git_oid *expected;
int error;
if (obj->type != GIT_OBJECT_BLOB &&
obj->type != GIT_OBJECT_TREE &&
obj->type != GIT_OBJECT_COMMIT &&
obj->type != GIT_OBJECT_TAG)
return 0;
if ((error = git_object__from_raw(&object, obj->data, obj->len, obj->type)) < 0)
goto out;
if ((expected = git_oidmap_get(idx->expected_oids, &object->cached.oid)) != NULL) {
git_oidmap_delete(idx->expected_oids, &object->cached.oid);
git__free(expected);
}
/*
* Check whether this is a known object. If so, we can just continue as
* we assume that the ODB has a complete graph.
*/
if (idx->odb && git_odb_exists(idx->odb, &object->cached.oid))
return 0;
switch (obj->type) {
case GIT_OBJECT_TREE:
{
git_tree *tree = (git_tree *) object;
git_tree_entry *entry;
size_t i;
git_array_foreach(tree->entries, i, entry)
if (add_expected_oid(idx, entry->oid) < 0)
goto out;
break;
}
case GIT_OBJECT_COMMIT:
{
git_commit *commit = (git_commit *) object;
git_oid *parent_oid;
size_t i;
git_array_foreach(commit->parent_ids, i, parent_oid)
if (add_expected_oid(idx, parent_oid) < 0)
goto out;
if (add_expected_oid(idx, &commit->tree_id) < 0)
goto out;
break;
}
case GIT_OBJECT_TAG:
{
git_tag *tag = (git_tag *) object;
if (add_expected_oid(idx, &tag->target) < 0)
goto out;
break;
}
case GIT_OBJECT_BLOB:
default:
break;
}
out:
git_object_free(object);
return error;
}
static int store_object(git_indexer *idx)
{
int i, error;
git_oid oid;
struct entry *entry;
off64_t entry_size;
struct git_pack_entry *pentry;
off64_t entry_start = idx->entry_start;
entry = git__calloc(1, sizeof(*entry));
GIT_ERROR_CHECK_ALLOC(entry);
pentry = git__calloc(1, sizeof(struct git_pack_entry));
GIT_ERROR_CHECK_ALLOC(pentry);
if (git_hash_final(&oid, &idx->hash_ctx)) {
git__free(pentry);
goto on_error;
}
entry_size = idx->off - entry_start;
if (entry_start > UINT31_MAX) {
entry->offset = UINT32_MAX;
entry->offset_long = entry_start;
} else {
entry->offset = (uint32_t)entry_start;
}
if (idx->do_verify) {
git_rawobj rawobj = {
idx->entry_data.ptr,
idx->entry_data.size,
idx->entry_type
};
if ((error = check_object_connectivity(idx, &rawobj)) < 0)
goto on_error;
}
git_oid_cpy(&pentry->sha1, &oid);
pentry->offset = entry_start;
if (git_oidmap_exists(idx->pack->idx_cache, &pentry->sha1)) {
git_error_set(GIT_ERROR_INDEXER, "duplicate object %s found in pack", git_oid_tostr_s(&pentry->sha1));
git__free(pentry);
goto on_error;
}
if ((error = git_oidmap_set(idx->pack->idx_cache, &pentry->sha1, pentry)) < 0) {
git__free(pentry);
git_error_set_oom();
goto on_error;
}
git_oid_cpy(&entry->oid, &oid);
if (crc_object(&entry->crc, &idx->pack->mwf, entry_start, entry_size) < 0)
goto on_error;
/* Add the object to the list */
if (git_vector_insert(&idx->objects, entry) < 0)
goto on_error;
for (i = oid.id[0]; i < 256; ++i) {
idx->fanout[i]++;
}
return 0;
on_error:
git__free(entry);
return -1;
}
GIT_INLINE(bool) has_entry(git_indexer *idx, git_oid *id)
{
return git_oidmap_exists(idx->pack->idx_cache, id);
}
static int save_entry(git_indexer *idx, struct entry *entry, struct git_pack_entry *pentry, off64_t entry_start)
{
int i;
if (entry_start > UINT31_MAX) {
entry->offset = UINT32_MAX;
entry->offset_long = entry_start;
} else {
entry->offset = (uint32_t)entry_start;
}
pentry->offset = entry_start;
if (git_oidmap_exists(idx->pack->idx_cache, &pentry->sha1) ||
git_oidmap_set(idx->pack->idx_cache, &pentry->sha1, pentry) < 0) {
git_error_set(GIT_ERROR_INDEXER, "cannot insert object into pack");
return -1;
}
/* Add the object to the list */
if (git_vector_insert(&idx->objects, entry) < 0)
return -1;
for (i = entry->oid.id[0]; i < 256; ++i) {
idx->fanout[i]++;
}
return 0;
}
static int hash_and_save(git_indexer *idx, git_rawobj *obj, off64_t entry_start)
{
git_oid oid;
size_t entry_size;
struct entry *entry;
struct git_pack_entry *pentry = NULL;
entry = git__calloc(1, sizeof(*entry));
GIT_ERROR_CHECK_ALLOC(entry);
if (git_odb__hashobj(&oid, obj) < 0) {
git_error_set(GIT_ERROR_INDEXER, "failed to hash object");
goto on_error;
}
pentry = git__calloc(1, sizeof(struct git_pack_entry));
GIT_ERROR_CHECK_ALLOC(pentry);
git_oid_cpy(&pentry->sha1, &oid);
git_oid_cpy(&entry->oid, &oid);
entry->crc = crc32(0L, Z_NULL, 0);
entry_size = (size_t)(idx->off - entry_start);
if (crc_object(&entry->crc, &idx->pack->mwf, entry_start, entry_size) < 0)
goto on_error;
return save_entry(idx, entry, pentry, entry_start);
on_error:
git__free(pentry);
git__free(entry);
git__free(obj->data);
return -1;
}
static int do_progress_callback(git_indexer *idx, git_indexer_progress *stats)
{
if (idx->progress_cb)
return git_error_set_after_callback_function(
idx->progress_cb(stats, idx->progress_payload),
"indexer progress");
return 0;
}
/* Hash everything but the last 20B of input */
static void hash_partially(git_indexer *idx, const uint8_t *data, size_t size)
{
size_t to_expell, to_keep;
if (size == 0)
return;
/* Easy case, dump the buffer and the data minus the last 20 bytes */
if (size >= GIT_OID_RAWSZ) {
git_hash_update(&idx->trailer, idx->inbuf, idx->inbuf_len);
git_hash_update(&idx->trailer, data, size - GIT_OID_RAWSZ);
data += size - GIT_OID_RAWSZ;
memcpy(idx->inbuf, data, GIT_OID_RAWSZ);
idx->inbuf_len = GIT_OID_RAWSZ;
return;
}
/* We can just append */
if (idx->inbuf_len + size <= GIT_OID_RAWSZ) {
memcpy(idx->inbuf + idx->inbuf_len, data, size);
idx->inbuf_len += size;
return;
}
/* We need to partially drain the buffer and then append */
to_keep = GIT_OID_RAWSZ - size;
to_expell = idx->inbuf_len - to_keep;
git_hash_update(&idx->trailer, idx->inbuf, to_expell);
memmove(idx->inbuf, idx->inbuf + to_expell, to_keep);
memcpy(idx->inbuf + to_keep, data, size);
idx->inbuf_len += size - to_expell;
}
#if defined(NO_MMAP) || !defined(GIT_WIN32)
static int write_at(git_indexer *idx, const void *data, off64_t offset, size_t size)
{
size_t remaining_size = size;
const char *ptr = (const char *)data;
/* Handle data size larger that ssize_t */
while (remaining_size > 0) {
ssize_t nb;
HANDLE_EINTR(nb, p_pwrite(idx->pack->mwf.fd, (void *)ptr,
remaining_size, offset));
if (nb <= 0)
return -1;
ptr += nb;
offset += nb;
remaining_size -= nb;
}
return 0;
}
static int append_to_pack(git_indexer *idx, const void *data, size_t size)
{
if (write_at(idx, data, idx->pack->mwf.size, size) < 0) {
git_error_set(GIT_ERROR_OS, "cannot extend packfile '%s'", idx->pack->pack_name);
return -1;
}
return 0;
}
#else
/*
* Windows may keep different views to a networked file for the mmap- and
* open-accessed versions of a file, so any writes done through
* `write(2)`/`pwrite(2)` may not be reflected on the data that `mmap(2)` is
* able to read.
*/
static int write_at(git_indexer *idx, const void *data, off64_t offset, size_t size)
{
git_file fd = idx->pack->mwf.fd;
size_t mmap_alignment;
size_t page_offset;
off64_t page_start;
unsigned char *map_data;
git_map map;
int error;
GIT_ASSERT_ARG(data);
GIT_ASSERT_ARG(size);
if ((error = git__mmap_alignment(&mmap_alignment)) < 0)
return error;
/* the offset needs to be at the mmap boundary for the platform */
page_offset = offset % mmap_alignment;
page_start = offset - page_offset;
if ((error = p_mmap(&map, page_offset + size, GIT_PROT_WRITE, GIT_MAP_SHARED, fd, page_start)) < 0)
return error;
map_data = (unsigned char *)map.data;
memcpy(map_data + page_offset, data, size);
p_munmap(&map);
return 0;
}
static int append_to_pack(git_indexer *idx, const void *data, size_t size)
{
off64_t new_size;
size_t mmap_alignment;
size_t page_offset;
off64_t page_start;
off64_t current_size = idx->pack->mwf.size;
int error;
if (!size)
return 0;
if ((error = git__mmap_alignment(&mmap_alignment)) < 0)
return error;
/* Write a single byte to force the file system to allocate space now or
* report an error, since we can't report errors when writing using mmap.
* Round the size up to the nearest page so that we only need to perform file
* I/O when we add a page, instead of whenever we write even a single byte. */
new_size = current_size + size;
page_offset = new_size % mmap_alignment;
page_start = new_size - page_offset;
if (p_pwrite(idx->pack->mwf.fd, data, 1, page_start + mmap_alignment - 1) < 0) {
git_error_set(GIT_ERROR_OS, "cannot extend packfile '%s'", idx->pack->pack_name);
return -1;
}
return write_at(idx, data, idx->pack->mwf.size, size);
}
#endif
static int read_stream_object(git_indexer *idx, git_indexer_progress *stats)
{
git_packfile_stream *stream = &idx->stream;
off64_t entry_start = idx->off;
size_t entry_size;
git_object_t type;
git_mwindow *w = NULL;
int error;
if (idx->pack->mwf.size <= idx->off + 20)
return GIT_EBUFS;
if (!idx->have_stream) {
error = git_packfile_unpack_header(&entry_size, &type, idx->pack, &w, &idx->off);
if (error == GIT_EBUFS) {
idx->off = entry_start;
return error;
}
if (error < 0)
return error;
git_mwindow_close(&w);
idx->entry_start = entry_start;
git_hash_init(&idx->hash_ctx);
git_buf_clear(&idx->entry_data);
if (type == GIT_OBJECT_REF_DELTA || type == GIT_OBJECT_OFS_DELTA) {
error = advance_delta_offset(idx, type);
if (error == GIT_EBUFS) {
idx->off = entry_start;
return error;
}
if (error < 0)
return error;
idx->have_delta = 1;
} else {
idx->have_delta = 0;
error = hash_header(&idx->hash_ctx, entry_size, type);
if (error < 0)
return error;
}
idx->have_stream = 1;
idx->entry_type = type;
error = git_packfile_stream_open(stream, idx->pack, idx->off);
if (error < 0)
return error;
}
if (idx->have_delta) {
error = read_object_stream(idx, stream);
} else {
error = hash_object_stream(idx, stream);
}
idx->off = stream->curpos;
if (error == GIT_EBUFS)
return error;
/* We want to free the stream reasorces no matter what here */
idx->have_stream = 0;
git_packfile_stream_dispose(stream);
if (error < 0)
return error;
if (idx->have_delta) {
error = store_delta(idx);
} else {
error = store_object(idx);
}
if (error < 0)
return error;
if (!idx->have_delta) {
stats->indexed_objects++;
}
stats->received_objects++;
if ((error = do_progress_callback(idx, stats)) != 0)
return error;
return 0;
}
int git_indexer_append(git_indexer *idx, const void *data, size_t size, git_indexer_progress *stats)
{
int error = -1;
struct git_pack_header *hdr = &idx->hdr;
git_mwindow_file *mwf = &idx->pack->mwf;
GIT_ASSERT_ARG(idx);
GIT_ASSERT_ARG(data);
GIT_ASSERT_ARG(stats);
if ((error = append_to_pack(idx, data, size)) < 0)
return error;
hash_partially(idx, data, (int)size);
/* Make sure we set the new size of the pack */
idx->pack->mwf.size += size;
if (!idx->parsed_header) {
unsigned int total_objects;
if ((unsigned)idx->pack->mwf.size < sizeof(struct git_pack_header))
return 0;
if ((error = parse_header(&idx->hdr, idx->pack)) < 0)
return error;
idx->parsed_header = 1;
idx->nr_objects = ntohl(hdr->hdr_entries);
idx->off = sizeof(struct git_pack_header);
if (idx->nr_objects <= git_indexer__max_objects) {
total_objects = (unsigned int)idx->nr_objects;
} else {
git_error_set(GIT_ERROR_INDEXER, "too many objects");
return -1;
}
if (git_oidmap_new(&idx->pack->idx_cache) < 0)
return -1;
idx->pack->has_cache = 1;
if (git_vector_init(&idx->objects, total_objects, objects_cmp) < 0)
return -1;
if (git_vector_init(&idx->deltas, total_objects / 2, NULL) < 0)
return -1;
stats->received_objects = 0;
stats->local_objects = 0;
stats->total_deltas = 0;
stats->indexed_deltas = 0;
stats->indexed_objects = 0;
stats->total_objects = total_objects;
if ((error = do_progress_callback(idx, stats)) != 0)
return error;
}
/* Now that we have data in the pack, let's try to parse it */
/* As the file grows any windows we try to use will be out of date */
if ((error = git_mwindow_free_all(mwf)) < 0)
goto on_error;
while (stats->indexed_objects < idx->nr_objects) {
if ((error = read_stream_object(idx, stats)) != 0) {
if (error == GIT_EBUFS)
break;
else
goto on_error;
}
}
return 0;
on_error:
git_mwindow_free_all(mwf);
return error;
}
static int index_path(git_buf *path, git_indexer *idx, const char *suffix)
{
const char prefix[] = "pack-";
size_t slash = (size_t)path->size;
/* search backwards for '/' */
while (slash > 0 && path->ptr[slash - 1] != '/')
slash--;
if (git_buf_grow(path, slash + 1 + strlen(prefix) +
GIT_OID_HEXSZ + strlen(suffix) + 1) < 0)
return -1;
git_buf_truncate(path, slash);
git_buf_puts(path, prefix);
git_oid_fmt(path->ptr + git_buf_len(path), &idx->hash);
path->size += GIT_OID_HEXSZ;
git_buf_puts(path, suffix);
return git_buf_oom(path) ? -1 : 0;
}
/**
* Rewind the packfile by the trailer, as we might need to fix the
* packfile by injecting objects at the tail and must overwrite it.
*/
static int seek_back_trailer(git_indexer *idx)
{
idx->pack->mwf.size -= GIT_OID_RAWSZ;
return git_mwindow_free_all(&idx->pack->mwf);
}
static int inject_object(git_indexer *idx, git_oid *id)
{
git_odb_object *obj = NULL;
struct entry *entry = NULL;
struct git_pack_entry *pentry = NULL;
git_oid foo = {{0}};
unsigned char hdr[64];
git_buf buf = GIT_BUF_INIT;
off64_t entry_start;
const void *data;
size_t len, hdr_len;
int error;
if ((error = seek_back_trailer(idx)) < 0)
goto cleanup;
entry_start = idx->pack->mwf.size;
if ((error = git_odb_read(&obj, idx->odb, id)) < 0) {
git_error_set(GIT_ERROR_INDEXER, "missing delta bases");
goto cleanup;
}
data = git_odb_object_data(obj);
len = git_odb_object_size(obj);
entry = git__calloc(1, sizeof(*entry));
GIT_ERROR_CHECK_ALLOC(entry);
entry->crc = crc32(0L, Z_NULL, 0);
/* Write out the object header */
if ((error = git_packfile__object_header(&hdr_len, hdr, len, git_odb_object_type(obj))) < 0 ||
(error = append_to_pack(idx, hdr, hdr_len)) < 0)
goto cleanup;
idx->pack->mwf.size += hdr_len;
entry->crc = crc32(entry->crc, hdr, (uInt)hdr_len);
if ((error = git_zstream_deflatebuf(&buf, data, len)) < 0)
goto cleanup;
/* And then the compressed object */
if ((error = append_to_pack(idx, buf.ptr, buf.size)) < 0)
goto cleanup;
idx->pack->mwf.size += buf.size;
entry->crc = htonl(crc32(entry->crc, (unsigned char *)buf.ptr, (uInt)buf.size));
git_buf_dispose(&buf);
/* Write a fake trailer so the pack functions play ball */
if ((error = append_to_pack(idx, &foo, GIT_OID_RAWSZ)) < 0)
goto cleanup;
idx->pack->mwf.size += GIT_OID_RAWSZ;
pentry = git__calloc(1, sizeof(struct git_pack_entry));
GIT_ERROR_CHECK_ALLOC(pentry);
git_oid_cpy(&pentry->sha1, id);
git_oid_cpy(&entry->oid, id);
idx->off = entry_start + hdr_len + len;
error = save_entry(idx, entry, pentry, entry_start);
cleanup:
if (error) {
git__free(entry);
git__free(pentry);
}
git_odb_object_free(obj);
return error;
}
static int fix_thin_pack(git_indexer *idx, git_indexer_progress *stats)
{
int error, found_ref_delta = 0;
unsigned int i;
struct delta_info *delta;
size_t size;
git_object_t type;
git_mwindow *w = NULL;
off64_t curpos = 0;
unsigned char *base_info;
unsigned int left = 0;
git_oid base;
GIT_ASSERT(git_vector_length(&idx->deltas) > 0);
if (idx->odb == NULL) {
git_error_set(GIT_ERROR_INDEXER, "cannot fix a thin pack without an ODB");
return -1;
}
/* Loop until we find the first REF delta */
git_vector_foreach(&idx->deltas, i, delta) {
if (!delta)
continue;
curpos = delta->delta_off;
error = git_packfile_unpack_header(&size, &type, idx->pack, &w, &curpos);
if (error < 0)
return error;
if (type == GIT_OBJECT_REF_DELTA) {
found_ref_delta = 1;
break;
}
}
if (!found_ref_delta) {
git_error_set(GIT_ERROR_INDEXER, "no REF_DELTA found, cannot inject object");
return -1;
}
/* curpos now points to the base information, which is an OID */
base_info = git_mwindow_open(&idx->pack->mwf, &w, curpos, GIT_OID_RAWSZ, &left);
if (base_info == NULL) {
git_error_set(GIT_ERROR_INDEXER, "failed to map delta information");
return -1;
}
git_oid_fromraw(&base, base_info);
git_mwindow_close(&w);
if (has_entry(idx, &base))
return 0;
if (inject_object(idx, &base) < 0)
return -1;
stats->local_objects++;
return 0;
}
static int resolve_deltas(git_indexer *idx, git_indexer_progress *stats)
{
unsigned int i;
int error;
struct delta_info *delta;
int progressed = 0, non_null = 0, progress_cb_result;
while (idx->deltas.length > 0) {
progressed = 0;
non_null = 0;
git_vector_foreach(&idx->deltas, i, delta) {
git_rawobj obj = {0};
if (!delta)
continue;
non_null = 1;
idx->off = delta->delta_off;
if ((error = git_packfile_unpack(&obj, idx->pack, &idx->off)) < 0) {
if (error == GIT_PASSTHROUGH) {
/* We have not seen the base object, we'll try again later. */
continue;
}
return -1;
}
if (idx->do_verify && check_object_connectivity(idx, &obj) < 0)
/* TODO: error? continue? */
continue;
if (hash_and_save(idx, &obj, delta->delta_off) < 0)
continue;
git__free(obj.data);
stats->indexed_objects++;
stats->indexed_deltas++;
progressed = 1;
if ((progress_cb_result = do_progress_callback(idx, stats)) < 0)
return progress_cb_result;
/* remove from the list */
git_vector_set(NULL, &idx->deltas, i, NULL);
git__free(delta);
}
/* if none were actually set, we're done */
if (!non_null)
break;
if (!progressed && (fix_thin_pack(idx, stats) < 0)) {
return -1;
}
}
return 0;
}
static int update_header_and_rehash(git_indexer *idx, git_indexer_progress *stats)
{
void *ptr;
size_t chunk = 1024*1024;
off64_t hashed = 0;
git_mwindow *w = NULL;
git_mwindow_file *mwf;
unsigned int left;
mwf = &idx->pack->mwf;
git_hash_init(&idx->trailer);
/* Update the header to include the numer of local objects we injected */
idx->hdr.hdr_entries = htonl(stats->total_objects + stats->local_objects);
if (write_at(idx, &idx->hdr, 0, sizeof(struct git_pack_header)) < 0)
return -1;
/*
* We now use the same technique as before to determine the
* hash. We keep reading up to the end and let
* hash_partially() keep the existing trailer out of the
* calculation.
*/
if (git_mwindow_free_all(mwf) < 0)
return -1;
idx->inbuf_len = 0;
while (hashed < mwf->size) {
ptr = git_mwindow_open(mwf, &w, hashed, chunk, &left);
if (ptr == NULL)
return -1;
hash_partially(idx, ptr, left);
hashed += left;
git_mwindow_close(&w);
}
return 0;
}
int git_indexer_commit(git_indexer *idx, git_indexer_progress *stats)
{
git_mwindow *w = NULL;
unsigned int i, long_offsets = 0, left;
int error;
struct git_pack_idx_header hdr;
git_buf filename = GIT_BUF_INIT;
struct entry *entry;
git_oid trailer_hash, file_hash;
git_filebuf index_file = {0};
void *packfile_trailer;
if (!idx->parsed_header) {
git_error_set(GIT_ERROR_INDEXER, "incomplete pack header");
return -1;
}
/* Test for this before resolve_deltas(), as it plays with idx->off */
if (idx->off + 20 < idx->pack->mwf.size) {
git_error_set(GIT_ERROR_INDEXER, "unexpected data at the end of the pack");
return -1;
}
if (idx->off + 20 > idx->pack->mwf.size) {
git_error_set(GIT_ERROR_INDEXER, "missing trailer at the end of the pack");
return -1;
}
packfile_trailer = git_mwindow_open(&idx->pack->mwf, &w, idx->pack->mwf.size - GIT_OID_RAWSZ, GIT_OID_RAWSZ, &left);
if (packfile_trailer == NULL) {
git_mwindow_close(&w);
goto on_error;
}
/* Compare the packfile trailer as it was sent to us and what we calculated */
git_oid_fromraw(&file_hash, packfile_trailer);
git_mwindow_close(&w);
git_hash_final(&trailer_hash, &idx->trailer);
if (git_oid_cmp(&file_hash, &trailer_hash)) {
git_error_set(GIT_ERROR_INDEXER, "packfile trailer mismatch");
return -1;
}
/* Freeze the number of deltas */
stats->total_deltas = stats->total_objects - stats->indexed_objects;
if ((error = resolve_deltas(idx, stats)) < 0)
return error;
if (stats->indexed_objects != stats->total_objects) {
git_error_set(GIT_ERROR_INDEXER, "early EOF");
return -1;
}
if (stats->local_objects > 0) {
if (update_header_and_rehash(idx, stats) < 0)
return -1;
git_hash_final(&trailer_hash, &idx->trailer);
write_at(idx, &trailer_hash, idx->pack->mwf.size - GIT_OID_RAWSZ, GIT_OID_RAWSZ);
}
/*
* Is the resulting graph fully connected or are we still
* missing some objects? In the second case, we can
* bail out due to an incomplete and thus corrupt
* packfile.
*/
if (git_oidmap_size(idx->expected_oids) > 0) {
git_error_set(GIT_ERROR_INDEXER, "packfile is missing %"PRIuZ" objects",
git_oidmap_size(idx->expected_oids));
return -1;
}
git_vector_sort(&idx->objects);
/* Use the trailer hash as the pack file name to ensure
* files with different contents have different names */
git_oid_cpy(&idx->hash, &trailer_hash);
git_buf_sets(&filename, idx->pack->pack_name);
git_buf_shorten(&filename, strlen("pack"));
git_buf_puts(&filename, "idx");
if (git_buf_oom(&filename))
return -1;
if (git_filebuf_open(&index_file, filename.ptr,
GIT_FILEBUF_HASH_CONTENTS |
(idx->do_fsync ? GIT_FILEBUF_FSYNC : 0),
idx->mode) < 0)
goto on_error;
/* Write out the header */
hdr.idx_signature = htonl(PACK_IDX_SIGNATURE);
hdr.idx_version = htonl(2);
git_filebuf_write(&index_file, &hdr, sizeof(hdr));
/* Write out the fanout table */
for (i = 0; i < 256; ++i) {
uint32_t n = htonl(idx->fanout[i]);
git_filebuf_write(&index_file, &n, sizeof(n));
}
/* Write out the object names (SHA-1 hashes) */
git_vector_foreach(&idx->objects, i, entry) {
git_filebuf_write(&index_file, &entry->oid, sizeof(git_oid));
}
/* Write out the CRC32 values */
git_vector_foreach(&idx->objects, i, entry) {
git_filebuf_write(&index_file, &entry->crc, sizeof(uint32_t));
}
/* Write out the offsets */
git_vector_foreach(&idx->objects, i, entry) {
uint32_t n;
if (entry->offset == UINT32_MAX)
n = htonl(0x80000000 | long_offsets++);
else
n = htonl(entry->offset);
git_filebuf_write(&index_file, &n, sizeof(uint32_t));
}
/* Write out the long offsets */
git_vector_foreach(&idx->objects, i, entry) {
uint32_t split[2];
if (entry->offset != UINT32_MAX)
continue;
split[0] = htonl(entry->offset_long >> 32);
split[1] = htonl(entry->offset_long & 0xffffffff);
git_filebuf_write(&index_file, &split, sizeof(uint32_t) * 2);
}
/* Write out the packfile trailer to the index */
if (git_filebuf_write(&index_file, &trailer_hash, GIT_OID_RAWSZ) < 0)
goto on_error;
/* Write out the hash of the idx */
if (git_filebuf_hash(&trailer_hash, &index_file) < 0)
goto on_error;
git_filebuf_write(&index_file, &trailer_hash, sizeof(git_oid));
/* Figure out what the final name should be */
if (index_path(&filename, idx, ".idx") < 0)
goto on_error;
/* Commit file */
if (git_filebuf_commit_at(&index_file, filename.ptr) < 0)
goto on_error;
if (git_mwindow_free_all(&idx->pack->mwf) < 0)
goto on_error;
#if !defined(NO_MMAP) && defined(GIT_WIN32)
/*
* Some non-Windows remote filesystems fail when truncating files if the
* file permissions change after opening the file (done by p_mkstemp).
*
* Truncation is only needed when mmap is used to undo rounding up to next
* page_size in append_to_pack.
*/
if (p_ftruncate(idx->pack->mwf.fd, idx->pack->mwf.size) < 0) {
git_error_set(GIT_ERROR_OS, "failed to truncate pack file '%s'", idx->pack->pack_name);
return -1;
}
#endif
if (idx->do_fsync && p_fsync(idx->pack->mwf.fd) < 0) {
git_error_set(GIT_ERROR_OS, "failed to fsync packfile");
goto on_error;
}
/* We need to close the descriptor here so Windows doesn't choke on commit_at */
if (p_close(idx->pack->mwf.fd) < 0) {
git_error_set(GIT_ERROR_OS, "failed to close packfile");
goto on_error;
}
idx->pack->mwf.fd = -1;
if (index_path(&filename, idx, ".pack") < 0)
goto on_error;
/* And don't forget to rename the packfile to its new place. */
if (p_rename(idx->pack->pack_name, git_buf_cstr(&filename)) < 0)
goto on_error;
/* And fsync the parent directory if we're asked to. */
if (idx->do_fsync &&
git_futils_fsync_parent(git_buf_cstr(&filename)) < 0)
goto on_error;
idx->pack_committed = 1;
git_buf_dispose(&filename);
return 0;
on_error:
git_mwindow_free_all(&idx->pack->mwf);
git_filebuf_cleanup(&index_file);
git_buf_dispose(&filename);
return -1;
}
void git_indexer_free(git_indexer *idx)
{
const git_oid *key;
git_oid *value;
size_t iter;
if (idx == NULL)
return;
if (idx->have_stream)
git_packfile_stream_dispose(&idx->stream);
git_vector_free_deep(&idx->objects);
if (idx->pack->idx_cache) {
struct git_pack_entry *pentry;
git_oidmap_foreach_value(idx->pack->idx_cache, pentry, {
git__free(pentry);
});
git_oidmap_free(idx->pack->idx_cache);
}
git_vector_free_deep(&idx->deltas);
git_packfile_free(idx->pack, !idx->pack_committed);
iter = 0;
while (git_oidmap_iterate((void **) &value, idx->expected_oids, &iter, &key) == 0)
git__free(value);
git_hash_ctx_cleanup(&idx->trailer);
git_hash_ctx_cleanup(&idx->hash_ctx);
git_buf_dispose(&idx->entry_data);
git_oidmap_free(idx->expected_oids);
git__free(idx);
}
|
0 |
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2
|
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2/src/trace.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 "trace.h"
#include "buffer.h"
#include "runtime.h"
#include "git2/trace.h"
#ifdef GIT_TRACE
struct git_trace_data git_trace__data = {0};
#endif
int git_trace_set(git_trace_level_t level, git_trace_cb callback)
{
#ifdef GIT_TRACE
GIT_ASSERT_ARG(level == 0 || callback != NULL);
git_trace__data.level = level;
git_trace__data.callback = callback;
GIT_MEMORY_BARRIER;
return 0;
#else
GIT_UNUSED(level);
GIT_UNUSED(callback);
git_error_set(GIT_ERROR_INVALID,
"this version of libgit2 was not built with tracing.");
return -1;
#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_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 "diff_driver.h"
#include "git2/attr.h"
#include "common.h"
#include "diff.h"
#include "strmap.h"
#include "map.h"
#include "config.h"
#include "regexp.h"
#include "repository.h"
typedef enum {
DIFF_DRIVER_AUTO = 0,
DIFF_DRIVER_BINARY = 1,
DIFF_DRIVER_TEXT = 2,
DIFF_DRIVER_PATTERNLIST = 3,
} git_diff_driver_t;
typedef struct {
git_regexp re;
int flags;
} git_diff_driver_pattern;
enum {
REG_NEGATE = (1 << 15) /* get out of the way of existing flags */
};
/* data for finding function context for a given file type */
struct git_diff_driver {
git_diff_driver_t type;
uint32_t binary_flags;
uint32_t other_flags;
git_array_t(git_diff_driver_pattern) fn_patterns;
git_regexp word_pattern;
char name[GIT_FLEX_ARRAY];
};
#include "userdiff.h"
struct git_diff_driver_registry {
git_strmap *drivers;
};
#define FORCE_DIFFABLE (GIT_DIFF_FORCE_TEXT | GIT_DIFF_FORCE_BINARY)
static git_diff_driver global_drivers[3] = {
{ DIFF_DRIVER_AUTO, 0, 0, },
{ DIFF_DRIVER_BINARY, GIT_DIFF_FORCE_BINARY, 0 },
{ DIFF_DRIVER_TEXT, GIT_DIFF_FORCE_TEXT, 0 },
};
git_diff_driver_registry *git_diff_driver_registry_new(void)
{
git_diff_driver_registry *reg =
git__calloc(1, sizeof(git_diff_driver_registry));
if (!reg)
return NULL;
if (git_strmap_new(®->drivers) < 0) {
git_diff_driver_registry_free(reg);
return NULL;
}
return reg;
}
void git_diff_driver_registry_free(git_diff_driver_registry *reg)
{
git_diff_driver *drv;
if (!reg)
return;
git_strmap_foreach_value(reg->drivers, drv, git_diff_driver_free(drv));
git_strmap_free(reg->drivers);
git__free(reg);
}
static int diff_driver_add_patterns(
git_diff_driver *drv, const char *regex_str, int regex_flags)
{
int error = 0;
const char *scan, *end;
git_diff_driver_pattern *pat = NULL;
git_buf buf = GIT_BUF_INIT;
for (scan = regex_str; scan; scan = end) {
/* get pattern to fill in */
if ((pat = git_array_alloc(drv->fn_patterns)) == NULL) {
return -1;
}
pat->flags = regex_flags;
if (*scan == '!') {
pat->flags |= REG_NEGATE;
++scan;
}
if ((end = strchr(scan, '\n')) != NULL) {
error = git_buf_set(&buf, scan, end - scan);
end++;
} else {
error = git_buf_sets(&buf, scan);
}
if (error < 0)
break;
if ((error = git_regexp_compile(&pat->re, buf.ptr, regex_flags)) != 0) {
/*
* TODO: issue a warning
*/
}
}
if (error && pat != NULL)
(void)git_array_pop(drv->fn_patterns); /* release last item */
git_buf_dispose(&buf);
/* We want to ignore bad patterns, so return success regardless */
return 0;
}
static int diff_driver_xfuncname(const git_config_entry *entry, void *payload)
{
return diff_driver_add_patterns(payload, entry->value, 0);
}
static int diff_driver_funcname(const git_config_entry *entry, void *payload)
{
return diff_driver_add_patterns(payload, entry->value, 0);
}
static git_diff_driver_registry *git_repository_driver_registry(
git_repository *repo)
{
git_diff_driver_registry *reg = git_atomic_load(repo->diff_drivers), *newreg;
if (reg)
return reg;
newreg = git_diff_driver_registry_new();
if (!newreg) {
git_error_set(GIT_ERROR_REPOSITORY, "unable to create diff driver registry");
return newreg;
}
reg = git_atomic_compare_and_swap(&repo->diff_drivers, NULL, newreg);
if (!reg) {
reg = newreg;
} else {
/* if we race, free losing allocation */
git_diff_driver_registry_free(newreg);
}
return reg;
}
static int diff_driver_alloc(
git_diff_driver **out, size_t *namelen_out, const char *name)
{
git_diff_driver *driver;
size_t driverlen = sizeof(git_diff_driver),
namelen = strlen(name),
alloclen;
GIT_ERROR_CHECK_ALLOC_ADD(&alloclen, driverlen, namelen);
GIT_ERROR_CHECK_ALLOC_ADD(&alloclen, alloclen, 1);
driver = git__calloc(1, alloclen);
GIT_ERROR_CHECK_ALLOC(driver);
memcpy(driver->name, name, namelen);
*out = driver;
if (namelen_out)
*namelen_out = namelen;
return 0;
}
static int git_diff_driver_builtin(
git_diff_driver **out,
git_diff_driver_registry *reg,
const char *driver_name)
{
git_diff_driver_definition *ddef = NULL;
git_diff_driver *drv = NULL;
int error = 0;
size_t idx;
for (idx = 0; idx < ARRAY_SIZE(builtin_defs); ++idx) {
if (!strcasecmp(driver_name, builtin_defs[idx].name)) {
ddef = &builtin_defs[idx];
break;
}
}
if (!ddef)
goto done;
if ((error = diff_driver_alloc(&drv, NULL, ddef->name)) < 0)
goto done;
drv->type = DIFF_DRIVER_PATTERNLIST;
if (ddef->fns &&
(error = diff_driver_add_patterns(
drv, ddef->fns, ddef->flags)) < 0)
goto done;
if (ddef->words &&
(error = git_regexp_compile(&drv->word_pattern, ddef->words, ddef->flags)) < 0)
goto done;
if ((error = git_strmap_set(reg->drivers, drv->name, drv)) < 0)
goto done;
done:
if (error && drv)
git_diff_driver_free(drv);
else
*out = drv;
return error;
}
static int git_diff_driver_load(
git_diff_driver **out, git_repository *repo, const char *driver_name)
{
int error = 0;
git_diff_driver_registry *reg;
git_diff_driver *drv;
size_t namelen;
git_config *cfg = NULL;
git_buf name = GIT_BUF_INIT;
git_config_entry *ce = NULL;
bool found_driver = false;
if ((reg = git_repository_driver_registry(repo)) == NULL)
return -1;
if ((drv = git_strmap_get(reg->drivers, driver_name)) != NULL) {
*out = drv;
return 0;
}
if ((error = diff_driver_alloc(&drv, &namelen, driver_name)) < 0)
goto done;
drv->type = DIFF_DRIVER_AUTO;
/* if you can't read config for repo, just use default driver */
if (git_repository_config_snapshot(&cfg, repo) < 0) {
git_error_clear();
goto done;
}
if ((error = git_buf_printf(&name, "diff.%s.binary", driver_name)) < 0)
goto done;
switch (git_config__get_bool_force(cfg, name.ptr, -1)) {
case true:
/* if diff.<driver>.binary is true, just return the binary driver */
*out = &global_drivers[DIFF_DRIVER_BINARY];
goto done;
case false:
/* if diff.<driver>.binary is false, force binary checks off */
/* but still may have custom function context patterns, etc. */
drv->binary_flags = GIT_DIFF_FORCE_TEXT;
found_driver = true;
break;
default:
/* diff.<driver>.binary unspecified or "auto", so just continue */
break;
}
/* TODO: warn if diff.<name>.command or diff.<name>.textconv are set */
git_buf_truncate(&name, namelen + strlen("diff.."));
if ((error = git_buf_PUTS(&name, "xfuncname")) < 0)
goto done;
if ((error = git_config_get_multivar_foreach(
cfg, name.ptr, NULL, diff_driver_xfuncname, drv)) < 0) {
if (error != GIT_ENOTFOUND)
goto done;
git_error_clear(); /* no diff.<driver>.xfuncname, so just continue */
}
git_buf_truncate(&name, namelen + strlen("diff.."));
if ((error = git_buf_PUTS(&name, "funcname")) < 0)
goto done;
if ((error = git_config_get_multivar_foreach(
cfg, name.ptr, NULL, diff_driver_funcname, drv)) < 0) {
if (error != GIT_ENOTFOUND)
goto done;
git_error_clear(); /* no diff.<driver>.funcname, so just continue */
}
/* if we found any patterns, set driver type to use correct callback */
if (git_array_size(drv->fn_patterns) > 0) {
drv->type = DIFF_DRIVER_PATTERNLIST;
found_driver = true;
}
git_buf_truncate(&name, namelen + strlen("diff.."));
if ((error = git_buf_PUTS(&name, "wordregex")) < 0)
goto done;
if ((error = git_config__lookup_entry(&ce, cfg, name.ptr, false)) < 0)
goto done;
if (!ce || !ce->value)
/* no diff.<driver>.wordregex, so just continue */;
else if (!(error = git_regexp_compile(&drv->word_pattern, ce->value, 0)))
found_driver = true;
else {
/* TODO: warn about bad regex instead of failure */
goto done;
}
/* TODO: look up diff.<driver>.algorithm to turn on minimal / patience
* diff in drv->other_flags
*/
/* if no driver config found at all, fall back on AUTO driver */
if (!found_driver)
goto done;
/* store driver in registry */
if ((error = git_strmap_set(reg->drivers, drv->name, drv)) < 0)
goto done;
*out = drv;
done:
git_config_entry_free(ce);
git_buf_dispose(&name);
git_config_free(cfg);
if (!*out) {
int error2 = git_diff_driver_builtin(out, reg, driver_name);
if (!error)
error = error2;
}
if (drv && drv != *out)
git_diff_driver_free(drv);
return error;
}
int git_diff_driver_lookup(
git_diff_driver **out, git_repository *repo,
git_attr_session *attrsession, const char *path)
{
int error = 0;
const char *values[1], *attrs[] = { "diff" };
GIT_ASSERT_ARG(out);
*out = NULL;
if (!repo || !path || !strlen(path))
/* just use the auto value */;
else if ((error = git_attr_get_many_with_session(values, repo,
attrsession, 0, path, 1, attrs)) < 0)
/* return error below */;
else if (GIT_ATTR_IS_UNSPECIFIED(values[0]))
/* just use the auto value */;
else if (GIT_ATTR_IS_FALSE(values[0]))
*out = &global_drivers[DIFF_DRIVER_BINARY];
else if (GIT_ATTR_IS_TRUE(values[0]))
*out = &global_drivers[DIFF_DRIVER_TEXT];
/* otherwise look for driver information in config and build driver */
else if ((error = git_diff_driver_load(out, repo, values[0])) < 0) {
if (error == GIT_ENOTFOUND) {
error = 0;
git_error_clear();
}
}
if (!*out)
*out = &global_drivers[DIFF_DRIVER_AUTO];
return error;
}
void git_diff_driver_free(git_diff_driver *driver)
{
git_diff_driver_pattern *pat;
if (!driver)
return;
while ((pat = git_array_pop(driver->fn_patterns)) != NULL)
git_regexp_dispose(&pat->re);
git_array_clear(driver->fn_patterns);
git_regexp_dispose(&driver->word_pattern);
git__free(driver);
}
void git_diff_driver_update_options(
uint32_t *option_flags, git_diff_driver *driver)
{
if ((*option_flags & FORCE_DIFFABLE) == 0)
*option_flags |= driver->binary_flags;
*option_flags |= driver->other_flags;
}
int git_diff_driver_content_is_binary(
git_diff_driver *driver, const char *content, size_t content_len)
{
git_buf search = GIT_BUF_INIT;
GIT_UNUSED(driver);
git_buf_attach_notowned(&search, content,
min(content_len, GIT_FILTER_BYTES_TO_CHECK_NUL));
/* TODO: provide encoding / binary detection callbacks that can
* be UTF-8 aware, etc. For now, instead of trying to be smart,
* let's just use the simple NUL-byte detection that core git uses.
*/
/* previously was: if (git_buf_is_binary(&search)) */
if (git_buf_contains_nul(&search))
return 1;
return 0;
}
static int diff_context_line__simple(
git_diff_driver *driver, git_buf *line)
{
char firstch = line->ptr[0];
GIT_UNUSED(driver);
return (git__isalpha(firstch) || firstch == '_' || firstch == '$');
}
static int diff_context_line__pattern_match(
git_diff_driver *driver, git_buf *line)
{
size_t i, maxi = git_array_size(driver->fn_patterns);
git_regmatch pmatch[2];
for (i = 0; i < maxi; ++i) {
git_diff_driver_pattern *pat = git_array_get(driver->fn_patterns, i);
if (!git_regexp_search(&pat->re, line->ptr, 2, pmatch)) {
if (pat->flags & REG_NEGATE)
return false;
/* use pmatch data to trim line data */
i = (pmatch[1].start >= 0) ? 1 : 0;
git_buf_consume(line, git_buf_cstr(line) + pmatch[i].start);
git_buf_truncate(line, pmatch[i].end - pmatch[i].start);
git_buf_rtrim(line);
return true;
}
}
return false;
}
static long diff_context_find(
const char *line,
long line_len,
char *out,
long out_size,
void *payload)
{
git_diff_find_context_payload *ctxt = payload;
if (git_buf_set(&ctxt->line, line, (size_t)line_len) < 0)
return -1;
git_buf_rtrim(&ctxt->line);
if (!ctxt->line.size)
return -1;
if (!ctxt->match_line || !ctxt->match_line(ctxt->driver, &ctxt->line))
return -1;
if (out_size > (long)ctxt->line.size)
out_size = (long)ctxt->line.size;
memcpy(out, ctxt->line.ptr, (size_t)out_size);
return out_size;
}
void git_diff_find_context_init(
git_diff_find_context_fn *findfn_out,
git_diff_find_context_payload *payload_out,
git_diff_driver *driver)
{
*findfn_out = driver ? diff_context_find : NULL;
memset(payload_out, 0, sizeof(*payload_out));
if (driver) {
payload_out->driver = driver;
payload_out->match_line = (driver->type == DIFF_DRIVER_PATTERNLIST) ?
diff_context_line__pattern_match : diff_context_line__simple;
git_buf_init(&payload_out->line, 0);
}
}
void git_diff_find_context_clear(git_diff_find_context_payload *payload)
{
if (payload) {
git_buf_dispose(&payload->line);
payload->driver = 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/status.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 "status.h"
#include "git2.h"
#include "futils.h"
#include "hash.h"
#include "vector.h"
#include "tree.h"
#include "git2/status.h"
#include "repository.h"
#include "ignore.h"
#include "index.h"
#include "wildmatch.h"
#include "git2/diff.h"
#include "diff.h"
#include "diff_generate.h"
static unsigned int index_delta2status(const git_diff_delta *head2idx)
{
git_status_t st = GIT_STATUS_CURRENT;
switch (head2idx->status) {
case GIT_DELTA_ADDED:
case GIT_DELTA_COPIED:
st = GIT_STATUS_INDEX_NEW;
break;
case GIT_DELTA_DELETED:
st = GIT_STATUS_INDEX_DELETED;
break;
case GIT_DELTA_MODIFIED:
st = GIT_STATUS_INDEX_MODIFIED;
break;
case GIT_DELTA_RENAMED:
st = GIT_STATUS_INDEX_RENAMED;
if (!git_oid_equal(&head2idx->old_file.id, &head2idx->new_file.id))
st |= GIT_STATUS_INDEX_MODIFIED;
break;
case GIT_DELTA_TYPECHANGE:
st = GIT_STATUS_INDEX_TYPECHANGE;
break;
case GIT_DELTA_CONFLICTED:
st = GIT_STATUS_CONFLICTED;
break;
default:
break;
}
return st;
}
static unsigned int workdir_delta2status(
git_diff *diff, git_diff_delta *idx2wd)
{
git_status_t st = GIT_STATUS_CURRENT;
switch (idx2wd->status) {
case GIT_DELTA_ADDED:
case GIT_DELTA_COPIED:
case GIT_DELTA_UNTRACKED:
st = GIT_STATUS_WT_NEW;
break;
case GIT_DELTA_UNREADABLE:
st = GIT_STATUS_WT_UNREADABLE;
break;
case GIT_DELTA_DELETED:
st = GIT_STATUS_WT_DELETED;
break;
case GIT_DELTA_MODIFIED:
st = GIT_STATUS_WT_MODIFIED;
break;
case GIT_DELTA_IGNORED:
st = GIT_STATUS_IGNORED;
break;
case GIT_DELTA_RENAMED:
st = GIT_STATUS_WT_RENAMED;
if (!git_oid_equal(&idx2wd->old_file.id, &idx2wd->new_file.id)) {
/* if OIDs don't match, we might need to calculate them now to
* discern between RENAMED vs RENAMED+MODIFED
*/
if (git_oid_is_zero(&idx2wd->old_file.id) &&
diff->old_src == GIT_ITERATOR_WORKDIR &&
!git_diff__oid_for_file(
&idx2wd->old_file.id, diff, idx2wd->old_file.path,
idx2wd->old_file.mode, idx2wd->old_file.size))
idx2wd->old_file.flags |= GIT_DIFF_FLAG_VALID_ID;
if (git_oid_is_zero(&idx2wd->new_file.id) &&
diff->new_src == GIT_ITERATOR_WORKDIR &&
!git_diff__oid_for_file(
&idx2wd->new_file.id, diff, idx2wd->new_file.path,
idx2wd->new_file.mode, idx2wd->new_file.size))
idx2wd->new_file.flags |= GIT_DIFF_FLAG_VALID_ID;
if (!git_oid_equal(&idx2wd->old_file.id, &idx2wd->new_file.id))
st |= GIT_STATUS_WT_MODIFIED;
}
break;
case GIT_DELTA_TYPECHANGE:
st = GIT_STATUS_WT_TYPECHANGE;
break;
case GIT_DELTA_CONFLICTED:
st = GIT_STATUS_CONFLICTED;
break;
default:
break;
}
return st;
}
static bool status_is_included(
git_status_list *status,
git_diff_delta *head2idx,
git_diff_delta *idx2wd)
{
if (!(status->opts.flags & GIT_STATUS_OPT_EXCLUDE_SUBMODULES))
return 1;
/* if excluding submodules and this is a submodule everywhere */
if (head2idx) {
if (head2idx->status != GIT_DELTA_ADDED &&
head2idx->old_file.mode != GIT_FILEMODE_COMMIT)
return 1;
if (head2idx->status != GIT_DELTA_DELETED &&
head2idx->new_file.mode != GIT_FILEMODE_COMMIT)
return 1;
}
if (idx2wd) {
if (idx2wd->status != GIT_DELTA_ADDED &&
idx2wd->old_file.mode != GIT_FILEMODE_COMMIT)
return 1;
if (idx2wd->status != GIT_DELTA_DELETED &&
idx2wd->new_file.mode != GIT_FILEMODE_COMMIT)
return 1;
}
/* only get here if every valid mode is GIT_FILEMODE_COMMIT */
return 0;
}
static git_status_t status_compute(
git_status_list *status,
git_diff_delta *head2idx,
git_diff_delta *idx2wd)
{
git_status_t st = GIT_STATUS_CURRENT;
if (head2idx)
st |= index_delta2status(head2idx);
if (idx2wd)
st |= workdir_delta2status(status->idx2wd, idx2wd);
return st;
}
static int status_collect(
git_diff_delta *head2idx,
git_diff_delta *idx2wd,
void *payload)
{
git_status_list *status = payload;
git_status_entry *status_entry;
if (!status_is_included(status, head2idx, idx2wd))
return 0;
status_entry = git__malloc(sizeof(git_status_entry));
GIT_ERROR_CHECK_ALLOC(status_entry);
status_entry->status = status_compute(status, head2idx, idx2wd);
status_entry->head_to_index = head2idx;
status_entry->index_to_workdir = idx2wd;
return git_vector_insert(&status->paired, status_entry);
}
GIT_INLINE(int) status_entry_cmp_base(
const void *a,
const void *b,
int (*strcomp)(const char *a, const char *b))
{
const git_status_entry *entry_a = a;
const git_status_entry *entry_b = b;
const git_diff_delta *delta_a, *delta_b;
delta_a = entry_a->index_to_workdir ? entry_a->index_to_workdir :
entry_a->head_to_index;
delta_b = entry_b->index_to_workdir ? entry_b->index_to_workdir :
entry_b->head_to_index;
if (!delta_a && delta_b)
return -1;
if (delta_a && !delta_b)
return 1;
if (!delta_a && !delta_b)
return 0;
return strcomp(delta_a->new_file.path, delta_b->new_file.path);
}
static int status_entry_icmp(const void *a, const void *b)
{
return status_entry_cmp_base(a, b, git__strcasecmp);
}
static int status_entry_cmp(const void *a, const void *b)
{
return status_entry_cmp_base(a, b, git__strcmp);
}
static git_status_list *git_status_list_alloc(git_index *index)
{
git_status_list *status = NULL;
int (*entrycmp)(const void *a, const void *b);
if (!(status = git__calloc(1, sizeof(git_status_list))))
return NULL;
entrycmp = index->ignore_case ? status_entry_icmp : status_entry_cmp;
if (git_vector_init(&status->paired, 0, entrycmp) < 0) {
git__free(status);
return NULL;
}
return status;
}
static int status_validate_options(const git_status_options *opts)
{
if (!opts)
return 0;
GIT_ERROR_CHECK_VERSION(opts, GIT_STATUS_OPTIONS_VERSION, "git_status_options");
if (opts->show > GIT_STATUS_SHOW_WORKDIR_ONLY) {
git_error_set(GIT_ERROR_INVALID, "unknown status 'show' option");
return -1;
}
if ((opts->flags & GIT_STATUS_OPT_NO_REFRESH) != 0 &&
(opts->flags & GIT_STATUS_OPT_UPDATE_INDEX) != 0) {
git_error_set(GIT_ERROR_INVALID, "updating index from status "
"is not allowed when index refresh is disabled");
return -1;
}
return 0;
}
int git_status_list_new(
git_status_list **out,
git_repository *repo,
const git_status_options *opts)
{
git_index *index = NULL;
git_status_list *status = NULL;
git_diff_options diffopt = GIT_DIFF_OPTIONS_INIT;
git_diff_find_options findopt = GIT_DIFF_FIND_OPTIONS_INIT;
git_tree *head = NULL;
git_status_show_t show =
opts ? opts->show : GIT_STATUS_SHOW_INDEX_AND_WORKDIR;
int error = 0;
unsigned int flags = opts ? opts->flags : GIT_STATUS_OPT_DEFAULTS;
*out = NULL;
if (status_validate_options(opts) < 0)
return -1;
if ((error = git_repository__ensure_not_bare(repo, "status")) < 0 ||
(error = git_repository_index(&index, repo)) < 0)
return error;
if (opts != NULL && opts->baseline != NULL) {
head = opts->baseline;
} else {
/* if there is no HEAD, that's okay - we'll make an empty iterator */
if ((error = git_repository_head_tree(&head, repo)) < 0) {
if (error != GIT_ENOTFOUND && error != GIT_EUNBORNBRANCH)
goto done;
git_error_clear();
}
}
/* refresh index from disk unless prevented */
if ((flags & GIT_STATUS_OPT_NO_REFRESH) == 0 &&
git_index_read_safely(index) < 0)
git_error_clear();
status = git_status_list_alloc(index);
GIT_ERROR_CHECK_ALLOC(status);
if (opts) {
memcpy(&status->opts, opts, sizeof(git_status_options));
memcpy(&diffopt.pathspec, &opts->pathspec, sizeof(diffopt.pathspec));
}
diffopt.flags = GIT_DIFF_INCLUDE_TYPECHANGE;
findopt.flags = GIT_DIFF_FIND_FOR_UNTRACKED;
if ((flags & GIT_STATUS_OPT_INCLUDE_UNTRACKED) != 0)
diffopt.flags = diffopt.flags | GIT_DIFF_INCLUDE_UNTRACKED;
if ((flags & GIT_STATUS_OPT_INCLUDE_IGNORED) != 0)
diffopt.flags = diffopt.flags | GIT_DIFF_INCLUDE_IGNORED;
if ((flags & GIT_STATUS_OPT_INCLUDE_UNMODIFIED) != 0)
diffopt.flags = diffopt.flags | GIT_DIFF_INCLUDE_UNMODIFIED;
if ((flags & GIT_STATUS_OPT_RECURSE_UNTRACKED_DIRS) != 0)
diffopt.flags = diffopt.flags | GIT_DIFF_RECURSE_UNTRACKED_DIRS;
if ((flags & GIT_STATUS_OPT_DISABLE_PATHSPEC_MATCH) != 0)
diffopt.flags = diffopt.flags | GIT_DIFF_DISABLE_PATHSPEC_MATCH;
if ((flags & GIT_STATUS_OPT_RECURSE_IGNORED_DIRS) != 0)
diffopt.flags = diffopt.flags | GIT_DIFF_RECURSE_IGNORED_DIRS;
if ((flags & GIT_STATUS_OPT_EXCLUDE_SUBMODULES) != 0)
diffopt.flags = diffopt.flags | GIT_DIFF_IGNORE_SUBMODULES;
if ((flags & GIT_STATUS_OPT_UPDATE_INDEX) != 0)
diffopt.flags = diffopt.flags | GIT_DIFF_UPDATE_INDEX;
if ((flags & GIT_STATUS_OPT_INCLUDE_UNREADABLE) != 0)
diffopt.flags = diffopt.flags | GIT_DIFF_INCLUDE_UNREADABLE;
if ((flags & GIT_STATUS_OPT_INCLUDE_UNREADABLE_AS_UNTRACKED) != 0)
diffopt.flags = diffopt.flags | GIT_DIFF_INCLUDE_UNREADABLE_AS_UNTRACKED;
if ((flags & GIT_STATUS_OPT_RENAMES_FROM_REWRITES) != 0)
findopt.flags = findopt.flags |
GIT_DIFF_FIND_AND_BREAK_REWRITES |
GIT_DIFF_FIND_RENAMES_FROM_REWRITES |
GIT_DIFF_BREAK_REWRITES_FOR_RENAMES_ONLY;
if (show != GIT_STATUS_SHOW_WORKDIR_ONLY) {
if ((error = git_diff_tree_to_index(
&status->head2idx, repo, head, index, &diffopt)) < 0)
goto done;
if ((flags & GIT_STATUS_OPT_RENAMES_HEAD_TO_INDEX) != 0 &&
(error = git_diff_find_similar(status->head2idx, &findopt)) < 0)
goto done;
}
if (show != GIT_STATUS_SHOW_INDEX_ONLY) {
if ((error = git_diff_index_to_workdir(
&status->idx2wd, repo, index, &diffopt)) < 0) {
goto done;
}
if ((flags & GIT_STATUS_OPT_RENAMES_INDEX_TO_WORKDIR) != 0 &&
(error = git_diff_find_similar(status->idx2wd, &findopt)) < 0)
goto done;
}
error = git_diff__paired_foreach(
status->head2idx, status->idx2wd, status_collect, status);
if (error < 0)
goto done;
if (flags & GIT_STATUS_OPT_SORT_CASE_SENSITIVELY)
git_vector_set_cmp(&status->paired, status_entry_cmp);
if (flags & GIT_STATUS_OPT_SORT_CASE_INSENSITIVELY)
git_vector_set_cmp(&status->paired, status_entry_icmp);
if ((flags &
(GIT_STATUS_OPT_RENAMES_HEAD_TO_INDEX |
GIT_STATUS_OPT_RENAMES_INDEX_TO_WORKDIR |
GIT_STATUS_OPT_SORT_CASE_SENSITIVELY |
GIT_STATUS_OPT_SORT_CASE_INSENSITIVELY)) != 0)
git_vector_sort(&status->paired);
done:
if (error < 0) {
git_status_list_free(status);
status = NULL;
}
*out = status;
if (opts == NULL || opts->baseline != head)
git_tree_free(head);
git_index_free(index);
return error;
}
size_t git_status_list_entrycount(git_status_list *status)
{
GIT_ASSERT_ARG_WITH_RETVAL(status, 0);
return status->paired.length;
}
const git_status_entry *git_status_byindex(git_status_list *status, size_t i)
{
GIT_ASSERT_ARG_WITH_RETVAL(status, NULL);
return git_vector_get(&status->paired, i);
}
void git_status_list_free(git_status_list *status)
{
if (status == NULL)
return;
git_diff_free(status->head2idx);
git_diff_free(status->idx2wd);
git_vector_free_deep(&status->paired);
git__memzero(status, sizeof(*status));
git__free(status);
}
int git_status_foreach_ext(
git_repository *repo,
const git_status_options *opts,
git_status_cb cb,
void *payload)
{
git_status_list *status;
const git_status_entry *status_entry;
size_t i;
int error = 0;
if ((error = git_status_list_new(&status, repo, opts)) < 0) {
return error;
}
git_vector_foreach(&status->paired, i, status_entry) {
const char *path = status_entry->head_to_index ?
status_entry->head_to_index->old_file.path :
status_entry->index_to_workdir->old_file.path;
if ((error = cb(path, status_entry->status, payload)) != 0) {
git_error_set_after_callback(error);
break;
}
}
git_status_list_free(status);
return error;
}
int git_status_foreach(git_repository *repo, git_status_cb cb, void *payload)
{
return git_status_foreach_ext(repo, NULL, cb, payload);
}
struct status_file_info {
char *expected;
unsigned int count;
unsigned int status;
int wildmatch_flags;
int ambiguous;
};
static int get_one_status(const char *path, unsigned int status, void *data)
{
struct status_file_info *sfi = data;
int (*strcomp)(const char *a, const char *b);
sfi->count++;
sfi->status = status;
strcomp = (sfi->wildmatch_flags & WM_CASEFOLD) ? git__strcasecmp : git__strcmp;
if (sfi->count > 1 ||
(strcomp(sfi->expected, path) != 0 &&
wildmatch(sfi->expected, path, sfi->wildmatch_flags) != 0))
{
sfi->ambiguous = true;
return GIT_EAMBIGUOUS; /* git_error_set will be done by caller */
}
return 0;
}
int git_status_file(
unsigned int *status_flags,
git_repository *repo,
const char *path)
{
int error;
git_status_options opts = GIT_STATUS_OPTIONS_INIT;
struct status_file_info sfi = {0};
git_index *index;
GIT_ASSERT_ARG(status_flags);
GIT_ASSERT_ARG(repo);
GIT_ASSERT_ARG(path);
if ((error = git_repository_index__weakptr(&index, repo)) < 0)
return error;
if ((sfi.expected = git__strdup(path)) == NULL)
return -1;
if (index->ignore_case)
sfi.wildmatch_flags = WM_CASEFOLD;
opts.show = GIT_STATUS_SHOW_INDEX_AND_WORKDIR;
opts.flags = GIT_STATUS_OPT_INCLUDE_IGNORED |
GIT_STATUS_OPT_RECURSE_IGNORED_DIRS |
GIT_STATUS_OPT_INCLUDE_UNTRACKED |
GIT_STATUS_OPT_RECURSE_UNTRACKED_DIRS |
GIT_STATUS_OPT_INCLUDE_UNMODIFIED |
GIT_STATUS_OPT_DISABLE_PATHSPEC_MATCH;
opts.pathspec.count = 1;
opts.pathspec.strings = &sfi.expected;
error = git_status_foreach_ext(repo, &opts, get_one_status, &sfi);
if (error < 0 && sfi.ambiguous) {
git_error_set(GIT_ERROR_INVALID,
"ambiguous path '%s' given to git_status_file", sfi.expected);
error = GIT_EAMBIGUOUS;
}
if (!error && !sfi.count) {
git_error_set(GIT_ERROR_INVALID,
"attempt to get status of nonexistent file '%s'", path);
error = GIT_ENOTFOUND;
}
*status_flags = sfi.status;
git__free(sfi.expected);
return error;
}
int git_status_should_ignore(
int *ignored,
git_repository *repo,
const char *path)
{
return git_ignore_path_is_ignored(ignored, repo, path);
}
int git_status_options_init(git_status_options *opts, unsigned int version)
{
GIT_INIT_STRUCTURE_FROM_TEMPLATE(
opts, version, git_status_options, GIT_STATUS_OPTIONS_INIT);
return 0;
}
#ifndef GIT_DEPRECATE_HARD
int git_status_init_options(git_status_options *opts, unsigned int version)
{
return git_status_options_init(opts, version);
}
#endif
int git_status_list_get_perfdata(
git_diff_perfdata *out, const git_status_list *status)
{
GIT_ASSERT_ARG(out);
GIT_ERROR_CHECK_VERSION(out, GIT_DIFF_PERFDATA_VERSION, "git_diff_perfdata");
out->stat_calls = 0;
out->oid_calculations = 0;
if (status->head2idx) {
out->stat_calls += status->head2idx->perf.stat_calls;
out->oid_calculations += status->head2idx->perf.oid_calculations;
}
if (status->idx2wd) {
out->stat_calls += status->idx2wd->perf.stat_calls;
out->oid_calculations += status->idx2wd->perf.oid_calculations;
}
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/proxy.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_proxy_h__
#define INCLUDE_proxy_h__
#include "common.h"
#include "git2/proxy.h"
extern int git_proxy_options_dup(git_proxy_options *tgt, const git_proxy_options *src);
extern void git_proxy_options_clear(git_proxy_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/commit_list.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 "commit_list.h"
#include "revwalk.h"
#include "pool.h"
#include "odb.h"
#include "commit.h"
int git_commit_list_generation_cmp(const void *a, const void *b)
{
uint32_t generation_a = ((git_commit_list_node *) a)->generation;
uint32_t generation_b = ((git_commit_list_node *) b)->generation;
if (!generation_a || !generation_b) {
/* Fall back to comparing by timestamps if at least one commit lacks a generation. */
return git_commit_list_time_cmp(a, b);
}
if (generation_a < generation_b)
return 1;
if (generation_a > generation_b)
return -1;
return 0;
}
int git_commit_list_time_cmp(const void *a, const void *b)
{
int64_t time_a = ((git_commit_list_node *) a)->time;
int64_t time_b = ((git_commit_list_node *) b)->time;
if (time_a < time_b)
return 1;
if (time_a > time_b)
return -1;
return 0;
}
git_commit_list *git_commit_list_insert(git_commit_list_node *item, git_commit_list **list_p)
{
git_commit_list *new_list = git__malloc(sizeof(git_commit_list));
if (new_list != NULL) {
new_list->item = item;
new_list->next = *list_p;
}
*list_p = new_list;
return new_list;
}
git_commit_list *git_commit_list_insert_by_date(git_commit_list_node *item, git_commit_list **list_p)
{
git_commit_list **pp = list_p;
git_commit_list *p;
while ((p = *pp) != NULL) {
if (git_commit_list_time_cmp(p->item, item) > 0)
break;
pp = &p->next;
}
return git_commit_list_insert(item, pp);
}
git_commit_list_node *git_commit_list_alloc_node(git_revwalk *walk)
{
return (git_commit_list_node *)git_pool_mallocz(&walk->commit_pool, 1);
}
static git_commit_list_node **alloc_parents(
git_revwalk *walk, git_commit_list_node *commit, size_t n_parents)
{
size_t bytes;
if (n_parents <= PARENTS_PER_COMMIT)
return (git_commit_list_node **)((char *)commit + sizeof(git_commit_list_node));
if (git__multiply_sizet_overflow(&bytes, n_parents, sizeof(git_commit_list_node *)))
return NULL;
return (git_commit_list_node **)git_pool_malloc(&walk->commit_pool, bytes);
}
void git_commit_list_free(git_commit_list **list_p)
{
git_commit_list *list = *list_p;
if (list == NULL)
return;
while (list) {
git_commit_list *temp = list;
list = temp->next;
git__free(temp);
}
*list_p = NULL;
}
git_commit_list_node *git_commit_list_pop(git_commit_list **stack)
{
git_commit_list *top = *stack;
git_commit_list_node *item = top ? top->item : NULL;
if (top) {
*stack = top->next;
git__free(top);
}
return item;
}
static int commit_quick_parse(
git_revwalk *walk,
git_commit_list_node *node,
git_odb_object *obj)
{
git_oid *parent_oid;
git_commit *commit;
int error;
size_t i;
commit = git__calloc(1, sizeof(*commit));
GIT_ERROR_CHECK_ALLOC(commit);
commit->object.repo = walk->repo;
if ((error = git_commit__parse_ext(commit, obj, GIT_COMMIT_PARSE_QUICK)) < 0) {
git__free(commit);
return error;
}
if (!git__is_uint16(git_array_size(commit->parent_ids))) {
git__free(commit);
git_error_set(GIT_ERROR_INVALID, "commit has more than 2^16 parents");
return -1;
}
node->generation = 0;
node->time = commit->committer->when.time;
node->out_degree = (uint16_t) git_array_size(commit->parent_ids);
node->parents = alloc_parents(walk, node, node->out_degree);
GIT_ERROR_CHECK_ALLOC(node->parents);
git_array_foreach(commit->parent_ids, i, parent_oid) {
node->parents[i] = git_revwalk__commit_lookup(walk, parent_oid);
}
git_commit__free(commit);
node->parsed = 1;
return 0;
}
int git_commit_list_parse(git_revwalk *walk, git_commit_list_node *commit)
{
git_odb_object *obj;
git_commit_graph_file *cgraph_file = NULL;
int error;
if (commit->parsed)
return 0;
/* Let's try to use the commit graph first. */
git_odb__get_commit_graph_file(&cgraph_file, walk->odb);
if (cgraph_file) {
git_commit_graph_entry e;
error = git_commit_graph_entry_find(&e, cgraph_file, &commit->oid, GIT_OID_RAWSZ);
if (error == 0 && git__is_uint16(e.parent_count)) {
size_t i;
commit->generation = (uint32_t)e.generation;
commit->time = e.commit_time;
commit->out_degree = (uint16_t)e.parent_count;
commit->parents = alloc_parents(walk, commit, commit->out_degree);
GIT_ERROR_CHECK_ALLOC(commit->parents);
for (i = 0; i < commit->out_degree; ++i) {
git_commit_graph_entry parent;
error = git_commit_graph_entry_parent(&parent, cgraph_file, &e, i);
if (error < 0)
return error;
commit->parents[i] = git_revwalk__commit_lookup(walk, &parent.sha1);
}
commit->parsed = 1;
return 0;
}
}
if ((error = git_odb_read(&obj, walk->odb, &commit->oid)) < 0)
return error;
if (obj->cached.type != GIT_OBJECT_COMMIT) {
git_error_set(GIT_ERROR_INVALID, "object is no commit object");
error = -1;
} else
error = commit_quick_parse(walk, commit, obj);
git_odb_object_free(obj);
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_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 "diff_file.h"
#include "git2/blob.h"
#include "git2/submodule.h"
#include "diff.h"
#include "diff_generate.h"
#include "odb.h"
#include "futils.h"
#include "filter.h"
#define DIFF_MAX_FILESIZE 0x20000000
static bool diff_file_content_binary_by_size(git_diff_file_content *fc)
{
/* if we have diff opts, check max_size vs file size */
if ((fc->file->flags & DIFF_FLAGS_KNOWN_BINARY) == 0 &&
fc->opts_max_size > 0 &&
fc->file->size > fc->opts_max_size)
fc->file->flags |= GIT_DIFF_FLAG_BINARY;
return ((fc->file->flags & GIT_DIFF_FLAG_BINARY) != 0);
}
static void diff_file_content_binary_by_content(git_diff_file_content *fc)
{
if ((fc->file->flags & DIFF_FLAGS_KNOWN_BINARY) != 0)
return;
switch (git_diff_driver_content_is_binary(
fc->driver, fc->map.data, fc->map.len)) {
case 0: fc->file->flags |= GIT_DIFF_FLAG_NOT_BINARY; break;
case 1: fc->file->flags |= GIT_DIFF_FLAG_BINARY; break;
default: break;
}
}
static int diff_file_content_init_common(
git_diff_file_content *fc, const git_diff_options *opts)
{
fc->opts_flags = opts ? opts->flags : GIT_DIFF_NORMAL;
if (opts && opts->max_size >= 0)
fc->opts_max_size = opts->max_size ?
opts->max_size : DIFF_MAX_FILESIZE;
if (fc->src == GIT_ITERATOR_EMPTY)
fc->src = GIT_ITERATOR_TREE;
if (!fc->driver &&
git_diff_driver_lookup(&fc->driver, fc->repo,
NULL, fc->file->path) < 0)
return -1;
/* give driver a chance to modify options */
git_diff_driver_update_options(&fc->opts_flags, fc->driver);
/* make sure file is conceivable mmap-able */
if ((size_t)fc->file->size != fc->file->size)
fc->file->flags |= GIT_DIFF_FLAG_BINARY;
/* check if user is forcing text diff the file */
else if (fc->opts_flags & GIT_DIFF_FORCE_TEXT) {
fc->file->flags &= ~GIT_DIFF_FLAG_BINARY;
fc->file->flags |= GIT_DIFF_FLAG_NOT_BINARY;
}
/* check if user is forcing binary diff the file */
else if (fc->opts_flags & GIT_DIFF_FORCE_BINARY) {
fc->file->flags &= ~GIT_DIFF_FLAG_NOT_BINARY;
fc->file->flags |= GIT_DIFF_FLAG_BINARY;
}
diff_file_content_binary_by_size(fc);
if ((fc->flags & GIT_DIFF_FLAG__NO_DATA) != 0) {
fc->flags |= GIT_DIFF_FLAG__LOADED;
fc->map.len = 0;
fc->map.data = "";
}
if ((fc->flags & GIT_DIFF_FLAG__LOADED) != 0)
diff_file_content_binary_by_content(fc);
return 0;
}
int git_diff_file_content__init_from_diff(
git_diff_file_content *fc,
git_diff *diff,
git_diff_delta *delta,
bool use_old)
{
bool has_data = true;
memset(fc, 0, sizeof(*fc));
fc->repo = diff->repo;
fc->file = use_old ? &delta->old_file : &delta->new_file;
fc->src = use_old ? diff->old_src : diff->new_src;
if (git_diff_driver_lookup(&fc->driver, fc->repo,
&diff->attrsession, fc->file->path) < 0)
return -1;
switch (delta->status) {
case GIT_DELTA_ADDED:
has_data = !use_old; break;
case GIT_DELTA_DELETED:
has_data = use_old; break;
case GIT_DELTA_UNTRACKED:
has_data = !use_old &&
(diff->opts.flags & GIT_DIFF_SHOW_UNTRACKED_CONTENT) != 0;
break;
case GIT_DELTA_UNREADABLE:
case GIT_DELTA_MODIFIED:
case GIT_DELTA_COPIED:
case GIT_DELTA_RENAMED:
break;
default:
has_data = false;
break;
}
if (!has_data)
fc->flags |= GIT_DIFF_FLAG__NO_DATA;
return diff_file_content_init_common(fc, &diff->opts);
}
int git_diff_file_content__init_from_src(
git_diff_file_content *fc,
git_repository *repo,
const git_diff_options *opts,
const git_diff_file_content_src *src,
git_diff_file *as_file)
{
memset(fc, 0, sizeof(*fc));
fc->repo = repo;
fc->file = as_file;
if (!src->blob && !src->buf) {
fc->flags |= GIT_DIFF_FLAG__NO_DATA;
} else {
fc->flags |= GIT_DIFF_FLAG__LOADED;
fc->file->flags |= GIT_DIFF_FLAG_VALID_ID;
fc->file->mode = GIT_FILEMODE_BLOB;
if (src->blob) {
git_blob_dup((git_blob **)&fc->blob, (git_blob *) src->blob);
fc->file->size = git_blob_rawsize(src->blob);
git_oid_cpy(&fc->file->id, git_blob_id(src->blob));
fc->file->id_abbrev = GIT_OID_HEXSZ;
fc->map.len = (size_t)fc->file->size;
fc->map.data = (char *)git_blob_rawcontent(src->blob);
fc->flags |= GIT_DIFF_FLAG__FREE_BLOB;
} else {
int error;
if ((error = git_odb_hash(&fc->file->id, src->buf, src->buflen, GIT_OBJECT_BLOB)) < 0)
return error;
fc->file->size = src->buflen;
fc->file->id_abbrev = GIT_OID_HEXSZ;
fc->map.len = src->buflen;
fc->map.data = (char *)src->buf;
}
}
return diff_file_content_init_common(fc, opts);
}
static int diff_file_content_commit_to_str(
git_diff_file_content *fc, bool check_status)
{
char oid[GIT_OID_HEXSZ+1];
git_buf content = GIT_BUF_INIT;
const char *status = "";
if (check_status) {
int error = 0;
git_submodule *sm = NULL;
unsigned int sm_status = 0;
const git_oid *sm_head;
if ((error = git_submodule_lookup(&sm, fc->repo, fc->file->path)) < 0) {
/* GIT_EEXISTS means a "submodule" that has not been git added */
if (error == GIT_EEXISTS) {
git_error_clear();
error = 0;
}
return error;
}
if ((error = git_submodule_status(&sm_status, fc->repo, fc->file->path, GIT_SUBMODULE_IGNORE_UNSPECIFIED)) < 0) {
git_submodule_free(sm);
return error;
}
/* update OID if we didn't have it previously */
if ((fc->file->flags & GIT_DIFF_FLAG_VALID_ID) == 0 &&
((sm_head = git_submodule_wd_id(sm)) != NULL ||
(sm_head = git_submodule_head_id(sm)) != NULL))
{
git_oid_cpy(&fc->file->id, sm_head);
fc->file->flags |= GIT_DIFF_FLAG_VALID_ID;
}
if (GIT_SUBMODULE_STATUS_IS_WD_DIRTY(sm_status))
status = "-dirty";
git_submodule_free(sm);
}
git_oid_tostr(oid, sizeof(oid), &fc->file->id);
if (git_buf_printf(&content, "Subproject commit %s%s\n", oid, status) < 0)
return -1;
fc->map.len = git_buf_len(&content);
fc->map.data = git_buf_detach(&content);
fc->flags |= GIT_DIFF_FLAG__FREE_DATA;
return 0;
}
static int diff_file_content_load_blob(
git_diff_file_content *fc,
git_diff_options *opts)
{
int error = 0;
git_odb_object *odb_obj = NULL;
if (git_oid_is_zero(&fc->file->id))
return 0;
if (fc->file->mode == GIT_FILEMODE_COMMIT)
return diff_file_content_commit_to_str(fc, false);
/* if we don't know size, try to peek at object header first */
if (!fc->file->size) {
if ((error = git_diff_file__resolve_zero_size(
fc->file, &odb_obj, fc->repo)) < 0)
return error;
}
if ((opts->flags & GIT_DIFF_SHOW_BINARY) == 0 &&
diff_file_content_binary_by_size(fc))
return 0;
if (odb_obj != NULL) {
error = git_object__from_odb_object(
(git_object **)&fc->blob, fc->repo, odb_obj, GIT_OBJECT_BLOB);
git_odb_object_free(odb_obj);
} else {
error = git_blob_lookup(
(git_blob **)&fc->blob, fc->repo, &fc->file->id);
}
if (!error) {
fc->flags |= GIT_DIFF_FLAG__FREE_BLOB;
fc->map.data = (void *)git_blob_rawcontent(fc->blob);
fc->map.len = (size_t)git_blob_rawsize(fc->blob);
}
return error;
}
static int diff_file_content_load_workdir_symlink_fake(
git_diff_file_content *fc, git_buf *path)
{
git_buf target = GIT_BUF_INIT;
int error;
if ((error = git_futils_readbuffer(&target, path->ptr)) < 0)
return error;
fc->map.len = git_buf_len(&target);
fc->map.data = git_buf_detach(&target);
fc->flags |= GIT_DIFF_FLAG__FREE_DATA;
git_buf_dispose(&target);
return error;
}
static int diff_file_content_load_workdir_symlink(
git_diff_file_content *fc, git_buf *path)
{
ssize_t alloc_len, read_len;
int symlink_supported, error;
if ((error = git_repository__configmap_lookup(
&symlink_supported, fc->repo, GIT_CONFIGMAP_SYMLINKS)) < 0)
return -1;
if (!symlink_supported)
return diff_file_content_load_workdir_symlink_fake(fc, path);
/* link path on disk could be UTF-16, so prepare a buffer that is
* big enough to handle some UTF-8 data expansion
*/
alloc_len = (ssize_t)(fc->file->size * 2) + 1;
fc->map.data = git__calloc(alloc_len, sizeof(char));
GIT_ERROR_CHECK_ALLOC(fc->map.data);
fc->flags |= GIT_DIFF_FLAG__FREE_DATA;
read_len = p_readlink(git_buf_cstr(path), fc->map.data, alloc_len);
if (read_len < 0) {
git_error_set(GIT_ERROR_OS, "failed to read symlink '%s'", fc->file->path);
return -1;
}
fc->map.len = read_len;
return 0;
}
static int diff_file_content_load_workdir_file(
git_diff_file_content *fc,
git_buf *path,
git_diff_options *diff_opts)
{
int error = 0;
git_filter_list *fl = NULL;
git_file fd = git_futils_open_ro(git_buf_cstr(path));
git_buf raw = GIT_BUF_INIT;
if (fd < 0)
return fd;
if (!fc->file->size)
error = git_futils_filesize(&fc->file->size, fd);
if (error < 0 || !fc->file->size)
goto cleanup;
if ((diff_opts->flags & GIT_DIFF_SHOW_BINARY) == 0 &&
diff_file_content_binary_by_size(fc))
goto cleanup;
if ((error = git_filter_list_load(
&fl, fc->repo, NULL, fc->file->path,
GIT_FILTER_TO_ODB, GIT_FILTER_ALLOW_UNSAFE)) < 0)
goto cleanup;
/* if there are no filters, try to mmap the file */
if (fl == NULL) {
if (!(error = git_futils_mmap_ro(
&fc->map, fd, 0, (size_t)fc->file->size))) {
fc->flags |= GIT_DIFF_FLAG__UNMAP_DATA;
goto cleanup;
}
/* if mmap failed, fall through to try readbuffer below */
git_error_clear();
}
if (!(error = git_futils_readbuffer_fd(&raw, fd, (size_t)fc->file->size))) {
git_buf out = GIT_BUF_INIT;
error = git_filter_list__convert_buf(&out, fl, &raw);
if (!error) {
fc->map.len = out.size;
fc->map.data = out.ptr;
fc->flags |= GIT_DIFF_FLAG__FREE_DATA;
}
}
cleanup:
git_filter_list_free(fl);
p_close(fd);
return error;
}
static int diff_file_content_load_workdir(
git_diff_file_content *fc,
git_diff_options *diff_opts)
{
int error = 0;
git_buf path = GIT_BUF_INIT;
if (fc->file->mode == GIT_FILEMODE_COMMIT)
return diff_file_content_commit_to_str(fc, true);
if (fc->file->mode == GIT_FILEMODE_TREE)
return 0;
if (git_repository_workdir_path(&path, fc->repo, fc->file->path) < 0)
return -1;
if (S_ISLNK(fc->file->mode))
error = diff_file_content_load_workdir_symlink(fc, &path);
else
error = diff_file_content_load_workdir_file(fc, &path, diff_opts);
/* once data is loaded, update OID if we didn't have it previously */
if (!error && (fc->file->flags & GIT_DIFF_FLAG_VALID_ID) == 0) {
error = git_odb_hash(
&fc->file->id, fc->map.data, fc->map.len, GIT_OBJECT_BLOB);
fc->file->flags |= GIT_DIFF_FLAG_VALID_ID;
}
git_buf_dispose(&path);
return error;
}
int git_diff_file_content__load(
git_diff_file_content *fc,
git_diff_options *diff_opts)
{
int error = 0;
if ((fc->flags & GIT_DIFF_FLAG__LOADED) != 0)
return 0;
if ((fc->file->flags & GIT_DIFF_FLAG_BINARY) != 0 &&
(diff_opts->flags & GIT_DIFF_SHOW_BINARY) == 0)
return 0;
if (fc->src == GIT_ITERATOR_WORKDIR)
error = diff_file_content_load_workdir(fc, diff_opts);
else
error = diff_file_content_load_blob(fc, diff_opts);
if (error)
return error;
fc->flags |= GIT_DIFF_FLAG__LOADED;
diff_file_content_binary_by_content(fc);
return 0;
}
void git_diff_file_content__unload(git_diff_file_content *fc)
{
if ((fc->flags & GIT_DIFF_FLAG__LOADED) == 0)
return;
if (fc->flags & GIT_DIFF_FLAG__FREE_DATA) {
git__free(fc->map.data);
fc->map.data = "";
fc->map.len = 0;
fc->flags &= ~GIT_DIFF_FLAG__FREE_DATA;
}
else if (fc->flags & GIT_DIFF_FLAG__UNMAP_DATA) {
git_futils_mmap_free(&fc->map);
fc->map.data = "";
fc->map.len = 0;
fc->flags &= ~GIT_DIFF_FLAG__UNMAP_DATA;
}
if (fc->flags & GIT_DIFF_FLAG__FREE_BLOB) {
git_blob_free((git_blob *)fc->blob);
fc->blob = NULL;
fc->flags &= ~GIT_DIFF_FLAG__FREE_BLOB;
}
fc->flags &= ~GIT_DIFF_FLAG__LOADED;
}
void git_diff_file_content__clear(git_diff_file_content *fc)
{
git_diff_file_content__unload(fc);
/* for now, nothing else to do */
}
|
0 |
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2
|
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2/src/stash.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 "commit.h"
#include "message.h"
#include "tree.h"
#include "reflog.h"
#include "blob.h"
#include "git2/diff.h"
#include "git2/stash.h"
#include "git2/status.h"
#include "git2/checkout.h"
#include "git2/index.h"
#include "git2/transaction.h"
#include "git2/merge.h"
#include "index.h"
#include "signature.h"
#include "iterator.h"
#include "merge.h"
#include "diff.h"
#include "diff_generate.h"
static int create_error(int error, const char *msg)
{
git_error_set(GIT_ERROR_STASH, "cannot stash changes - %s", msg);
return error;
}
static int retrieve_head(git_reference **out, git_repository *repo)
{
int error = git_repository_head(out, repo);
if (error == GIT_EUNBORNBRANCH)
return create_error(error, "you do not have the initial commit yet.");
return error;
}
static int append_abbreviated_oid(git_buf *out, const git_oid *b_commit)
{
char *formatted_oid;
formatted_oid = git_oid_allocfmt(b_commit);
GIT_ERROR_CHECK_ALLOC(formatted_oid);
git_buf_put(out, formatted_oid, 7);
git__free(formatted_oid);
return git_buf_oom(out) ? -1 : 0;
}
static int append_commit_description(git_buf *out, git_commit *commit)
{
const char *summary = git_commit_summary(commit);
GIT_ERROR_CHECK_ALLOC(summary);
if (append_abbreviated_oid(out, git_commit_id(commit)) < 0)
return -1;
git_buf_putc(out, ' ');
git_buf_puts(out, summary);
git_buf_putc(out, '\n');
return git_buf_oom(out) ? -1 : 0;
}
static int retrieve_base_commit_and_message(
git_commit **b_commit,
git_buf *stash_message,
git_repository *repo)
{
git_reference *head = NULL;
int error;
if ((error = retrieve_head(&head, repo)) < 0)
return error;
if (strcmp("HEAD", git_reference_name(head)) == 0)
error = git_buf_puts(stash_message, "(no branch): ");
else
error = git_buf_printf(
stash_message,
"%s: ",
git_reference_name(head) + strlen(GIT_REFS_HEADS_DIR));
if (error < 0)
goto cleanup;
if ((error = git_commit_lookup(
b_commit, repo, git_reference_target(head))) < 0)
goto cleanup;
if ((error = append_commit_description(stash_message, *b_commit)) < 0)
goto cleanup;
cleanup:
git_reference_free(head);
return error;
}
static int build_tree_from_index(
git_tree **out,
git_repository *repo,
git_index *index)
{
int error;
git_oid i_tree_oid;
if ((error = git_index_write_tree_to(&i_tree_oid, index, repo)) < 0)
return error;
return git_tree_lookup(out, repo, &i_tree_oid);
}
static int commit_index(
git_commit **i_commit,
git_repository *repo,
git_index *index,
const git_signature *stasher,
const char *message,
const git_commit *parent)
{
git_tree *i_tree = NULL;
git_oid i_commit_oid;
git_buf msg = GIT_BUF_INIT;
int error;
if ((error = build_tree_from_index(&i_tree, repo, index)) < 0)
goto cleanup;
if ((error = git_buf_printf(&msg, "index on %s\n", message)) < 0)
goto cleanup;
if ((error = git_commit_create(
&i_commit_oid,
git_index_owner(index),
NULL,
stasher,
stasher,
NULL,
git_buf_cstr(&msg),
i_tree,
1,
&parent)) < 0)
goto cleanup;
error = git_commit_lookup(i_commit, git_index_owner(index), &i_commit_oid);
cleanup:
git_tree_free(i_tree);
git_buf_dispose(&msg);
return error;
}
struct stash_update_rules {
bool include_changed;
bool include_untracked;
bool include_ignored;
};
/*
* Similar to git_index_add_bypath but able to operate on any
* index without making assumptions about the repository's index
*/
static int stash_to_index(
git_repository *repo,
git_index *index,
const char *path)
{
git_index *repo_index = NULL;
git_index_entry entry = {{0}};
struct stat st;
int error;
if (!git_repository_is_bare(repo) &&
(error = git_repository_index__weakptr(&repo_index, repo)) < 0)
return error;
if ((error = git_blob__create_from_paths(
&entry.id, &st, repo, NULL, path, 0, true)) < 0)
return error;
git_index_entry__init_from_stat(&entry, &st,
(repo_index == NULL || !repo_index->distrust_filemode));
entry.path = path;
return git_index_add(index, &entry);
}
static int stash_update_index_from_diff(
git_repository *repo,
git_index *index,
const git_diff *diff,
struct stash_update_rules *data)
{
int error = 0;
size_t d, max_d = git_diff_num_deltas(diff);
for (d = 0; !error && d < max_d; ++d) {
const char *add_path = NULL;
const git_diff_delta *delta = git_diff_get_delta(diff, d);
switch (delta->status) {
case GIT_DELTA_IGNORED:
if (data->include_ignored)
add_path = delta->new_file.path;
break;
case GIT_DELTA_UNTRACKED:
if (data->include_untracked &&
delta->new_file.mode != GIT_FILEMODE_TREE)
add_path = delta->new_file.path;
break;
case GIT_DELTA_ADDED:
case GIT_DELTA_MODIFIED:
if (data->include_changed)
add_path = delta->new_file.path;
break;
case GIT_DELTA_DELETED:
if (data->include_changed &&
!git_index_find(NULL, index, delta->old_file.path))
error = git_index_remove(index, delta->old_file.path, 0);
break;
default:
/* Unimplemented */
git_error_set(
GIT_ERROR_INVALID,
"cannot update index. Unimplemented status (%d)",
delta->status);
return -1;
}
if (add_path != NULL)
error = stash_to_index(repo, index, add_path);
}
return error;
}
static int build_untracked_tree(
git_tree **tree_out,
git_repository *repo,
git_commit *i_commit,
uint32_t flags)
{
git_index *i_index = NULL;
git_tree *i_tree = NULL;
git_diff *diff = NULL;
git_diff_options opts = GIT_DIFF_OPTIONS_INIT;
struct stash_update_rules data = {0};
int error;
if ((error = git_index_new(&i_index)) < 0)
goto cleanup;
if (flags & GIT_STASH_INCLUDE_UNTRACKED) {
opts.flags |= GIT_DIFF_INCLUDE_UNTRACKED |
GIT_DIFF_RECURSE_UNTRACKED_DIRS;
data.include_untracked = true;
}
if (flags & GIT_STASH_INCLUDE_IGNORED) {
opts.flags |= GIT_DIFF_INCLUDE_IGNORED |
GIT_DIFF_RECURSE_IGNORED_DIRS;
data.include_ignored = true;
}
if ((error = git_commit_tree(&i_tree, i_commit)) < 0)
goto cleanup;
if ((error = git_diff_tree_to_workdir(&diff, repo, i_tree, &opts)) < 0)
goto cleanup;
if ((error = stash_update_index_from_diff(repo, i_index, diff, &data)) < 0)
goto cleanup;
error = build_tree_from_index(tree_out, repo, i_index);
cleanup:
git_diff_free(diff);
git_tree_free(i_tree);
git_index_free(i_index);
return error;
}
static int commit_untracked(
git_commit **u_commit,
git_repository *repo,
const git_signature *stasher,
const char *message,
git_commit *i_commit,
uint32_t flags)
{
git_tree *u_tree = NULL;
git_oid u_commit_oid;
git_buf msg = GIT_BUF_INIT;
int error;
if ((error = build_untracked_tree(&u_tree, repo, i_commit, flags)) < 0)
goto cleanup;
if ((error = git_buf_printf(&msg, "untracked files on %s\n", message)) < 0)
goto cleanup;
if ((error = git_commit_create(
&u_commit_oid,
repo,
NULL,
stasher,
stasher,
NULL,
git_buf_cstr(&msg),
u_tree,
0,
NULL)) < 0)
goto cleanup;
error = git_commit_lookup(u_commit, repo, &u_commit_oid);
cleanup:
git_tree_free(u_tree);
git_buf_dispose(&msg);
return error;
}
static git_diff_delta *stash_delta_merge(
const git_diff_delta *a,
const git_diff_delta *b,
git_pool *pool)
{
/* Special case for stash: if a file is deleted in the index, but exists
* in the working tree, we need to stash the workdir copy for the workdir.
*/
if (a->status == GIT_DELTA_DELETED && b->status == GIT_DELTA_UNTRACKED) {
git_diff_delta *dup = git_diff__delta_dup(b, pool);
if (dup)
dup->status = GIT_DELTA_MODIFIED;
return dup;
}
return git_diff__merge_like_cgit(a, b, pool);
}
static int build_workdir_tree(
git_tree **tree_out,
git_repository *repo,
git_index *i_index,
git_commit *b_commit)
{
git_tree *b_tree = NULL;
git_diff *diff = NULL, *idx_to_wd = NULL;
git_diff_options opts = GIT_DIFF_OPTIONS_INIT;
struct stash_update_rules data = {0};
int error;
opts.flags = GIT_DIFF_IGNORE_SUBMODULES | GIT_DIFF_INCLUDE_UNTRACKED;
if ((error = git_commit_tree(&b_tree, b_commit)) < 0)
goto cleanup;
if ((error = git_diff_tree_to_index(&diff, repo, b_tree, i_index, &opts)) < 0 ||
(error = git_diff_index_to_workdir(&idx_to_wd, repo, i_index, &opts)) < 0 ||
(error = git_diff__merge(diff, idx_to_wd, stash_delta_merge)) < 0)
goto cleanup;
data.include_changed = true;
if ((error = stash_update_index_from_diff(repo, i_index, diff, &data)) < 0)
goto cleanup;
error = build_tree_from_index(tree_out, repo, i_index);
cleanup:
git_diff_free(idx_to_wd);
git_diff_free(diff);
git_tree_free(b_tree);
return error;
}
static int commit_worktree(
git_oid *w_commit_oid,
git_repository *repo,
const git_signature *stasher,
const char *message,
git_commit *i_commit,
git_commit *b_commit,
git_commit *u_commit)
{
const git_commit *parents[] = { NULL, NULL, NULL };
git_index *i_index = NULL, *r_index = NULL;
git_tree *w_tree = NULL;
int error = 0, ignorecase;
parents[0] = b_commit;
parents[1] = i_commit;
parents[2] = u_commit;
if ((error = git_repository_index(&r_index, repo) < 0) ||
(error = git_index_new(&i_index)) < 0 ||
(error = git_index__fill(i_index, &r_index->entries) < 0) ||
(error = git_repository__configmap_lookup(&ignorecase, repo, GIT_CONFIGMAP_IGNORECASE)) < 0)
goto cleanup;
git_index__set_ignore_case(i_index, ignorecase);
if ((error = build_workdir_tree(&w_tree, repo, i_index, b_commit)) < 0)
goto cleanup;
error = git_commit_create(
w_commit_oid,
repo,
NULL,
stasher,
stasher,
NULL,
message,
w_tree,
u_commit ? 3 : 2,
parents);
cleanup:
git_tree_free(w_tree);
git_index_free(i_index);
git_index_free(r_index);
return error;
}
static int prepare_worktree_commit_message(git_buf *out, const char *user_message)
{
git_buf buf = GIT_BUF_INIT;
int error = 0;
if (!user_message) {
git_buf_printf(&buf, "WIP on %s", git_buf_cstr(out));
} else {
const char *colon;
if ((colon = strchr(git_buf_cstr(out), ':')) == NULL)
goto cleanup;
git_buf_puts(&buf, "On ");
git_buf_put(&buf, git_buf_cstr(out), colon - out->ptr);
git_buf_printf(&buf, ": %s\n", user_message);
}
if (git_buf_oom(&buf)) {
error = -1;
goto cleanup;
}
git_buf_swap(out, &buf);
cleanup:
git_buf_dispose(&buf);
return error;
}
static int update_reflog(
git_oid *w_commit_oid,
git_repository *repo,
const char *message)
{
git_reference *stash;
int error;
if ((error = git_reference_ensure_log(repo, GIT_REFS_STASH_FILE)) < 0)
return error;
error = git_reference_create(&stash, repo, GIT_REFS_STASH_FILE, w_commit_oid, 1, message);
git_reference_free(stash);
return error;
}
static int is_dirty_cb(const char *path, unsigned int status, void *payload)
{
GIT_UNUSED(path);
GIT_UNUSED(status);
GIT_UNUSED(payload);
return GIT_PASSTHROUGH;
}
static int ensure_there_are_changes_to_stash(git_repository *repo, uint32_t flags)
{
int error;
git_status_options opts = GIT_STATUS_OPTIONS_INIT;
opts.show = GIT_STATUS_SHOW_INDEX_AND_WORKDIR;
opts.flags = GIT_STATUS_OPT_EXCLUDE_SUBMODULES;
if (flags & GIT_STASH_INCLUDE_UNTRACKED)
opts.flags |= GIT_STATUS_OPT_INCLUDE_UNTRACKED |
GIT_STATUS_OPT_RECURSE_UNTRACKED_DIRS;
if (flags & GIT_STASH_INCLUDE_IGNORED)
opts.flags |= GIT_STATUS_OPT_INCLUDE_IGNORED |
GIT_STATUS_OPT_RECURSE_IGNORED_DIRS;
error = git_status_foreach_ext(repo, &opts, is_dirty_cb, NULL);
if (error == GIT_PASSTHROUGH)
return 0;
if (!error)
return create_error(GIT_ENOTFOUND, "there is nothing to stash.");
return error;
}
static int reset_index_and_workdir(git_repository *repo, git_commit *commit, uint32_t flags)
{
git_checkout_options opts = GIT_CHECKOUT_OPTIONS_INIT;
opts.checkout_strategy = GIT_CHECKOUT_FORCE;
if (flags & GIT_STASH_INCLUDE_UNTRACKED)
opts.checkout_strategy |= GIT_CHECKOUT_REMOVE_UNTRACKED;
if (flags & GIT_STASH_INCLUDE_IGNORED)
opts.checkout_strategy |= GIT_CHECKOUT_REMOVE_IGNORED;
return git_checkout_tree(repo, (git_object *)commit, &opts);
}
int git_stash_save(
git_oid *out,
git_repository *repo,
const git_signature *stasher,
const char *message,
uint32_t flags)
{
git_index *index = NULL;
git_commit *b_commit = NULL, *i_commit = NULL, *u_commit = NULL;
git_buf msg = GIT_BUF_INIT;
int error;
GIT_ASSERT_ARG(out);
GIT_ASSERT_ARG(repo);
GIT_ASSERT_ARG(stasher);
if ((error = git_repository__ensure_not_bare(repo, "stash save")) < 0)
return error;
if ((error = retrieve_base_commit_and_message(&b_commit, &msg, repo)) < 0)
goto cleanup;
if ((error = ensure_there_are_changes_to_stash(repo, flags)) < 0)
goto cleanup;
if ((error = git_repository_index(&index, repo)) < 0)
goto cleanup;
if ((error = commit_index(&i_commit, repo, index, stasher,
git_buf_cstr(&msg), b_commit)) < 0)
goto cleanup;
if ((flags & (GIT_STASH_INCLUDE_UNTRACKED | GIT_STASH_INCLUDE_IGNORED)) &&
(error = commit_untracked(&u_commit, repo, stasher,
git_buf_cstr(&msg), i_commit, flags)) < 0)
goto cleanup;
if ((error = prepare_worktree_commit_message(&msg, message)) < 0)
goto cleanup;
if ((error = commit_worktree(out, repo, stasher, git_buf_cstr(&msg),
i_commit, b_commit, u_commit)) < 0)
goto cleanup;
git_buf_rtrim(&msg);
if ((error = update_reflog(out, repo, git_buf_cstr(&msg))) < 0)
goto cleanup;
if ((error = reset_index_and_workdir(repo, (flags & GIT_STASH_KEEP_INDEX) ? i_commit : b_commit,
flags)) < 0)
goto cleanup;
cleanup:
git_buf_dispose(&msg);
git_commit_free(i_commit);
git_commit_free(b_commit);
git_commit_free(u_commit);
git_index_free(index);
return error;
}
static int retrieve_stash_commit(
git_commit **commit,
git_repository *repo,
size_t index)
{
git_reference *stash = NULL;
git_reflog *reflog = NULL;
int error;
size_t max;
const git_reflog_entry *entry;
if ((error = git_reference_lookup(&stash, repo, GIT_REFS_STASH_FILE)) < 0)
goto cleanup;
if ((error = git_reflog_read(&reflog, repo, GIT_REFS_STASH_FILE)) < 0)
goto cleanup;
max = git_reflog_entrycount(reflog);
if (!max || index > max - 1) {
error = GIT_ENOTFOUND;
git_error_set(GIT_ERROR_STASH, "no stashed state at position %" PRIuZ, index);
goto cleanup;
}
entry = git_reflog_entry_byindex(reflog, index);
if ((error = git_commit_lookup(commit, repo, git_reflog_entry_id_new(entry))) < 0)
goto cleanup;
cleanup:
git_reference_free(stash);
git_reflog_free(reflog);
return error;
}
static int retrieve_stash_trees(
git_tree **out_stash_tree,
git_tree **out_base_tree,
git_tree **out_index_tree,
git_tree **out_index_parent_tree,
git_tree **out_untracked_tree,
git_commit *stash_commit)
{
git_tree *stash_tree = NULL;
git_commit *base_commit = NULL;
git_tree *base_tree = NULL;
git_commit *index_commit = NULL;
git_tree *index_tree = NULL;
git_commit *index_parent_commit = NULL;
git_tree *index_parent_tree = NULL;
git_commit *untracked_commit = NULL;
git_tree *untracked_tree = NULL;
int error;
if ((error = git_commit_tree(&stash_tree, stash_commit)) < 0)
goto cleanup;
if ((error = git_commit_parent(&base_commit, stash_commit, 0)) < 0)
goto cleanup;
if ((error = git_commit_tree(&base_tree, base_commit)) < 0)
goto cleanup;
if ((error = git_commit_parent(&index_commit, stash_commit, 1)) < 0)
goto cleanup;
if ((error = git_commit_tree(&index_tree, index_commit)) < 0)
goto cleanup;
if ((error = git_commit_parent(&index_parent_commit, index_commit, 0)) < 0)
goto cleanup;
if ((error = git_commit_tree(&index_parent_tree, index_parent_commit)) < 0)
goto cleanup;
if (git_commit_parentcount(stash_commit) == 3) {
if ((error = git_commit_parent(&untracked_commit, stash_commit, 2)) < 0)
goto cleanup;
if ((error = git_commit_tree(&untracked_tree, untracked_commit)) < 0)
goto cleanup;
}
*out_stash_tree = stash_tree;
*out_base_tree = base_tree;
*out_index_tree = index_tree;
*out_index_parent_tree = index_parent_tree;
*out_untracked_tree = untracked_tree;
cleanup:
git_commit_free(untracked_commit);
git_commit_free(index_parent_commit);
git_commit_free(index_commit);
git_commit_free(base_commit);
if (error < 0) {
git_tree_free(stash_tree);
git_tree_free(base_tree);
git_tree_free(index_tree);
git_tree_free(index_parent_tree);
git_tree_free(untracked_tree);
}
return error;
}
static int merge_indexes(
git_index **out,
git_repository *repo,
git_tree *ancestor_tree,
git_index *ours_index,
git_index *theirs_index)
{
git_iterator *ancestor = NULL, *ours = NULL, *theirs = NULL;
git_iterator_options iter_opts = GIT_ITERATOR_OPTIONS_INIT;
int error;
iter_opts.flags = GIT_ITERATOR_DONT_IGNORE_CASE;
if ((error = git_iterator_for_tree(&ancestor, ancestor_tree, &iter_opts)) < 0 ||
(error = git_iterator_for_index(&ours, repo, ours_index, &iter_opts)) < 0 ||
(error = git_iterator_for_index(&theirs, repo, theirs_index, &iter_opts)) < 0)
goto done;
error = git_merge__iterators(out, repo, ancestor, ours, theirs, NULL);
done:
git_iterator_free(ancestor);
git_iterator_free(ours);
git_iterator_free(theirs);
return error;
}
static int merge_index_and_tree(
git_index **out,
git_repository *repo,
git_tree *ancestor_tree,
git_index *ours_index,
git_tree *theirs_tree)
{
git_iterator *ancestor = NULL, *ours = NULL, *theirs = NULL;
git_iterator_options iter_opts = GIT_ITERATOR_OPTIONS_INIT;
int error;
iter_opts.flags = GIT_ITERATOR_DONT_IGNORE_CASE;
if ((error = git_iterator_for_tree(&ancestor, ancestor_tree, &iter_opts)) < 0 ||
(error = git_iterator_for_index(&ours, repo, ours_index, &iter_opts)) < 0 ||
(error = git_iterator_for_tree(&theirs, theirs_tree, &iter_opts)) < 0)
goto done;
error = git_merge__iterators(out, repo, ancestor, ours, theirs, NULL);
done:
git_iterator_free(ancestor);
git_iterator_free(ours);
git_iterator_free(theirs);
return error;
}
static void normalize_apply_options(
git_stash_apply_options *opts,
const git_stash_apply_options *given_apply_opts)
{
if (given_apply_opts != NULL) {
memcpy(opts, given_apply_opts, sizeof(git_stash_apply_options));
} else {
git_stash_apply_options default_apply_opts = GIT_STASH_APPLY_OPTIONS_INIT;
memcpy(opts, &default_apply_opts, sizeof(git_stash_apply_options));
}
opts->checkout_options.checkout_strategy |= GIT_CHECKOUT_NO_REFRESH;
if (!opts->checkout_options.our_label)
opts->checkout_options.our_label = "Updated upstream";
if (!opts->checkout_options.their_label)
opts->checkout_options.their_label = "Stashed changes";
}
int git_stash_apply_options_init(git_stash_apply_options *opts, unsigned int version)
{
GIT_INIT_STRUCTURE_FROM_TEMPLATE(
opts, version, git_stash_apply_options, GIT_STASH_APPLY_OPTIONS_INIT);
return 0;
}
#ifndef GIT_DEPRECATE_HARD
int git_stash_apply_init_options(git_stash_apply_options *opts, unsigned int version)
{
return git_stash_apply_options_init(opts, version);
}
#endif
#define NOTIFY_PROGRESS(opts, progress_type) \
do { \
if ((opts).progress_cb && \
(error = (opts).progress_cb((progress_type), (opts).progress_payload))) { \
error = (error < 0) ? error : -1; \
goto cleanup; \
} \
} while(false);
static int ensure_clean_index(git_repository *repo, git_index *index)
{
git_tree *head_tree = NULL;
git_diff *index_diff = NULL;
int error = 0;
if ((error = git_repository_head_tree(&head_tree, repo)) < 0 ||
(error = git_diff_tree_to_index(
&index_diff, repo, head_tree, index, NULL)) < 0)
goto done;
if (git_diff_num_deltas(index_diff) > 0) {
git_error_set(GIT_ERROR_STASH, "%" PRIuZ " uncommitted changes exist in the index",
git_diff_num_deltas(index_diff));
error = GIT_EUNCOMMITTED;
}
done:
git_diff_free(index_diff);
git_tree_free(head_tree);
return error;
}
static int stage_new_file(const git_index_entry **entries, void *data)
{
git_index *index = data;
if(entries[0] == NULL)
return git_index_add(index, entries[1]);
else
return git_index_add(index, entries[0]);
}
static int stage_new_files(
git_index **out,
git_tree *parent_tree,
git_tree *tree)
{
git_iterator *iterators[2] = { NULL, NULL };
git_iterator_options iterator_options = GIT_ITERATOR_OPTIONS_INIT;
git_index *index = NULL;
int error;
if ((error = git_index_new(&index)) < 0 ||
(error = git_iterator_for_tree(
&iterators[0], parent_tree, &iterator_options)) < 0 ||
(error = git_iterator_for_tree(
&iterators[1], tree, &iterator_options)) < 0)
goto done;
error = git_iterator_walk(iterators, 2, stage_new_file, index);
done:
if (error < 0)
git_index_free(index);
else
*out = index;
git_iterator_free(iterators[0]);
git_iterator_free(iterators[1]);
return error;
}
int git_stash_apply(
git_repository *repo,
size_t index,
const git_stash_apply_options *given_opts)
{
git_stash_apply_options opts;
unsigned int checkout_strategy;
git_commit *stash_commit = NULL;
git_tree *stash_tree = NULL;
git_tree *stash_parent_tree = NULL;
git_tree *index_tree = NULL;
git_tree *index_parent_tree = NULL;
git_tree *untracked_tree = NULL;
git_index *stash_adds = NULL;
git_index *repo_index = NULL;
git_index *unstashed_index = NULL;
git_index *modified_index = NULL;
git_index *untracked_index = NULL;
int error;
GIT_ERROR_CHECK_VERSION(given_opts, GIT_STASH_APPLY_OPTIONS_VERSION, "git_stash_apply_options");
normalize_apply_options(&opts, given_opts);
checkout_strategy = opts.checkout_options.checkout_strategy;
NOTIFY_PROGRESS(opts, GIT_STASH_APPLY_PROGRESS_LOADING_STASH);
/* Retrieve commit corresponding to the given stash */
if ((error = retrieve_stash_commit(&stash_commit, repo, index)) < 0)
goto cleanup;
/* Retrieve all trees in the stash */
if ((error = retrieve_stash_trees(
&stash_tree, &stash_parent_tree, &index_tree,
&index_parent_tree, &untracked_tree, stash_commit)) < 0)
goto cleanup;
/* Load repo index */
if ((error = git_repository_index(&repo_index, repo)) < 0)
goto cleanup;
NOTIFY_PROGRESS(opts, GIT_STASH_APPLY_PROGRESS_ANALYZE_INDEX);
if ((error = ensure_clean_index(repo, repo_index)) < 0)
goto cleanup;
/* Restore index if required */
if ((opts.flags & GIT_STASH_APPLY_REINSTATE_INDEX) &&
git_oid_cmp(git_tree_id(stash_parent_tree), git_tree_id(index_tree))) {
if ((error = merge_index_and_tree(
&unstashed_index, repo, index_parent_tree, repo_index, index_tree)) < 0)
goto cleanup;
if (git_index_has_conflicts(unstashed_index)) {
error = GIT_ECONFLICT;
goto cleanup;
}
/* Otherwise, stage any new files in the stash tree. (Note: their
* previously unstaged contents are staged, not the previously staged.)
*/
} else if ((opts.flags & GIT_STASH_APPLY_REINSTATE_INDEX) == 0) {
if ((error = stage_new_files(
&stash_adds, stash_parent_tree, stash_tree)) < 0 ||
(error = merge_indexes(
&unstashed_index, repo, stash_parent_tree, repo_index, stash_adds)) < 0)
goto cleanup;
}
NOTIFY_PROGRESS(opts, GIT_STASH_APPLY_PROGRESS_ANALYZE_MODIFIED);
/* Restore modified files in workdir */
if ((error = merge_index_and_tree(
&modified_index, repo, stash_parent_tree, repo_index, stash_tree)) < 0)
goto cleanup;
/* If applicable, restore untracked / ignored files in workdir */
if (untracked_tree) {
NOTIFY_PROGRESS(opts, GIT_STASH_APPLY_PROGRESS_ANALYZE_UNTRACKED);
if ((error = merge_index_and_tree(&untracked_index, repo, NULL, repo_index, untracked_tree)) < 0)
goto cleanup;
}
if (untracked_index) {
opts.checkout_options.checkout_strategy |= GIT_CHECKOUT_DONT_UPDATE_INDEX;
NOTIFY_PROGRESS(opts, GIT_STASH_APPLY_PROGRESS_CHECKOUT_UNTRACKED);
if ((error = git_checkout_index(repo, untracked_index, &opts.checkout_options)) < 0)
goto cleanup;
opts.checkout_options.checkout_strategy = checkout_strategy;
}
/* If there are conflicts in the modified index, then we need to actually
* check that out as the repo's index. Otherwise, we don't update the
* index.
*/
if (!git_index_has_conflicts(modified_index))
opts.checkout_options.checkout_strategy |= GIT_CHECKOUT_DONT_UPDATE_INDEX;
/* Check out the modified index using the existing repo index as baseline,
* so that existing modifications in the index can be rewritten even when
* checking out safely.
*/
opts.checkout_options.baseline_index = repo_index;
NOTIFY_PROGRESS(opts, GIT_STASH_APPLY_PROGRESS_CHECKOUT_MODIFIED);
if ((error = git_checkout_index(repo, modified_index, &opts.checkout_options)) < 0)
goto cleanup;
if (unstashed_index && !git_index_has_conflicts(modified_index)) {
if ((error = git_index_read_index(repo_index, unstashed_index)) < 0)
goto cleanup;
}
NOTIFY_PROGRESS(opts, GIT_STASH_APPLY_PROGRESS_DONE);
error = git_index_write(repo_index);
cleanup:
git_index_free(untracked_index);
git_index_free(modified_index);
git_index_free(unstashed_index);
git_index_free(stash_adds);
git_index_free(repo_index);
git_tree_free(untracked_tree);
git_tree_free(index_parent_tree);
git_tree_free(index_tree);
git_tree_free(stash_parent_tree);
git_tree_free(stash_tree);
git_commit_free(stash_commit);
return error;
}
int git_stash_foreach(
git_repository *repo,
git_stash_cb callback,
void *payload)
{
git_reference *stash;
git_reflog *reflog = NULL;
int error;
size_t i, max;
const git_reflog_entry *entry;
error = git_reference_lookup(&stash, repo, GIT_REFS_STASH_FILE);
if (error == GIT_ENOTFOUND) {
git_error_clear();
return 0;
}
if (error < 0)
goto cleanup;
if ((error = git_reflog_read(&reflog, repo, GIT_REFS_STASH_FILE)) < 0)
goto cleanup;
max = git_reflog_entrycount(reflog);
for (i = 0; i < max; i++) {
entry = git_reflog_entry_byindex(reflog, i);
error = callback(i,
git_reflog_entry_message(entry),
git_reflog_entry_id_new(entry),
payload);
if (error) {
git_error_set_after_callback(error);
break;
}
}
cleanup:
git_reference_free(stash);
git_reflog_free(reflog);
return error;
}
int git_stash_drop(
git_repository *repo,
size_t index)
{
git_transaction *tx;
git_reference *stash = NULL;
git_reflog *reflog = NULL;
size_t max;
int error;
if ((error = git_transaction_new(&tx, repo)) < 0)
return error;
if ((error = git_transaction_lock_ref(tx, GIT_REFS_STASH_FILE)) < 0)
goto cleanup;
if ((error = git_reference_lookup(&stash, repo, GIT_REFS_STASH_FILE)) < 0)
goto cleanup;
if ((error = git_reflog_read(&reflog, repo, GIT_REFS_STASH_FILE)) < 0)
goto cleanup;
max = git_reflog_entrycount(reflog);
if (!max || index > max - 1) {
error = GIT_ENOTFOUND;
git_error_set(GIT_ERROR_STASH, "no stashed state at position %" PRIuZ, index);
goto cleanup;
}
if ((error = git_reflog_drop(reflog, index, true)) < 0)
goto cleanup;
if ((error = git_transaction_set_reflog(tx, GIT_REFS_STASH_FILE, reflog)) < 0)
goto cleanup;
if (max == 1) {
if ((error = git_transaction_remove(tx, GIT_REFS_STASH_FILE)) < 0)
goto cleanup;
} else if (index == 0) {
const git_reflog_entry *entry;
entry = git_reflog_entry_byindex(reflog, 0);
if ((error = git_transaction_set_target(tx, GIT_REFS_STASH_FILE, &entry->oid_cur, NULL, NULL)) < 0)
goto cleanup;
}
error = git_transaction_commit(tx);
cleanup:
git_reference_free(stash);
git_transaction_free(tx);
git_reflog_free(reflog);
return error;
}
int git_stash_pop(
git_repository *repo,
size_t index,
const git_stash_apply_options *options)
{
int error;
if ((error = git_stash_apply(repo, index, options)) < 0)
return error;
return git_stash_drop(repo, index);
}
|
0 |
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2
|
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2/src/runtime.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_runtime_h__
#define INCLUDE_runtime_h__
#include "common.h"
typedef int (*git_runtime_init_fn)(void);
typedef void (*git_runtime_shutdown_fn)(void);
/**
* Start up a new runtime. If this is the first time that this
* function is called within the context of the current library
* or executable, then the given `init_fns` will be invoked. If
* it is not the first time, they will be ignored.
*
* The given initialization functions _may_ register shutdown
* handlers using `git_runtime_shutdown_register` to be notified
* when the runtime is shutdown.
*
* @param init_fns The list of initialization functions to call
* @param cnt The number of init_fns
* @return The number of initializations performed (including this one) or an error
*/
int git_runtime_init(git_runtime_init_fn init_fns[], size_t cnt);
/*
* Returns the number of initializations active (the number of calls to
* `git_runtime_init` minus the number of calls sto `git_runtime_shutdown`).
* If 0, the runtime is not currently initialized.
*
* @return The number of initializations performed or an error
*/
int git_runtime_init_count(void);
/**
* Shut down the runtime. If this is the last shutdown call,
* such that there are no remaining `init` calls, then any
* shutdown hooks that have been registered will be invoked.
*
* The number of outstanding initializations will be returned.
* If this number is 0, then the runtime is shutdown.
*
* @return The number of outstanding initializations (after this one) or an error
*/
int git_runtime_shutdown(void);
/**
* Register a shutdown handler for this runtime. This should be done
* by a function invoked by `git_runtime_init` to ensure that the
* appropriate locks are taken.
*
* @param callback The shutdown handler callback
* @return 0 or an error code
*/
int git_runtime_shutdown_register(git_runtime_shutdown_fn callback);
#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/varint.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 "varint.h"
uintmax_t git_decode_varint(const unsigned char *bufp, size_t *varint_len)
{
const unsigned char *buf = bufp;
unsigned char c = *buf++;
uintmax_t val = c & 127;
while (c & 128) {
val += 1;
if (!val || MSB(val, 7)) {
/* This is not a valid varint_len, so it signals
the error */
*varint_len = 0;
return 0; /* overflow */
}
c = *buf++;
val = (val << 7) + (c & 127);
}
*varint_len = buf - bufp;
return val;
}
int git_encode_varint(unsigned char *buf, size_t bufsize, uintmax_t value)
{
unsigned char varint[16];
unsigned pos = sizeof(varint) - 1;
varint[pos] = value & 127;
while (value >>= 7)
varint[--pos] = 128 | (--value & 127);
if (buf) {
if (bufsize < (sizeof(varint) - pos))
return -1;
memcpy(buf, varint + pos, sizeof(varint) - pos);
}
return sizeof(varint) - pos;
}
|
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.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_filter_h__
#define INCLUDE_filter_h__
#include "common.h"
#include "attr_file.h"
#include "git2/filter.h"
#include "git2/sys/filter.h"
/* Amount of file to examine for NUL byte when checking binary-ness */
#define GIT_FILTER_BYTES_TO_CHECK_NUL 8000
typedef struct {
git_filter_options options;
git_attr_session *attr_session;
git_buf *temp_buf;
} git_filter_session;
#define GIT_FILTER_SESSION_INIT {GIT_FILTER_OPTIONS_INIT, 0}
extern int git_filter_global_init(void);
extern void git_filter_free(git_filter *filter);
extern 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);
/*
* The given input buffer will be converted to the given output buffer.
* The input buffer will be freed (_if_ it was allocated).
*/
extern int git_filter_list__convert_buf(
git_buf *out,
git_filter_list *filters,
git_buf *in);
/*
* Available filters
*/
extern git_filter *git_crlf_filter_new(void);
extern git_filter *git_ident_filter_new(void);
extern 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);
#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.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 "branch.h"
#include "commit.h"
#include "tag.h"
#include "config.h"
#include "refspec.h"
#include "refs.h"
#include "remote.h"
#include "annotated_commit.h"
#include "worktree.h"
#include "git2/branch.h"
static int retrieve_branch_reference(
git_reference **branch_reference_out,
git_repository *repo,
const char *branch_name,
bool is_remote)
{
git_reference *branch = NULL;
int error = 0;
char *prefix;
git_buf ref_name = GIT_BUF_INIT;
prefix = is_remote ? GIT_REFS_REMOTES_DIR : GIT_REFS_HEADS_DIR;
if ((error = git_buf_joinpath(&ref_name, prefix, branch_name)) < 0)
/* OOM */;
else if ((error = git_reference_lookup(&branch, repo, ref_name.ptr)) < 0)
git_error_set(
GIT_ERROR_REFERENCE, "cannot locate %s branch '%s'",
is_remote ? "remote-tracking" : "local", branch_name);
*branch_reference_out = branch; /* will be NULL on error */
git_buf_dispose(&ref_name);
return error;
}
static int not_a_local_branch(const char *reference_name)
{
git_error_set(
GIT_ERROR_INVALID,
"reference '%s' is not a local branch.", reference_name);
return -1;
}
static int create_branch(
git_reference **ref_out,
git_repository *repository,
const char *branch_name,
const git_commit *commit,
const char *from,
int force)
{
int is_unmovable_head = 0;
git_reference *branch = NULL;
git_buf canonical_branch_name = GIT_BUF_INIT,
log_message = GIT_BUF_INIT;
int error = -1;
int bare = git_repository_is_bare(repository);
GIT_ASSERT_ARG(branch_name);
GIT_ASSERT_ARG(commit);
GIT_ASSERT_ARG(ref_out);
GIT_ASSERT_ARG(git_commit_owner(commit) == repository);
if (!git__strcmp(branch_name, "HEAD")) {
git_error_set(GIT_ERROR_REFERENCE, "'HEAD' is not a valid branch name");
error = -1;
goto cleanup;
}
if (force && !bare && git_branch_lookup(&branch, repository, branch_name, GIT_BRANCH_LOCAL) == 0) {
error = git_branch_is_head(branch);
git_reference_free(branch);
branch = NULL;
if (error < 0)
goto cleanup;
is_unmovable_head = error;
}
if (is_unmovable_head && force) {
git_error_set(GIT_ERROR_REFERENCE, "cannot force update branch '%s' as it is "
"the current HEAD of the repository.", branch_name);
error = -1;
goto cleanup;
}
if (git_buf_joinpath(&canonical_branch_name, GIT_REFS_HEADS_DIR, branch_name) < 0)
goto cleanup;
if (git_buf_printf(&log_message, "branch: Created from %s", from) < 0)
goto cleanup;
error = git_reference_create(&branch, repository,
git_buf_cstr(&canonical_branch_name), git_commit_id(commit), force,
git_buf_cstr(&log_message));
if (!error)
*ref_out = branch;
cleanup:
git_buf_dispose(&canonical_branch_name);
git_buf_dispose(&log_message);
return error;
}
int git_branch_create(
git_reference **ref_out,
git_repository *repository,
const char *branch_name,
const git_commit *commit,
int force)
{
return create_branch(ref_out, repository, branch_name, commit, git_oid_tostr_s(git_commit_id(commit)), force);
}
int git_branch_create_from_annotated(
git_reference **ref_out,
git_repository *repository,
const char *branch_name,
const git_annotated_commit *commit,
int force)
{
return create_branch(ref_out,
repository, branch_name, commit->commit, commit->description, force);
}
static int branch_is_checked_out(git_repository *worktree, void *payload)
{
git_reference *branch = (git_reference *) payload;
git_reference *head = NULL;
int error;
if (git_repository_is_bare(worktree))
return 0;
if ((error = git_reference_lookup(&head, worktree, GIT_HEAD_FILE)) < 0) {
if (error == GIT_ENOTFOUND)
error = 0;
goto out;
}
if (git_reference_type(head) != GIT_REFERENCE_SYMBOLIC)
goto out;
error = !git__strcmp(head->target.symbolic, branch->name);
out:
git_reference_free(head);
return error;
}
int git_branch_is_checked_out(const git_reference *branch)
{
GIT_ASSERT_ARG(branch);
if (!git_reference_is_branch(branch))
return 0;
return git_repository_foreach_worktree(git_reference_owner(branch),
branch_is_checked_out, (void *)branch) == 1;
}
int git_branch_delete(git_reference *branch)
{
int is_head;
git_buf config_section = GIT_BUF_INIT;
int error = -1;
GIT_ASSERT_ARG(branch);
if (!git_reference_is_branch(branch) && !git_reference_is_remote(branch)) {
git_error_set(GIT_ERROR_INVALID, "reference '%s' is not a valid branch.",
git_reference_name(branch));
return GIT_ENOTFOUND;
}
if ((is_head = git_branch_is_head(branch)) < 0)
return is_head;
if (is_head) {
git_error_set(GIT_ERROR_REFERENCE, "cannot delete branch '%s' as it is "
"the current HEAD of the repository.", git_reference_name(branch));
return -1;
}
if (git_reference_is_branch(branch) && git_branch_is_checked_out(branch)) {
git_error_set(GIT_ERROR_REFERENCE, "Cannot delete branch '%s' as it is "
"the current HEAD of a linked repository.", git_reference_name(branch));
return -1;
}
if (git_buf_join(&config_section, '.', "branch",
git_reference_name(branch) + strlen(GIT_REFS_HEADS_DIR)) < 0)
goto on_error;
if (git_config_rename_section(
git_reference_owner(branch), git_buf_cstr(&config_section), NULL) < 0)
goto on_error;
error = git_reference_delete(branch);
on_error:
git_buf_dispose(&config_section);
return error;
}
typedef struct {
git_reference_iterator *iter;
unsigned int flags;
} branch_iter;
int git_branch_next(git_reference **out, git_branch_t *out_type, git_branch_iterator *_iter)
{
branch_iter *iter = (branch_iter *) _iter;
git_reference *ref;
int error;
while ((error = git_reference_next(&ref, iter->iter)) == 0) {
if ((iter->flags & GIT_BRANCH_LOCAL) &&
!git__prefixcmp(ref->name, GIT_REFS_HEADS_DIR)) {
*out = ref;
*out_type = GIT_BRANCH_LOCAL;
return 0;
} else if ((iter->flags & GIT_BRANCH_REMOTE) &&
!git__prefixcmp(ref->name, GIT_REFS_REMOTES_DIR)) {
*out = ref;
*out_type = GIT_BRANCH_REMOTE;
return 0;
} else {
git_reference_free(ref);
}
}
return error;
}
int git_branch_iterator_new(
git_branch_iterator **out,
git_repository *repo,
git_branch_t list_flags)
{
branch_iter *iter;
iter = git__calloc(1, sizeof(branch_iter));
GIT_ERROR_CHECK_ALLOC(iter);
iter->flags = list_flags;
if (git_reference_iterator_new(&iter->iter, repo) < 0) {
git__free(iter);
return -1;
}
*out = (git_branch_iterator *) iter;
return 0;
}
void git_branch_iterator_free(git_branch_iterator *_iter)
{
branch_iter *iter = (branch_iter *) _iter;
if (iter == NULL)
return;
git_reference_iterator_free(iter->iter);
git__free(iter);
}
int git_branch_move(
git_reference **out,
git_reference *branch,
const char *new_branch_name,
int force)
{
git_buf new_reference_name = GIT_BUF_INIT,
old_config_section = GIT_BUF_INIT,
new_config_section = GIT_BUF_INIT,
log_message = GIT_BUF_INIT;
int error;
GIT_ASSERT_ARG(branch);
GIT_ASSERT_ARG(new_branch_name);
if (!git_reference_is_branch(branch))
return not_a_local_branch(git_reference_name(branch));
if ((error = git_buf_joinpath(&new_reference_name, GIT_REFS_HEADS_DIR, new_branch_name)) < 0)
goto done;
if ((error = git_buf_printf(&log_message, "branch: renamed %s to %s",
git_reference_name(branch), git_buf_cstr(&new_reference_name))) < 0)
goto done;
/* first update ref then config so failure won't trash config */
error = git_reference_rename(
out, branch, git_buf_cstr(&new_reference_name), force,
git_buf_cstr(&log_message));
if (error < 0)
goto done;
git_buf_join(&old_config_section, '.', "branch",
git_reference_name(branch) + strlen(GIT_REFS_HEADS_DIR));
git_buf_join(&new_config_section, '.', "branch", new_branch_name);
error = git_config_rename_section(
git_reference_owner(branch),
git_buf_cstr(&old_config_section),
git_buf_cstr(&new_config_section));
done:
git_buf_dispose(&new_reference_name);
git_buf_dispose(&old_config_section);
git_buf_dispose(&new_config_section);
git_buf_dispose(&log_message);
return error;
}
int git_branch_lookup(
git_reference **ref_out,
git_repository *repo,
const char *branch_name,
git_branch_t branch_type)
{
int error = -1;
GIT_ASSERT_ARG(ref_out);
GIT_ASSERT_ARG(repo);
GIT_ASSERT_ARG(branch_name);
switch (branch_type) {
case GIT_BRANCH_LOCAL:
case GIT_BRANCH_REMOTE:
error = retrieve_branch_reference(ref_out, repo, branch_name, branch_type == GIT_BRANCH_REMOTE);
break;
case GIT_BRANCH_ALL:
error = retrieve_branch_reference(ref_out, repo, branch_name, false);
if (error == GIT_ENOTFOUND)
error = retrieve_branch_reference(ref_out, repo, branch_name, true);
break;
default:
GIT_ASSERT(false);
}
return error;
}
int git_branch_name(
const char **out,
const git_reference *ref)
{
const char *branch_name;
GIT_ASSERT_ARG(out);
GIT_ASSERT_ARG(ref);
branch_name = ref->name;
if (git_reference_is_branch(ref)) {
branch_name += strlen(GIT_REFS_HEADS_DIR);
} else if (git_reference_is_remote(ref)) {
branch_name += strlen(GIT_REFS_REMOTES_DIR);
} else {
git_error_set(GIT_ERROR_INVALID,
"reference '%s' is neither a local nor a remote branch.", ref->name);
return -1;
}
*out = branch_name;
return 0;
}
static int retrieve_upstream_configuration(
git_buf *out,
const git_config *config,
const char *canonical_branch_name,
const char *format)
{
git_buf buf = GIT_BUF_INIT;
int error;
if (git_buf_printf(&buf, format,
canonical_branch_name + strlen(GIT_REFS_HEADS_DIR)) < 0)
return -1;
error = git_config_get_string_buf(out, config, git_buf_cstr(&buf));
git_buf_dispose(&buf);
return error;
}
int git_branch_upstream_name(
git_buf *out,
git_repository *repo,
const char *refname)
{
git_buf remote_name = GIT_BUF_INIT;
git_buf merge_name = GIT_BUF_INIT;
git_buf buf = GIT_BUF_INIT;
int error = -1;
git_remote *remote = NULL;
const git_refspec *refspec;
git_config *config;
GIT_ASSERT_ARG(out);
GIT_ASSERT_ARG(refname);
if ((error = git_buf_sanitize(out)) < 0)
return error;
if (!git_reference__is_branch(refname))
return not_a_local_branch(refname);
if ((error = git_repository_config_snapshot(&config, repo)) < 0)
return error;
if ((error = retrieve_upstream_configuration(
&remote_name, config, refname, "branch.%s.remote")) < 0)
goto cleanup;
if ((error = retrieve_upstream_configuration(
&merge_name, config, refname, "branch.%s.merge")) < 0)
goto cleanup;
if (git_buf_len(&remote_name) == 0 || git_buf_len(&merge_name) == 0) {
git_error_set(GIT_ERROR_REFERENCE,
"branch '%s' does not have an upstream", refname);
error = GIT_ENOTFOUND;
goto cleanup;
}
if (strcmp(".", git_buf_cstr(&remote_name)) != 0) {
if ((error = git_remote_lookup(&remote, repo, git_buf_cstr(&remote_name))) < 0)
goto cleanup;
refspec = git_remote__matching_refspec(remote, git_buf_cstr(&merge_name));
if (!refspec) {
error = GIT_ENOTFOUND;
goto cleanup;
}
if (git_refspec_transform(&buf, refspec, git_buf_cstr(&merge_name)) < 0)
goto cleanup;
} else
if (git_buf_set(&buf, git_buf_cstr(&merge_name), git_buf_len(&merge_name)) < 0)
goto cleanup;
error = git_buf_set(out, git_buf_cstr(&buf), git_buf_len(&buf));
cleanup:
git_config_free(config);
git_remote_free(remote);
git_buf_dispose(&remote_name);
git_buf_dispose(&merge_name);
git_buf_dispose(&buf);
return error;
}
static int git_branch_upstream_with_format(git_buf *buf, git_repository *repo, const char *refname, const char *format, const char *format_name)
{
int error;
git_config *cfg;
if (!git_reference__is_branch(refname))
return not_a_local_branch(refname);
if ((error = git_repository_config__weakptr(&cfg, repo)) < 0)
return error;
if ((error = git_buf_sanitize(buf)) < 0 ||
(error = retrieve_upstream_configuration(buf, cfg, refname, format)) < 0)
return error;
if (git_buf_len(buf) == 0) {
git_error_set(GIT_ERROR_REFERENCE, "branch '%s' does not have an upstream %s", refname, format_name);
error = GIT_ENOTFOUND;
git_buf_clear(buf);
}
return error;
}
int git_branch_upstream_remote(git_buf *buf, git_repository *repo, const char *refname)
{
return git_branch_upstream_with_format(buf, repo, refname, "branch.%s.remote", "remote");
}
int git_branch_upstream_merge(git_buf *buf, git_repository *repo, const char *refname)
{
return git_branch_upstream_with_format(buf, repo, refname, "branch.%s.merge", "merge");
}
int git_branch_remote_name(git_buf *buf, git_repository *repo, const char *refname)
{
git_strarray remote_list = {0};
size_t i;
git_remote *remote;
const git_refspec *fetchspec;
int error = 0;
char *remote_name = NULL;
GIT_ASSERT_ARG(buf);
GIT_ASSERT_ARG(repo);
GIT_ASSERT_ARG(refname);
if ((error = git_buf_sanitize(buf)) < 0)
return error;
/* Verify that this is a remote branch */
if (!git_reference__is_remote(refname)) {
git_error_set(GIT_ERROR_INVALID, "reference '%s' is not a remote branch.",
refname);
error = GIT_ERROR;
goto cleanup;
}
/* Get the remotes */
if ((error = git_remote_list(&remote_list, repo)) < 0)
goto cleanup;
/* Find matching remotes */
for (i = 0; i < remote_list.count; i++) {
if ((error = git_remote_lookup(&remote, repo, remote_list.strings[i])) < 0)
continue;
fetchspec = git_remote__matching_dst_refspec(remote, refname);
if (fetchspec) {
/* If we have not already set out yet, then set
* it to the matching remote name. Otherwise
* multiple remotes match this reference, and it
* is ambiguous. */
if (!remote_name) {
remote_name = remote_list.strings[i];
} else {
git_remote_free(remote);
git_error_set(GIT_ERROR_REFERENCE,
"reference '%s' is ambiguous", refname);
error = GIT_EAMBIGUOUS;
goto cleanup;
}
}
git_remote_free(remote);
}
if (remote_name) {
git_buf_clear(buf);
error = git_buf_puts(buf, remote_name);
} else {
git_error_set(GIT_ERROR_REFERENCE,
"could not determine remote for '%s'", refname);
error = GIT_ENOTFOUND;
}
cleanup:
if (error < 0)
git_buf_dispose(buf);
git_strarray_dispose(&remote_list);
return error;
}
int git_branch_upstream(
git_reference **tracking_out,
const git_reference *branch)
{
int error;
git_buf tracking_name = GIT_BUF_INIT;
if ((error = git_branch_upstream_name(&tracking_name,
git_reference_owner(branch), git_reference_name(branch))) < 0)
return error;
error = git_reference_lookup(
tracking_out,
git_reference_owner(branch),
git_buf_cstr(&tracking_name));
git_buf_dispose(&tracking_name);
return error;
}
static int unset_upstream(git_config *config, const char *shortname)
{
git_buf buf = GIT_BUF_INIT;
if (git_buf_printf(&buf, "branch.%s.remote", shortname) < 0)
return -1;
if (git_config_delete_entry(config, git_buf_cstr(&buf)) < 0)
goto on_error;
git_buf_clear(&buf);
if (git_buf_printf(&buf, "branch.%s.merge", shortname) < 0)
goto on_error;
if (git_config_delete_entry(config, git_buf_cstr(&buf)) < 0)
goto on_error;
git_buf_dispose(&buf);
return 0;
on_error:
git_buf_dispose(&buf);
return -1;
}
int git_branch_set_upstream(git_reference *branch, const char *branch_name)
{
git_buf key = GIT_BUF_INIT, remote_name = GIT_BUF_INIT, merge_refspec = GIT_BUF_INIT;
git_reference *upstream;
git_repository *repo;
git_remote *remote = NULL;
git_config *config;
const char *refname, *shortname;
int local, error;
const git_refspec *fetchspec;
refname = git_reference_name(branch);
if (!git_reference__is_branch(refname))
return not_a_local_branch(refname);
if (git_repository_config__weakptr(&config, git_reference_owner(branch)) < 0)
return -1;
shortname = refname + strlen(GIT_REFS_HEADS_DIR);
/* We're unsetting, delegate and bail-out */
if (branch_name == NULL)
return unset_upstream(config, shortname);
repo = git_reference_owner(branch);
/* First we need to resolve name to a branch */
if (git_branch_lookup(&upstream, repo, branch_name, GIT_BRANCH_LOCAL) == 0)
local = 1;
else if (git_branch_lookup(&upstream, repo, branch_name, GIT_BRANCH_REMOTE) == 0)
local = 0;
else {
git_error_set(GIT_ERROR_REFERENCE,
"cannot set upstream for branch '%s'", shortname);
return GIT_ENOTFOUND;
}
/*
* If it's a local-tracking branch, its remote is "." (as "the local
* repository"), and the branch name is simply the refname.
* Otherwise we need to figure out what the remote-tracking branch's
* name on the remote is and use that.
*/
if (local)
error = git_buf_puts(&remote_name, ".");
else
error = git_branch_remote_name(&remote_name, repo, git_reference_name(upstream));
if (error < 0)
goto on_error;
/* Update the upsteam branch config with the new name */
if (git_buf_printf(&key, "branch.%s.remote", shortname) < 0)
goto on_error;
if (git_config_set_string(config, git_buf_cstr(&key), git_buf_cstr(&remote_name)) < 0)
goto on_error;
if (local) {
/* A local branch uses the upstream refname directly */
if (git_buf_puts(&merge_refspec, git_reference_name(upstream)) < 0)
goto on_error;
} else {
/* We transform the upstream branch name according to the remote's refspecs */
if (git_remote_lookup(&remote, repo, git_buf_cstr(&remote_name)) < 0)
goto on_error;
fetchspec = git_remote__matching_dst_refspec(remote, git_reference_name(upstream));
if (!fetchspec || git_refspec_rtransform(&merge_refspec, fetchspec, git_reference_name(upstream)) < 0)
goto on_error;
git_remote_free(remote);
remote = NULL;
}
/* Update the merge branch config with the refspec */
git_buf_clear(&key);
if (git_buf_printf(&key, "branch.%s.merge", shortname) < 0)
goto on_error;
if (git_config_set_string(config, git_buf_cstr(&key), git_buf_cstr(&merge_refspec)) < 0)
goto on_error;
git_reference_free(upstream);
git_buf_dispose(&key);
git_buf_dispose(&remote_name);
git_buf_dispose(&merge_refspec);
return 0;
on_error:
git_reference_free(upstream);
git_buf_dispose(&key);
git_buf_dispose(&remote_name);
git_buf_dispose(&merge_refspec);
git_remote_free(remote);
return -1;
}
int git_branch_is_head(
const git_reference *branch)
{
git_reference *head;
bool is_same = false;
int error;
GIT_ASSERT_ARG(branch);
if (!git_reference_is_branch(branch))
return false;
error = git_repository_head(&head, git_reference_owner(branch));
if (error == GIT_EUNBORNBRANCH || error == GIT_ENOTFOUND)
return false;
if (error < 0)
return -1;
is_same = strcmp(
git_reference_name(branch),
git_reference_name(head)) == 0;
git_reference_free(head);
return is_same;
}
int git_branch_name_is_valid(int *valid, const char *name)
{
git_buf ref_name = GIT_BUF_INIT;
int error = 0;
GIT_ASSERT(valid);
*valid = 0;
/*
* Discourage branch name starting with dash,
* https://github.com/git/git/commit/6348624010888b
* and discourage HEAD as branch name,
* https://github.com/git/git/commit/a625b092cc5994
*/
if (!name || name[0] == '-' || !git__strcmp(name, "HEAD"))
goto done;
if ((error = git_buf_puts(&ref_name, GIT_REFS_HEADS_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;
}
|
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_tform.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_tform.h"
#include "git2/config.h"
#include "git2/blob.h"
#include "git2/sys/hashsig.h"
#include "diff.h"
#include "diff_generate.h"
#include "path.h"
#include "futils.h"
#include "config.h"
git_diff_delta *git_diff__delta_dup(
const git_diff_delta *d, git_pool *pool)
{
git_diff_delta *delta = git__malloc(sizeof(git_diff_delta));
if (!delta)
return NULL;
memcpy(delta, d, sizeof(git_diff_delta));
GIT_DIFF_FLAG__CLEAR_INTERNAL(delta->flags);
if (d->old_file.path != NULL) {
delta->old_file.path = git_pool_strdup(pool, d->old_file.path);
if (delta->old_file.path == NULL)
goto fail;
}
if (d->new_file.path != d->old_file.path && d->new_file.path != NULL) {
delta->new_file.path = git_pool_strdup(pool, d->new_file.path);
if (delta->new_file.path == NULL)
goto fail;
} else {
delta->new_file.path = delta->old_file.path;
}
return delta;
fail:
git__free(delta);
return NULL;
}
git_diff_delta *git_diff__merge_like_cgit(
const git_diff_delta *a,
const git_diff_delta *b,
git_pool *pool)
{
git_diff_delta *dup;
/* Emulate C git for merging two diffs (a la 'git diff <sha>').
*
* When C git does a diff between the work dir and a tree, it actually
* diffs with the index but uses the workdir contents. This emulates
* those choices so we can emulate the type of diff.
*
* We have three file descriptions here, let's call them:
* f1 = a->old_file
* f2 = a->new_file AND b->old_file
* f3 = b->new_file
*/
/* If one of the diffs is a conflict, just dup it */
if (b->status == GIT_DELTA_CONFLICTED)
return git_diff__delta_dup(b, pool);
if (a->status == GIT_DELTA_CONFLICTED)
return git_diff__delta_dup(a, pool);
/* if f2 == f3 or f2 is deleted, then just dup the 'a' diff */
if (b->status == GIT_DELTA_UNMODIFIED || a->status == GIT_DELTA_DELETED)
return git_diff__delta_dup(a, pool);
/* otherwise, base this diff on the 'b' diff */
if ((dup = git_diff__delta_dup(b, pool)) == NULL)
return NULL;
/* If 'a' status is uninteresting, then we're done */
if (a->status == GIT_DELTA_UNMODIFIED ||
a->status == GIT_DELTA_UNTRACKED ||
a->status == GIT_DELTA_UNREADABLE)
return dup;
GIT_ASSERT_WITH_RETVAL(b->status != GIT_DELTA_UNMODIFIED, NULL);
/* A cgit exception is that the diff of a file that is only in the
* index (i.e. not in HEAD nor workdir) is given as empty.
*/
if (dup->status == GIT_DELTA_DELETED) {
if (a->status == GIT_DELTA_ADDED) {
dup->status = GIT_DELTA_UNMODIFIED;
dup->nfiles = 2;
}
/* else don't overwrite DELETE status */
} else {
dup->status = a->status;
dup->nfiles = a->nfiles;
}
git_oid_cpy(&dup->old_file.id, &a->old_file.id);
dup->old_file.mode = a->old_file.mode;
dup->old_file.size = a->old_file.size;
dup->old_file.flags = a->old_file.flags;
return dup;
}
int git_diff__merge(
git_diff *onto, const git_diff *from, git_diff__merge_cb cb)
{
int error = 0;
git_pool onto_pool;
git_vector onto_new;
git_diff_delta *delta;
bool ignore_case, reversed;
unsigned int i, j;
GIT_ASSERT_ARG(onto);
GIT_ASSERT_ARG(from);
if (!from->deltas.length)
return 0;
ignore_case = ((onto->opts.flags & GIT_DIFF_IGNORE_CASE) != 0);
reversed = ((onto->opts.flags & GIT_DIFF_REVERSE) != 0);
if (ignore_case != ((from->opts.flags & GIT_DIFF_IGNORE_CASE) != 0) ||
reversed != ((from->opts.flags & GIT_DIFF_REVERSE) != 0)) {
git_error_set(GIT_ERROR_INVALID,
"attempt to merge diffs created with conflicting options");
return -1;
}
if (git_vector_init(&onto_new, onto->deltas.length, git_diff_delta__cmp) < 0 ||
git_pool_init(&onto_pool, 1) < 0)
return -1;
for (i = 0, j = 0; i < onto->deltas.length || j < from->deltas.length; ) {
git_diff_delta *o = GIT_VECTOR_GET(&onto->deltas, i);
const git_diff_delta *f = GIT_VECTOR_GET(&from->deltas, j);
int cmp = !f ? -1 : !o ? 1 :
STRCMP_CASESELECT(ignore_case, o->old_file.path, f->old_file.path);
if (cmp < 0) {
delta = git_diff__delta_dup(o, &onto_pool);
i++;
} else if (cmp > 0) {
delta = git_diff__delta_dup(f, &onto_pool);
j++;
} else {
const git_diff_delta *left = reversed ? f : o;
const git_diff_delta *right = reversed ? o : f;
delta = cb(left, right, &onto_pool);
i++;
j++;
}
/* the ignore rules for the target may not match the source
* or the result of a merged delta could be skippable...
*/
if (delta && git_diff_delta__should_skip(&onto->opts, delta)) {
git__free(delta);
continue;
}
if ((error = !delta ? -1 : git_vector_insert(&onto_new, delta)) < 0)
break;
}
if (!error) {
git_vector_swap(&onto->deltas, &onto_new);
git_pool_swap(&onto->pool, &onto_pool);
if ((onto->opts.flags & GIT_DIFF_REVERSE) != 0)
onto->old_src = from->old_src;
else
onto->new_src = from->new_src;
/* prefix strings also come from old pool, so recreate those.*/
onto->opts.old_prefix =
git_pool_strdup_safe(&onto->pool, onto->opts.old_prefix);
onto->opts.new_prefix =
git_pool_strdup_safe(&onto->pool, onto->opts.new_prefix);
}
git_vector_free_deep(&onto_new);
git_pool_clear(&onto_pool);
return error;
}
int git_diff_merge(git_diff *onto, const git_diff *from)
{
return git_diff__merge(onto, from, git_diff__merge_like_cgit);
}
int git_diff_find_similar__hashsig_for_file(
void **out, const git_diff_file *f, const char *path, void *p)
{
git_hashsig_option_t opt = (git_hashsig_option_t)(intptr_t)p;
GIT_UNUSED(f);
return git_hashsig_create_fromfile((git_hashsig **)out, path, opt);
}
int git_diff_find_similar__hashsig_for_buf(
void **out, const git_diff_file *f, const char *buf, size_t len, void *p)
{
git_hashsig_option_t opt = (git_hashsig_option_t)(intptr_t)p;
GIT_UNUSED(f);
return git_hashsig_create((git_hashsig **)out, buf, len, opt);
}
void git_diff_find_similar__hashsig_free(void *sig, void *payload)
{
GIT_UNUSED(payload);
git_hashsig_free(sig);
}
int git_diff_find_similar__calc_similarity(
int *score, void *siga, void *sigb, void *payload)
{
int error;
GIT_UNUSED(payload);
error = git_hashsig_compare(siga, sigb);
if (error < 0)
return error;
*score = error;
return 0;
}
#define DEFAULT_THRESHOLD 50
#define DEFAULT_BREAK_REWRITE_THRESHOLD 60
#define DEFAULT_RENAME_LIMIT 200
static int normalize_find_opts(
git_diff *diff,
git_diff_find_options *opts,
const git_diff_find_options *given)
{
git_config *cfg = NULL;
git_hashsig_option_t hashsig_opts;
GIT_ERROR_CHECK_VERSION(given, GIT_DIFF_FIND_OPTIONS_VERSION, "git_diff_find_options");
if (diff->repo != NULL &&
git_repository_config__weakptr(&cfg, diff->repo) < 0)
return -1;
if (given)
memcpy(opts, given, sizeof(*opts));
if (!given ||
(given->flags & GIT_DIFF_FIND_ALL) == GIT_DIFF_FIND_BY_CONFIG)
{
if (cfg) {
char *rule =
git_config__get_string_force(cfg, "diff.renames", "true");
int boolval;
if (!git__parse_bool(&boolval, rule) && !boolval)
/* don't set FIND_RENAMES if bool value is false */;
else if (!strcasecmp(rule, "copies") || !strcasecmp(rule, "copy"))
opts->flags |= GIT_DIFF_FIND_RENAMES | GIT_DIFF_FIND_COPIES;
else
opts->flags |= GIT_DIFF_FIND_RENAMES;
git__free(rule);
} else {
/* set default flag */
opts->flags |= GIT_DIFF_FIND_RENAMES;
}
}
/* some flags imply others */
if (opts->flags & GIT_DIFF_FIND_EXACT_MATCH_ONLY) {
/* if we are only looking for exact matches, then don't turn
* MODIFIED items into ADD/DELETE pairs because it's too picky
*/
opts->flags &= ~(GIT_DIFF_FIND_REWRITES | GIT_DIFF_BREAK_REWRITES);
/* similarly, don't look for self-rewrites to split */
opts->flags &= ~GIT_DIFF_FIND_RENAMES_FROM_REWRITES;
}
if (opts->flags & GIT_DIFF_FIND_RENAMES_FROM_REWRITES)
opts->flags |= GIT_DIFF_FIND_RENAMES;
if (opts->flags & GIT_DIFF_FIND_COPIES_FROM_UNMODIFIED)
opts->flags |= GIT_DIFF_FIND_COPIES;
if (opts->flags & GIT_DIFF_BREAK_REWRITES)
opts->flags |= GIT_DIFF_FIND_REWRITES;
#define USE_DEFAULT(X) ((X) == 0 || (X) > 100)
if (USE_DEFAULT(opts->rename_threshold))
opts->rename_threshold = DEFAULT_THRESHOLD;
if (USE_DEFAULT(opts->rename_from_rewrite_threshold))
opts->rename_from_rewrite_threshold = DEFAULT_THRESHOLD;
if (USE_DEFAULT(opts->copy_threshold))
opts->copy_threshold = DEFAULT_THRESHOLD;
if (USE_DEFAULT(opts->break_rewrite_threshold))
opts->break_rewrite_threshold = DEFAULT_BREAK_REWRITE_THRESHOLD;
#undef USE_DEFAULT
if (!opts->rename_limit) {
if (cfg) {
opts->rename_limit = git_config__get_int_force(
cfg, "diff.renamelimit", DEFAULT_RENAME_LIMIT);
}
if (opts->rename_limit <= 0)
opts->rename_limit = DEFAULT_RENAME_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;
if (opts->flags & GIT_DIFF_FIND_IGNORE_WHITESPACE)
hashsig_opts = GIT_HASHSIG_IGNORE_WHITESPACE;
else if (opts->flags & GIT_DIFF_FIND_DONT_IGNORE_WHITESPACE)
hashsig_opts = GIT_HASHSIG_NORMAL;
else
hashsig_opts = GIT_HASHSIG_SMART_WHITESPACE;
hashsig_opts |= GIT_HASHSIG_ALLOW_SMALL_FILES;
opts->metric->payload = (void *)hashsig_opts;
}
return 0;
}
static int insert_delete_side_of_split(
git_diff *diff, git_vector *onto, const git_diff_delta *delta)
{
/* make new record for DELETED side of split */
git_diff_delta *deleted = git_diff__delta_dup(delta, &diff->pool);
GIT_ERROR_CHECK_ALLOC(deleted);
deleted->status = GIT_DELTA_DELETED;
deleted->nfiles = 1;
memset(&deleted->new_file, 0, sizeof(deleted->new_file));
deleted->new_file.path = deleted->old_file.path;
deleted->new_file.flags |= GIT_DIFF_FLAG_VALID_ID;
return git_vector_insert(onto, deleted);
}
static int apply_splits_and_deletes(
git_diff *diff, size_t expected_size, bool actually_split)
{
git_vector onto = GIT_VECTOR_INIT;
size_t i;
git_diff_delta *delta;
if (git_vector_init(&onto, expected_size, git_diff_delta__cmp) < 0)
return -1;
/* build new delta list without TO_DELETE and splitting TO_SPLIT */
git_vector_foreach(&diff->deltas, i, delta) {
if ((delta->flags & GIT_DIFF_FLAG__TO_DELETE) != 0)
continue;
if ((delta->flags & GIT_DIFF_FLAG__TO_SPLIT) != 0 && actually_split) {
delta->similarity = 0;
if (insert_delete_side_of_split(diff, &onto, delta) < 0)
goto on_error;
if (diff->new_src == GIT_ITERATOR_WORKDIR)
delta->status = GIT_DELTA_UNTRACKED;
else
delta->status = GIT_DELTA_ADDED;
delta->nfiles = 1;
memset(&delta->old_file, 0, sizeof(delta->old_file));
delta->old_file.path = delta->new_file.path;
delta->old_file.flags |= GIT_DIFF_FLAG_VALID_ID;
}
/* clean up delta before inserting into new list */
GIT_DIFF_FLAG__CLEAR_INTERNAL(delta->flags);
if (delta->status != GIT_DELTA_COPIED &&
delta->status != GIT_DELTA_RENAMED &&
(delta->status != GIT_DELTA_MODIFIED || actually_split))
delta->similarity = 0;
/* insert into new list */
if (git_vector_insert(&onto, delta) < 0)
goto on_error;
}
/* cannot return an error past this point */
/* free deltas from old list that didn't make it to the new one */
git_vector_foreach(&diff->deltas, i, delta) {
if ((delta->flags & GIT_DIFF_FLAG__TO_DELETE) != 0)
git__free(delta);
}
/* swap new delta list into place */
git_vector_swap(&diff->deltas, &onto);
git_vector_free(&onto);
git_vector_sort(&diff->deltas);
return 0;
on_error:
git_vector_free_deep(&onto);
return -1;
}
GIT_INLINE(git_diff_file *) similarity_get_file(git_diff *diff, size_t idx)
{
git_diff_delta *delta = git_vector_get(&diff->deltas, idx / 2);
return (idx & 1) ? &delta->new_file : &delta->old_file;
}
typedef struct {
size_t idx;
git_iterator_t src;
git_repository *repo;
git_diff_file *file;
git_buf data;
git_odb_object *odb_obj;
git_blob *blob;
} similarity_info;
static int similarity_init(
similarity_info *info, git_diff *diff, size_t file_idx)
{
info->idx = file_idx;
info->src = (file_idx & 1) ? diff->new_src : diff->old_src;
info->repo = diff->repo;
info->file = similarity_get_file(diff, file_idx);
info->odb_obj = NULL;
info->blob = NULL;
git_buf_init(&info->data, 0);
if (info->file->size > 0 || info->src == GIT_ITERATOR_WORKDIR)
return 0;
return git_diff_file__resolve_zero_size(
info->file, &info->odb_obj, info->repo);
}
static int similarity_sig(
similarity_info *info,
const git_diff_find_options *opts,
void **cache)
{
int error = 0;
git_diff_file *file = info->file;
if (info->src == GIT_ITERATOR_WORKDIR) {
if ((error = git_repository_workdir_path(
&info->data, info->repo, file->path)) < 0)
return error;
/* if path is not a regular file, just skip this item */
if (!git_path_isfile(info->data.ptr))
return 0;
/* TODO: apply wd-to-odb filters to file data if necessary */
error = opts->metric->file_signature(
&cache[info->idx], info->file,
info->data.ptr, opts->metric->payload);
} else {
/* if we didn't initially know the size, we might have an odb_obj
* around from earlier, so convert that, otherwise load the blob now
*/
if (info->odb_obj != NULL)
error = git_object__from_odb_object(
(git_object **)&info->blob, info->repo,
info->odb_obj, GIT_OBJECT_BLOB);
else
error = git_blob_lookup(&info->blob, info->repo, &file->id);
if (error < 0) {
/* if lookup fails, just skip this item in similarity calc */
git_error_clear();
} else {
size_t sz;
/* index size may not be actual blob size if filtered */
if (file->size != git_blob_rawsize(info->blob))
file->size = git_blob_rawsize(info->blob);
sz = git__is_sizet(file->size) ? (size_t)file->size : (size_t)-1;
error = opts->metric->buffer_signature(
&cache[info->idx], info->file,
git_blob_rawcontent(info->blob), sz, opts->metric->payload);
}
}
return error;
}
static void similarity_unload(similarity_info *info)
{
if (info->odb_obj)
git_odb_object_free(info->odb_obj);
if (info->blob)
git_blob_free(info->blob);
else
git_buf_dispose(&info->data);
}
#define FLAG_SET(opts,flag_name) (((opts)->flags & flag_name) != 0)
/* - score < 0 means files cannot be compared
* - score >= 100 means files are exact match
* - score == 0 means files are completely different
*/
static int similarity_measure(
int *score,
git_diff *diff,
const git_diff_find_options *opts,
void **cache,
size_t a_idx,
size_t b_idx)
{
git_diff_file *a_file = similarity_get_file(diff, a_idx);
git_diff_file *b_file = similarity_get_file(diff, b_idx);
bool exact_match = FLAG_SET(opts, GIT_DIFF_FIND_EXACT_MATCH_ONLY);
int error = 0;
similarity_info a_info, b_info;
*score = -1;
/* don't try to compare things that aren't files */
if (!GIT_MODE_ISBLOB(a_file->mode) || !GIT_MODE_ISBLOB(b_file->mode))
return 0;
/* if exact match is requested, force calculation of missing OIDs now */
if (exact_match) {
if (git_oid_is_zero(&a_file->id) &&
diff->old_src == GIT_ITERATOR_WORKDIR &&
!git_diff__oid_for_file(&a_file->id,
diff, a_file->path, a_file->mode, a_file->size))
a_file->flags |= GIT_DIFF_FLAG_VALID_ID;
if (git_oid_is_zero(&b_file->id) &&
diff->new_src == GIT_ITERATOR_WORKDIR &&
!git_diff__oid_for_file(&b_file->id,
diff, b_file->path, b_file->mode, b_file->size))
b_file->flags |= GIT_DIFF_FLAG_VALID_ID;
}
/* check OID match as a quick test */
if (git_oid__cmp(&a_file->id, &b_file->id) == 0) {
*score = 100;
return 0;
}
/* don't calculate signatures if we are doing exact match */
if (exact_match) {
*score = 0;
return 0;
}
memset(&a_info, 0, sizeof(a_info));
memset(&b_info, 0, sizeof(b_info));
/* set up similarity data (will try to update missing file sizes) */
if (!cache[a_idx] && (error = similarity_init(&a_info, diff, a_idx)) < 0)
return error;
if (!cache[b_idx] && (error = similarity_init(&b_info, diff, b_idx)) < 0)
goto cleanup;
/* check if file sizes are nowhere near each other */
if (a_file->size > 127 &&
b_file->size > 127 &&
(a_file->size > (b_file->size << 3) ||
b_file->size > (a_file->size << 3)))
goto cleanup;
/* update signature cache if needed */
if (!cache[a_idx]) {
if ((error = similarity_sig(&a_info, opts, cache)) < 0)
goto cleanup;
}
if (!cache[b_idx]) {
if ((error = similarity_sig(&b_info, opts, cache)) < 0)
goto cleanup;
}
/* calculate similarity provided that the metric choose to process
* both the a and b files (some may not if file is too big, etc).
*/
if (cache[a_idx] && cache[b_idx])
error = opts->metric->similarity(
score, cache[a_idx], cache[b_idx], opts->metric->payload);
cleanup:
similarity_unload(&a_info);
similarity_unload(&b_info);
return error;
}
static int calc_self_similarity(
git_diff *diff,
const git_diff_find_options *opts,
size_t delta_idx,
void **cache)
{
int error, similarity = -1;
git_diff_delta *delta = GIT_VECTOR_GET(&diff->deltas, delta_idx);
if ((delta->flags & GIT_DIFF_FLAG__HAS_SELF_SIMILARITY) != 0)
return 0;
error = similarity_measure(
&similarity, diff, opts, cache, 2 * delta_idx, 2 * delta_idx + 1);
if (error < 0)
return error;
if (similarity >= 0) {
delta->similarity = (uint16_t)similarity;
delta->flags |= GIT_DIFF_FLAG__HAS_SELF_SIMILARITY;
}
return 0;
}
static bool is_rename_target(
git_diff *diff,
const git_diff_find_options *opts,
size_t delta_idx,
void **cache)
{
git_diff_delta *delta = GIT_VECTOR_GET(&diff->deltas, delta_idx);
/* skip things that aren't plain blobs */
if (!GIT_MODE_ISBLOB(delta->new_file.mode))
return false;
/* only consider ADDED, RENAMED, COPIED, and split MODIFIED as
* targets; maybe include UNTRACKED if requested.
*/
switch (delta->status) {
case GIT_DELTA_UNMODIFIED:
case GIT_DELTA_DELETED:
case GIT_DELTA_IGNORED:
case GIT_DELTA_CONFLICTED:
return false;
case GIT_DELTA_MODIFIED:
if (!FLAG_SET(opts, GIT_DIFF_FIND_REWRITES) &&
!FLAG_SET(opts, GIT_DIFF_FIND_RENAMES_FROM_REWRITES))
return false;
if (calc_self_similarity(diff, opts, delta_idx, cache) < 0)
return false;
if (FLAG_SET(opts, GIT_DIFF_BREAK_REWRITES) &&
delta->similarity < opts->break_rewrite_threshold) {
delta->flags |= GIT_DIFF_FLAG__TO_SPLIT;
break;
}
if (FLAG_SET(opts, GIT_DIFF_FIND_RENAMES_FROM_REWRITES) &&
delta->similarity < opts->rename_from_rewrite_threshold) {
delta->flags |= GIT_DIFF_FLAG__TO_SPLIT;
break;
}
return false;
case GIT_DELTA_UNTRACKED:
if (!FLAG_SET(opts, GIT_DIFF_FIND_FOR_UNTRACKED))
return false;
break;
default: /* all other status values should be checked */
break;
}
delta->flags |= GIT_DIFF_FLAG__IS_RENAME_TARGET;
return true;
}
static bool is_rename_source(
git_diff *diff,
const git_diff_find_options *opts,
size_t delta_idx,
void **cache)
{
git_diff_delta *delta = GIT_VECTOR_GET(&diff->deltas, delta_idx);
/* skip things that aren't blobs */
if (!GIT_MODE_ISBLOB(delta->old_file.mode))
return false;
switch (delta->status) {
case GIT_DELTA_ADDED:
case GIT_DELTA_UNTRACKED:
case GIT_DELTA_UNREADABLE:
case GIT_DELTA_IGNORED:
case GIT_DELTA_CONFLICTED:
return false;
case GIT_DELTA_DELETED:
case GIT_DELTA_TYPECHANGE:
break;
case GIT_DELTA_UNMODIFIED:
if (!FLAG_SET(opts, GIT_DIFF_FIND_COPIES_FROM_UNMODIFIED))
return false;
if (FLAG_SET(opts, GIT_DIFF_FIND_REMOVE_UNMODIFIED))
delta->flags |= GIT_DIFF_FLAG__TO_DELETE;
break;
default: /* MODIFIED, RENAMED, COPIED */
/* if we're finding copies, this could be a source */
if (FLAG_SET(opts, GIT_DIFF_FIND_COPIES))
break;
/* otherwise, this is only a source if we can split it */
if (!FLAG_SET(opts, GIT_DIFF_FIND_REWRITES) &&
!FLAG_SET(opts, GIT_DIFF_FIND_RENAMES_FROM_REWRITES))
return false;
if (calc_self_similarity(diff, opts, delta_idx, cache) < 0)
return false;
if (FLAG_SET(opts, GIT_DIFF_BREAK_REWRITES) &&
delta->similarity < opts->break_rewrite_threshold) {
delta->flags |= GIT_DIFF_FLAG__TO_SPLIT;
break;
}
if (FLAG_SET(opts, GIT_DIFF_FIND_RENAMES_FROM_REWRITES) &&
delta->similarity < opts->rename_from_rewrite_threshold)
break;
return false;
}
delta->flags |= GIT_DIFF_FLAG__IS_RENAME_SOURCE;
return true;
}
GIT_INLINE(bool) delta_is_split(git_diff_delta *delta)
{
return (delta->status == GIT_DELTA_TYPECHANGE ||
(delta->flags & GIT_DIFF_FLAG__TO_SPLIT) != 0);
}
GIT_INLINE(bool) delta_is_new_only(git_diff_delta *delta)
{
return (delta->status == GIT_DELTA_ADDED ||
delta->status == GIT_DELTA_UNTRACKED ||
delta->status == GIT_DELTA_UNREADABLE ||
delta->status == GIT_DELTA_IGNORED);
}
GIT_INLINE(void) delta_make_rename(
git_diff_delta *to, const git_diff_delta *from, uint16_t similarity)
{
to->status = GIT_DELTA_RENAMED;
to->similarity = similarity;
to->nfiles = 2;
memcpy(&to->old_file, &from->old_file, sizeof(to->old_file));
to->flags &= ~GIT_DIFF_FLAG__TO_SPLIT;
}
typedef struct {
size_t idx;
uint16_t similarity;
} diff_find_match;
int git_diff_find_similar(
git_diff *diff,
const git_diff_find_options *given_opts)
{
size_t s, t;
int error = 0, result;
uint16_t similarity;
git_diff_delta *src, *tgt;
git_diff_find_options opts = GIT_DIFF_FIND_OPTIONS_INIT;
size_t num_deltas, num_srcs = 0, num_tgts = 0;
size_t tried_srcs = 0, tried_tgts = 0;
size_t num_rewrites = 0, num_updates = 0, num_bumped = 0;
size_t sigcache_size;
void **sigcache = NULL; /* cache of similarity metric file signatures */
diff_find_match *tgt2src = NULL;
diff_find_match *src2tgt = NULL;
diff_find_match *tgt2src_copy = NULL;
diff_find_match *best_match;
git_diff_file swap;
GIT_ASSERT_ARG(diff);
if ((error = normalize_find_opts(diff, &opts, given_opts)) < 0)
return error;
num_deltas = diff->deltas.length;
/* TODO: maybe abort if deltas.length > rename_limit ??? */
if (!num_deltas || !git__is_uint32(num_deltas))
goto cleanup;
/* No flags set; nothing to do */
if ((opts.flags & GIT_DIFF_FIND_ALL) == 0)
goto cleanup;
GIT_ERROR_CHECK_ALLOC_MULTIPLY(&sigcache_size, num_deltas, 2);
sigcache = git__calloc(sigcache_size, sizeof(void *));
GIT_ERROR_CHECK_ALLOC(sigcache);
/* Label rename sources and targets
*
* This will also set self-similarity scores for MODIFIED files and
* mark them for splitting if break-rewrites is enabled
*/
git_vector_foreach(&diff->deltas, t, tgt) {
if (is_rename_source(diff, &opts, t, sigcache))
++num_srcs;
if (is_rename_target(diff, &opts, t, sigcache))
++num_tgts;
if ((tgt->flags & GIT_DIFF_FLAG__TO_SPLIT) != 0)
num_rewrites++;
}
/* if there are no candidate srcs or tgts, we're done */
if (!num_srcs || !num_tgts)
goto cleanup;
src2tgt = git__calloc(num_deltas, sizeof(diff_find_match));
GIT_ERROR_CHECK_ALLOC(src2tgt);
tgt2src = git__calloc(num_deltas, sizeof(diff_find_match));
GIT_ERROR_CHECK_ALLOC(tgt2src);
if (FLAG_SET(&opts, GIT_DIFF_FIND_COPIES)) {
tgt2src_copy = git__calloc(num_deltas, sizeof(diff_find_match));
GIT_ERROR_CHECK_ALLOC(tgt2src_copy);
}
/*
* Find best-fit matches for rename / copy candidates
*/
find_best_matches:
tried_tgts = num_bumped = 0;
git_vector_foreach(&diff->deltas, t, tgt) {
/* skip things that are not rename targets */
if ((tgt->flags & GIT_DIFF_FLAG__IS_RENAME_TARGET) == 0)
continue;
tried_srcs = 0;
git_vector_foreach(&diff->deltas, s, src) {
/* skip things that are not rename sources */
if ((src->flags & GIT_DIFF_FLAG__IS_RENAME_SOURCE) == 0)
continue;
/* calculate similarity for this pair and find best match */
if (s == t)
result = -1; /* don't measure self-similarity here */
else if ((error = similarity_measure(
&result, diff, &opts, sigcache, 2 * s, 2 * t + 1)) < 0)
goto cleanup;
if (result < 0)
continue;
similarity = (uint16_t)result;
/* is this a better rename? */
if (tgt2src[t].similarity < similarity &&
src2tgt[s].similarity < similarity)
{
/* eject old mapping */
if (src2tgt[s].similarity > 0) {
tgt2src[src2tgt[s].idx].similarity = 0;
num_bumped++;
}
if (tgt2src[t].similarity > 0) {
src2tgt[tgt2src[t].idx].similarity = 0;
num_bumped++;
}
/* write new mapping */
tgt2src[t].idx = s;
tgt2src[t].similarity = similarity;
src2tgt[s].idx = t;
src2tgt[s].similarity = similarity;
}
/* keep best absolute match for copies */
if (tgt2src_copy != NULL &&
tgt2src_copy[t].similarity < similarity)
{
tgt2src_copy[t].idx = s;
tgt2src_copy[t].similarity = similarity;
}
if (++tried_srcs >= num_srcs)
break;
/* cap on maximum targets we'll examine (per "tgt" file) */
if (tried_srcs > opts.rename_limit)
break;
}
if (++tried_tgts >= num_tgts)
break;
}
if (num_bumped > 0) /* try again if we bumped some items */
goto find_best_matches;
/*
* Rewrite the diffs with renames / copies
*/
git_vector_foreach(&diff->deltas, t, tgt) {
/* skip things that are not rename targets */
if ((tgt->flags & GIT_DIFF_FLAG__IS_RENAME_TARGET) == 0)
continue;
/* check if this delta was the target of a similarity */
if (tgt2src[t].similarity)
best_match = &tgt2src[t];
else if (tgt2src_copy && tgt2src_copy[t].similarity)
best_match = &tgt2src_copy[t];
else
continue;
s = best_match->idx;
src = GIT_VECTOR_GET(&diff->deltas, s);
/* possible scenarios:
* 1. from DELETE to ADD/UNTRACK/IGNORE = RENAME
* 2. from DELETE to SPLIT/TYPECHANGE = RENAME + DELETE
* 3. from SPLIT/TYPECHANGE to ADD/UNTRACK/IGNORE = ADD + RENAME
* 4. from SPLIT/TYPECHANGE to SPLIT/TYPECHANGE = RENAME + SPLIT
* 5. from OTHER to ADD/UNTRACK/IGNORE = OTHER + COPY
*/
if (src->status == GIT_DELTA_DELETED) {
if (delta_is_new_only(tgt)) {
if (best_match->similarity < opts.rename_threshold)
continue;
delta_make_rename(tgt, src, best_match->similarity);
src->flags |= GIT_DIFF_FLAG__TO_DELETE;
num_rewrites++;
} else {
GIT_ASSERT(delta_is_split(tgt));
if (best_match->similarity < opts.rename_from_rewrite_threshold)
continue;
memcpy(&swap, &tgt->old_file, sizeof(swap));
delta_make_rename(tgt, src, best_match->similarity);
num_rewrites--;
GIT_ASSERT(src->status == GIT_DELTA_DELETED);
memcpy(&src->old_file, &swap, sizeof(src->old_file));
memset(&src->new_file, 0, sizeof(src->new_file));
src->new_file.path = src->old_file.path;
src->new_file.flags |= GIT_DIFF_FLAG_VALID_ID;
num_updates++;
if (src2tgt[t].similarity > 0 && src2tgt[t].idx > t) {
/* what used to be at src t is now at src s */
tgt2src[src2tgt[t].idx].idx = s;
}
}
}
else if (delta_is_split(src)) {
if (delta_is_new_only(tgt)) {
if (best_match->similarity < opts.rename_threshold)
continue;
delta_make_rename(tgt, src, best_match->similarity);
src->status = (diff->new_src == GIT_ITERATOR_WORKDIR) ?
GIT_DELTA_UNTRACKED : GIT_DELTA_ADDED;
src->nfiles = 1;
memset(&src->old_file, 0, sizeof(src->old_file));
src->old_file.path = src->new_file.path;
src->old_file.flags |= GIT_DIFF_FLAG_VALID_ID;
src->flags &= ~GIT_DIFF_FLAG__TO_SPLIT;
num_rewrites--;
num_updates++;
} else {
GIT_ASSERT(delta_is_split(src));
if (best_match->similarity < opts.rename_from_rewrite_threshold)
continue;
memcpy(&swap, &tgt->old_file, sizeof(swap));
delta_make_rename(tgt, src, best_match->similarity);
num_rewrites--;
num_updates++;
memcpy(&src->old_file, &swap, sizeof(src->old_file));
/* if we've just swapped the new element into the correct
* place, clear the SPLIT and RENAME_TARGET flags
*/
if (tgt2src[s].idx == t &&
tgt2src[s].similarity >
opts.rename_from_rewrite_threshold) {
src->status = GIT_DELTA_RENAMED;
src->similarity = tgt2src[s].similarity;
tgt2src[s].similarity = 0;
src->flags &= ~(GIT_DIFF_FLAG__TO_SPLIT | GIT_DIFF_FLAG__IS_RENAME_TARGET);
num_rewrites--;
}
/* otherwise, if we just overwrote a source, update mapping */
else if (src2tgt[t].similarity > 0 && src2tgt[t].idx > t) {
/* what used to be at src t is now at src s */
tgt2src[src2tgt[t].idx].idx = s;
}
num_updates++;
}
}
else if (FLAG_SET(&opts, GIT_DIFF_FIND_COPIES)) {
if (tgt2src_copy[t].similarity < opts.copy_threshold)
continue;
/* always use best possible source for copy */
best_match = &tgt2src_copy[t];
src = GIT_VECTOR_GET(&diff->deltas, best_match->idx);
if (delta_is_split(tgt)) {
error = insert_delete_side_of_split(diff, &diff->deltas, tgt);
if (error < 0)
goto cleanup;
num_rewrites--;
}
if (!delta_is_split(tgt) && !delta_is_new_only(tgt))
continue;
tgt->status = GIT_DELTA_COPIED;
tgt->similarity = best_match->similarity;
tgt->nfiles = 2;
memcpy(&tgt->old_file, &src->old_file, sizeof(tgt->old_file));
tgt->flags &= ~GIT_DIFF_FLAG__TO_SPLIT;
num_updates++;
}
}
/*
* Actually split and delete entries as needed
*/
if (num_rewrites > 0 || num_updates > 0)
error = apply_splits_and_deletes(
diff, diff->deltas.length - num_rewrites,
FLAG_SET(&opts, GIT_DIFF_BREAK_REWRITES) &&
!FLAG_SET(&opts, GIT_DIFF_BREAK_REWRITES_FOR_RENAMES_ONLY));
cleanup:
git__free(tgt2src);
git__free(src2tgt);
git__free(tgt2src_copy);
if (sigcache) {
for (t = 0; t < num_deltas * 2; ++t) {
if (sigcache[t] != NULL)
opts.metric->free_signature(sigcache[t], opts.metric->payload);
}
git__free(sigcache);
}
if (!given_opts || !given_opts->metric)
git__free(opts.metric);
return error;
}
#undef FLAG_SET
|
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_file.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_file_h__
#define INCLUDE_diff_file_h__
#include "common.h"
#include "diff.h"
#include "diff_driver.h"
#include "map.h"
/* expanded information for one side of a delta */
typedef struct {
git_repository *repo;
git_diff_file *file;
git_diff_driver *driver;
uint32_t flags;
uint32_t opts_flags;
git_object_size_t opts_max_size;
git_iterator_t src;
const git_blob *blob;
git_map map;
} git_diff_file_content;
extern int git_diff_file_content__init_from_diff(
git_diff_file_content *fc,
git_diff *diff,
git_diff_delta *delta,
bool use_old);
typedef struct {
const git_blob *blob;
const void *buf;
size_t buflen;
const char *as_path;
} git_diff_file_content_src;
#define GIT_DIFF_FILE_CONTENT_SRC__BLOB(BLOB,PATH) { (BLOB),NULL,0,(PATH) }
#define GIT_DIFF_FILE_CONTENT_SRC__BUF(BUF,LEN,PATH) { NULL,(BUF),(LEN),(PATH) }
extern int git_diff_file_content__init_from_src(
git_diff_file_content *fc,
git_repository *repo,
const git_diff_options *opts,
const git_diff_file_content_src *src,
git_diff_file *as_file);
/* this loads the blob/file-on-disk as needed */
extern int git_diff_file_content__load(
git_diff_file_content *fc,
git_diff_options *diff_opts);
/* this releases the blob/file-in-memory */
extern void git_diff_file_content__unload(git_diff_file_content *fc);
/* this unloads and also releases any other resources */
extern void git_diff_file_content__clear(git_diff_file_content *fc);
#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/transaction.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 "transaction.h"
#include "repository.h"
#include "strmap.h"
#include "refdb.h"
#include "pool.h"
#include "reflog.h"
#include "signature.h"
#include "config.h"
#include "git2/transaction.h"
#include "git2/signature.h"
#include "git2/sys/refs.h"
#include "git2/sys/refdb_backend.h"
typedef enum {
TRANSACTION_NONE,
TRANSACTION_REFS,
TRANSACTION_CONFIG,
} transaction_t;
typedef struct {
const char *name;
void *payload;
git_reference_t ref_type;
union {
git_oid id;
char *symbolic;
} target;
git_reflog *reflog;
const char *message;
git_signature *sig;
unsigned int committed :1,
remove :1;
} transaction_node;
struct git_transaction {
transaction_t type;
git_repository *repo;
git_refdb *db;
git_config *cfg;
git_strmap *locks;
git_pool pool;
};
int git_transaction_config_new(git_transaction **out, git_config *cfg)
{
git_transaction *tx;
GIT_ASSERT_ARG(out);
GIT_ASSERT_ARG(cfg);
tx = git__calloc(1, sizeof(git_transaction));
GIT_ERROR_CHECK_ALLOC(tx);
tx->type = TRANSACTION_CONFIG;
tx->cfg = cfg;
*out = tx;
return 0;
}
int git_transaction_new(git_transaction **out, git_repository *repo)
{
int error;
git_pool pool;
git_transaction *tx = NULL;
GIT_ASSERT_ARG(out);
GIT_ASSERT_ARG(repo);
if ((error = git_pool_init(&pool, 1)) < 0)
goto on_error;
tx = git_pool_mallocz(&pool, sizeof(git_transaction));
if (!tx) {
error = -1;
goto on_error;
}
if ((error = git_strmap_new(&tx->locks)) < 0) {
error = -1;
goto on_error;
}
if ((error = git_repository_refdb(&tx->db, repo)) < 0)
goto on_error;
tx->type = TRANSACTION_REFS;
memcpy(&tx->pool, &pool, sizeof(git_pool));
tx->repo = repo;
*out = tx;
return 0;
on_error:
git_pool_clear(&pool);
return error;
}
int git_transaction_lock_ref(git_transaction *tx, const char *refname)
{
int error;
transaction_node *node;
GIT_ASSERT_ARG(tx);
GIT_ASSERT_ARG(refname);
node = git_pool_mallocz(&tx->pool, sizeof(transaction_node));
GIT_ERROR_CHECK_ALLOC(node);
node->name = git_pool_strdup(&tx->pool, refname);
GIT_ERROR_CHECK_ALLOC(node->name);
if ((error = git_refdb_lock(&node->payload, tx->db, refname)) < 0)
return error;
if ((error = git_strmap_set(tx->locks, node->name, node)) < 0)
goto cleanup;
return 0;
cleanup:
git_refdb_unlock(tx->db, node->payload, false, false, NULL, NULL, NULL);
return error;
}
static int find_locked(transaction_node **out, git_transaction *tx, const char *refname)
{
transaction_node *node;
if ((node = git_strmap_get(tx->locks, refname)) == NULL) {
git_error_set(GIT_ERROR_REFERENCE, "the specified reference is not locked");
return GIT_ENOTFOUND;
}
*out = node;
return 0;
}
static int copy_common(transaction_node *node, git_transaction *tx, const git_signature *sig, const char *msg)
{
if (sig && git_signature__pdup(&node->sig, sig, &tx->pool) < 0)
return -1;
if (!node->sig) {
git_signature *tmp;
int error;
if (git_reference__log_signature(&tmp, tx->repo) < 0)
return -1;
/* make sure the sig we use is in our pool */
error = git_signature__pdup(&node->sig, tmp, &tx->pool);
git_signature_free(tmp);
if (error < 0)
return error;
}
if (msg) {
node->message = git_pool_strdup(&tx->pool, msg);
GIT_ERROR_CHECK_ALLOC(node->message);
}
return 0;
}
int git_transaction_set_target(git_transaction *tx, const char *refname, const git_oid *target, const git_signature *sig, const char *msg)
{
int error;
transaction_node *node;
GIT_ASSERT_ARG(tx);
GIT_ASSERT_ARG(refname);
GIT_ASSERT_ARG(target);
if ((error = find_locked(&node, tx, refname)) < 0)
return error;
if ((error = copy_common(node, tx, sig, msg)) < 0)
return error;
git_oid_cpy(&node->target.id, target);
node->ref_type = GIT_REFERENCE_DIRECT;
return 0;
}
int git_transaction_set_symbolic_target(git_transaction *tx, const char *refname, const char *target, const git_signature *sig, const char *msg)
{
int error;
transaction_node *node;
GIT_ASSERT_ARG(tx);
GIT_ASSERT_ARG(refname);
GIT_ASSERT_ARG(target);
if ((error = find_locked(&node, tx, refname)) < 0)
return error;
if ((error = copy_common(node, tx, sig, msg)) < 0)
return error;
node->target.symbolic = git_pool_strdup(&tx->pool, target);
GIT_ERROR_CHECK_ALLOC(node->target.symbolic);
node->ref_type = GIT_REFERENCE_SYMBOLIC;
return 0;
}
int git_transaction_remove(git_transaction *tx, const char *refname)
{
int error;
transaction_node *node;
if ((error = find_locked(&node, tx, refname)) < 0)
return error;
node->remove = true;
node->ref_type = GIT_REFERENCE_DIRECT; /* the id will be ignored */
return 0;
}
static int dup_reflog(git_reflog **out, const git_reflog *in, git_pool *pool)
{
git_reflog *reflog;
git_reflog_entry *entries;
size_t len, i;
reflog = git_pool_mallocz(pool, sizeof(git_reflog));
GIT_ERROR_CHECK_ALLOC(reflog);
reflog->ref_name = git_pool_strdup(pool, in->ref_name);
GIT_ERROR_CHECK_ALLOC(reflog->ref_name);
len = in->entries.length;
reflog->entries.length = len;
reflog->entries.contents = git_pool_mallocz(pool, len * sizeof(void *));
GIT_ERROR_CHECK_ALLOC(reflog->entries.contents);
entries = git_pool_mallocz(pool, len * sizeof(git_reflog_entry));
GIT_ERROR_CHECK_ALLOC(entries);
for (i = 0; i < len; i++) {
const git_reflog_entry *src;
git_reflog_entry *tgt;
tgt = &entries[i];
reflog->entries.contents[i] = tgt;
src = git_vector_get(&in->entries, i);
git_oid_cpy(&tgt->oid_old, &src->oid_old);
git_oid_cpy(&tgt->oid_cur, &src->oid_cur);
tgt->msg = git_pool_strdup(pool, src->msg);
GIT_ERROR_CHECK_ALLOC(tgt->msg);
if (git_signature__pdup(&tgt->committer, src->committer, pool) < 0)
return -1;
}
*out = reflog;
return 0;
}
int git_transaction_set_reflog(git_transaction *tx, const char *refname, const git_reflog *reflog)
{
int error;
transaction_node *node;
GIT_ASSERT_ARG(tx);
GIT_ASSERT_ARG(refname);
GIT_ASSERT_ARG(reflog);
if ((error = find_locked(&node, tx, refname)) < 0)
return error;
if ((error = dup_reflog(&node->reflog, reflog, &tx->pool)) < 0)
return error;
return 0;
}
static int update_target(git_refdb *db, transaction_node *node)
{
git_reference *ref;
int error, update_reflog;
if (node->ref_type == GIT_REFERENCE_DIRECT) {
ref = git_reference__alloc(node->name, &node->target.id, NULL);
} else if (node->ref_type == GIT_REFERENCE_SYMBOLIC) {
ref = git_reference__alloc_symbolic(node->name, node->target.symbolic);
} else {
abort();
}
GIT_ERROR_CHECK_ALLOC(ref);
update_reflog = node->reflog == NULL;
if (node->remove) {
error = git_refdb_unlock(db, node->payload, 2, false, ref, NULL, NULL);
} else if (node->ref_type == GIT_REFERENCE_DIRECT) {
error = git_refdb_unlock(db, node->payload, true, update_reflog, ref, node->sig, node->message);
} else if (node->ref_type == GIT_REFERENCE_SYMBOLIC) {
error = git_refdb_unlock(db, node->payload, true, update_reflog, ref, node->sig, node->message);
} else {
abort();
}
git_reference_free(ref);
node->committed = true;
return error;
}
int git_transaction_commit(git_transaction *tx)
{
transaction_node *node;
int error = 0;
GIT_ASSERT_ARG(tx);
if (tx->type == TRANSACTION_CONFIG) {
error = git_config_unlock(tx->cfg, true);
tx->cfg = NULL;
return error;
}
git_strmap_foreach_value(tx->locks, node, {
if (node->reflog) {
if ((error = tx->db->backend->reflog_write(tx->db->backend, node->reflog)) < 0)
return error;
}
if (node->ref_type == GIT_REFERENCE_INVALID) {
/* ref was locked but not modified */
if ((error = git_refdb_unlock(tx->db, node->payload, false, false, NULL, NULL, NULL)) < 0) {
return error;
}
node->committed = true;
} else {
if ((error = update_target(tx->db, node)) < 0)
return error;
}
});
return 0;
}
void git_transaction_free(git_transaction *tx)
{
transaction_node *node;
git_pool pool;
if (!tx)
return;
if (tx->type == TRANSACTION_CONFIG) {
if (tx->cfg) {
git_config_unlock(tx->cfg, false);
git_config_free(tx->cfg);
}
git__free(tx);
return;
}
/* start by unlocking the ones we've left hanging, if any */
git_strmap_foreach_value(tx->locks, node, {
if (node->committed)
continue;
git_refdb_unlock(tx->db, node->payload, false, false, NULL, NULL, NULL);
});
git_refdb_free(tx->db);
git_strmap_free(tx->locks);
/* tx is inside the pool, so we need to extract the data */
memcpy(&pool, &tx->pool, sizeof(git_pool));
git_pool_clear(&pool);
}
|
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.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_merge_h__
#define INCLUDE_merge_h__
#include "common.h"
#include "vector.h"
#include "commit_list.h"
#include "pool.h"
#include "iterator.h"
#include "git2/types.h"
#include "git2/merge.h"
#include "git2/sys/merge.h"
#define GIT_MERGE_MSG_FILE "MERGE_MSG"
#define GIT_MERGE_MODE_FILE "MERGE_MODE"
#define GIT_MERGE_FILE_MODE 0666
#define GIT_MERGE_DEFAULT_RENAME_THRESHOLD 50
#define GIT_MERGE_DEFAULT_TARGET_LIMIT 1000
/** Internal merge flags. */
enum {
/** The merge is for a virtual base in a recursive merge. */
GIT_MERGE__VIRTUAL_BASE = (1 << 31),
};
enum {
/** Accept the conflict file, staging it as the merge result. */
GIT_MERGE_FILE_FAVOR__CONFLICTED = 4,
};
/** Types of changes when files are merged from branch to branch. */
typedef enum {
/* No conflict - a change only occurs in one branch. */
GIT_MERGE_DIFF_NONE = 0,
/* Occurs when a file is modified in both branches. */
GIT_MERGE_DIFF_BOTH_MODIFIED = (1 << 0),
/* Occurs when a file is added in both branches. */
GIT_MERGE_DIFF_BOTH_ADDED = (1 << 1),
/* Occurs when a file is deleted in both branches. */
GIT_MERGE_DIFF_BOTH_DELETED = (1 << 2),
/* Occurs when a file is modified in one branch and deleted in the other. */
GIT_MERGE_DIFF_MODIFIED_DELETED = (1 << 3),
/* Occurs when a file is renamed in one branch and modified in the other. */
GIT_MERGE_DIFF_RENAMED_MODIFIED = (1 << 4),
/* Occurs when a file is renamed in one branch and deleted in the other. */
GIT_MERGE_DIFF_RENAMED_DELETED = (1 << 5),
/* Occurs when a file is renamed in one branch and a file with the same
* name is added in the other. Eg, A->B and new file B. Core git calls
* this a "rename/delete". */
GIT_MERGE_DIFF_RENAMED_ADDED = (1 << 6),
/* Occurs when both a file is renamed to the same name in the ours and
* theirs branches. Eg, A->B and A->B in both. Automergeable. */
GIT_MERGE_DIFF_BOTH_RENAMED = (1 << 7),
/* Occurs when a file is renamed to different names in the ours and theirs
* branches. Eg, A->B and A->C. */
GIT_MERGE_DIFF_BOTH_RENAMED_1_TO_2 = (1 << 8),
/* Occurs when two files are renamed to the same name in the ours and
* theirs branches. Eg, A->C and B->C. */
GIT_MERGE_DIFF_BOTH_RENAMED_2_TO_1 = (1 << 9),
/* Occurs when an item at a path in one branch is a directory, and an
* item at the same path in a different branch is a file. */
GIT_MERGE_DIFF_DIRECTORY_FILE = (1 << 10),
/* The child of a folder that is in a directory/file conflict. */
GIT_MERGE_DIFF_DF_CHILD = (1 << 11),
} git_merge_diff_t;
typedef struct {
git_repository *repo;
git_pool pool;
/* Vector of git_index_entry that represent the merged items that
* have been staged, either because only one side changed, or because
* the two changes were non-conflicting and mergeable. These items
* will be written as staged entries in the main index.
*/
git_vector staged;
/* Vector of git_merge_diff entries that represent the conflicts that
* have not been automerged. These items will be written to high-stage
* entries in the main index.
*/
git_vector conflicts;
/* Vector of git_merge_diff that have been automerged. These items
* will be written to the REUC when the index is produced.
*/
git_vector resolved;
} git_merge_diff_list;
/**
* Description of changes to one file across three trees.
*/
typedef struct {
git_merge_diff_t type;
git_index_entry ancestor_entry;
git_index_entry our_entry;
git_delta_t our_status;
git_index_entry their_entry;
git_delta_t their_status;
} git_merge_diff;
int git_merge__bases_many(
git_commit_list **out,
git_revwalk *walk,
git_commit_list_node *one,
git_vector *twos,
uint32_t minimum_generation);
/*
* Three-way tree differencing
*/
git_merge_diff_list *git_merge_diff_list__alloc(git_repository *repo);
int git_merge_diff_list__find_differences(
git_merge_diff_list *merge_diff_list,
git_iterator *ancestor_iterator,
git_iterator *ours_iter,
git_iterator *theirs_iter);
int git_merge_diff_list__find_renames(git_repository *repo, git_merge_diff_list *merge_diff_list, const git_merge_options *opts);
void git_merge_diff_list__free(git_merge_diff_list *diff_list);
/* Merge metadata setup */
int git_merge__setup(
git_repository *repo,
const git_annotated_commit *our_head,
const git_annotated_commit *heads[],
size_t heads_len);
int git_merge__iterators(
git_index **out,
git_repository *repo,
git_iterator *ancestor_iter,
git_iterator *our_iter,
git_iterator *their_iter,
const git_merge_options *given_opts);
int git_merge__check_result(git_repository *repo, git_index *index_new);
int git_merge__append_conflicts_to_merge_msg(git_repository *repo, git_index *index);
/* Merge files */
GIT_INLINE(const char *) git_merge_file__best_path(
const char *ancestor,
const char *ours,
const char *theirs)
{
if (!ancestor) {
if (ours && theirs && strcmp(ours, theirs) == 0)
return ours;
return NULL;
}
if (ours && strcmp(ancestor, ours) == 0)
return theirs;
else if(theirs && strcmp(ancestor, theirs) == 0)
return ours;
return NULL;
}
GIT_INLINE(uint32_t) git_merge_file__best_mode(
uint32_t ancestor, uint32_t ours, uint32_t theirs)
{
/*
* If ancestor didn't exist and either ours or theirs is executable,
* assume executable. Otherwise, if any mode changed from the ancestor,
* use that one.
*/
if (!ancestor) {
if (ours == GIT_FILEMODE_BLOB_EXECUTABLE ||
theirs == GIT_FILEMODE_BLOB_EXECUTABLE)
return GIT_FILEMODE_BLOB_EXECUTABLE;
return GIT_FILEMODE_BLOB;
} else if (ours && theirs) {
if (ancestor == ours)
return theirs;
return ours;
}
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/oidmap.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_oidmap_h__
#define INCLUDE_oidmap_h__
#include "common.h"
#include "git2/oid.h"
/** A map with `git_oid`s as key. */
typedef struct kh_oid_s git_oidmap;
/**
* Allocate a new OID map.
*
* @param out Pointer to the map that shall be allocated.
* @return 0 on success, an error code if allocation has failed.
*/
int git_oidmap_new(git_oidmap **out);
/**
* Free memory associated with the map.
*
* Note that this function will _not_ free values added to this
* map.
*
* @param map Pointer to the map that is to be free'd. May be
* `NULL`.
*/
void git_oidmap_free(git_oidmap *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_oidmap_clear(git_oidmap *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_oidmap_size(git_oidmap *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_oidmap_get(git_oidmap *map, const git_oid *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_oidmap_set(git_oidmap *map, const git_oid *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_oidmap_delete(git_oidmap *map, const git_oid *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_oidmap_exists(git_oidmap *map, const git_oid *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_oidmap_iterate(void **value, git_oidmap *map, size_t *iter, const git_oid **key);
#define git_oidmap_foreach_value(h, vvar, code) { size_t __i = 0; \
while (git_oidmap_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/repository.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_repository_h__
#define INCLUDE_repository_h__
#include "common.h"
#include "git2/common.h"
#include "git2/oid.h"
#include "git2/odb.h"
#include "git2/repository.h"
#include "git2/object.h"
#include "git2/config.h"
#include "array.h"
#include "cache.h"
#include "refs.h"
#include "buffer.h"
#include "object.h"
#include "attrcache.h"
#include "submodule.h"
#include "diff_driver.h"
#define DOT_GIT ".git"
#define GIT_DIR DOT_GIT "/"
#define GIT_DIR_MODE 0755
#define GIT_BARE_DIR_MODE 0777
/* Default DOS-compatible 8.3 "short name" for a git repository, "GIT~1" */
#define GIT_DIR_SHORTNAME "GIT~1"
extern bool git_repository__fsync_gitdir;
/** Cvar cache identifiers */
typedef enum {
GIT_CONFIGMAP_AUTO_CRLF = 0, /* core.autocrlf */
GIT_CONFIGMAP_EOL, /* core.eol */
GIT_CONFIGMAP_SYMLINKS, /* core.symlinks */
GIT_CONFIGMAP_IGNORECASE, /* core.ignorecase */
GIT_CONFIGMAP_FILEMODE, /* core.filemode */
GIT_CONFIGMAP_IGNORESTAT, /* core.ignorestat */
GIT_CONFIGMAP_TRUSTCTIME, /* core.trustctime */
GIT_CONFIGMAP_ABBREV, /* core.abbrev */
GIT_CONFIGMAP_PRECOMPOSE, /* core.precomposeunicode */
GIT_CONFIGMAP_SAFE_CRLF, /* core.safecrlf */
GIT_CONFIGMAP_LOGALLREFUPDATES, /* core.logallrefupdates */
GIT_CONFIGMAP_PROTECTHFS, /* core.protectHFS */
GIT_CONFIGMAP_PROTECTNTFS, /* core.protectNTFS */
GIT_CONFIGMAP_FSYNCOBJECTFILES, /* core.fsyncObjectFiles */
GIT_CONFIGMAP_LONGPATHS, /* core.longpaths */
GIT_CONFIGMAP_CACHE_MAX
} git_configmap_item;
/**
* Configuration map value enumerations
*
* These are the values that are actually stored in the configmap cache,
* instead of their string equivalents. These values are internal and
* symbolic; make sure that none of them is set to `-1`, since that is
* the unique identifier for "not cached"
*/
typedef enum {
/* The value hasn't been loaded from the cache yet */
GIT_CONFIGMAP_NOT_CACHED = -1,
/* core.safecrlf: false, 'fail', 'warn' */
GIT_SAFE_CRLF_FALSE = 0,
GIT_SAFE_CRLF_FAIL = 1,
GIT_SAFE_CRLF_WARN = 2,
/* core.autocrlf: false, true, 'input; */
GIT_AUTO_CRLF_FALSE = 0,
GIT_AUTO_CRLF_TRUE = 1,
GIT_AUTO_CRLF_INPUT = 2,
GIT_AUTO_CRLF_DEFAULT = GIT_AUTO_CRLF_FALSE,
/* core.eol: unset, 'crlf', 'lf', 'native' */
GIT_EOL_UNSET = 0,
GIT_EOL_CRLF = 1,
GIT_EOL_LF = 2,
#ifdef GIT_WIN32
GIT_EOL_NATIVE = GIT_EOL_CRLF,
#else
GIT_EOL_NATIVE = GIT_EOL_LF,
#endif
GIT_EOL_DEFAULT = GIT_EOL_NATIVE,
/* core.symlinks: bool */
GIT_SYMLINKS_DEFAULT = GIT_CONFIGMAP_TRUE,
/* core.ignorecase */
GIT_IGNORECASE_DEFAULT = GIT_CONFIGMAP_FALSE,
/* core.filemode */
GIT_FILEMODE_DEFAULT = GIT_CONFIGMAP_TRUE,
/* core.ignorestat */
GIT_IGNORESTAT_DEFAULT = GIT_CONFIGMAP_FALSE,
/* core.trustctime */
GIT_TRUSTCTIME_DEFAULT = GIT_CONFIGMAP_TRUE,
/* core.abbrev */
GIT_ABBREV_DEFAULT = 7,
/* core.precomposeunicode */
GIT_PRECOMPOSE_DEFAULT = GIT_CONFIGMAP_FALSE,
/* core.safecrlf */
GIT_SAFE_CRLF_DEFAULT = GIT_CONFIGMAP_FALSE,
/* core.logallrefupdates */
GIT_LOGALLREFUPDATES_FALSE = GIT_CONFIGMAP_FALSE,
GIT_LOGALLREFUPDATES_TRUE = GIT_CONFIGMAP_TRUE,
GIT_LOGALLREFUPDATES_UNSET = 2,
GIT_LOGALLREFUPDATES_ALWAYS = 3,
GIT_LOGALLREFUPDATES_DEFAULT = GIT_LOGALLREFUPDATES_UNSET,
/* core.protectHFS */
GIT_PROTECTHFS_DEFAULT = GIT_CONFIGMAP_FALSE,
/* core.protectNTFS */
GIT_PROTECTNTFS_DEFAULT = GIT_CONFIGMAP_TRUE,
/* core.fsyncObjectFiles */
GIT_FSYNCOBJECTFILES_DEFAULT = GIT_CONFIGMAP_FALSE,
/* core.longpaths */
GIT_LONGPATHS_DEFAULT = GIT_CONFIGMAP_FALSE,
} git_configmap_value;
/* internal repository init flags */
enum {
GIT_REPOSITORY_INIT__HAS_DOTGIT = (1u << 16),
GIT_REPOSITORY_INIT__NATURAL_WD = (1u << 17),
GIT_REPOSITORY_INIT__IS_REINIT = (1u << 18),
};
/** Internal structure for repository object */
struct git_repository {
git_odb *_odb;
git_refdb *_refdb;
git_config *_config;
git_index *_index;
git_cache objects;
git_attr_cache *attrcache;
git_diff_driver_registry *diff_drivers;
char *gitlink;
char *gitdir;
char *commondir;
char *workdir;
char *namespace;
char *ident_name;
char *ident_email;
git_array_t(git_buf) reserved_names;
unsigned is_bare:1;
unsigned is_worktree:1;
unsigned int lru_counter;
git_atomic32 attr_session_key;
intptr_t configmap_cache[GIT_CONFIGMAP_CACHE_MAX];
git_strmap *submodule_cache;
};
GIT_INLINE(git_attr_cache *) git_repository_attr_cache(git_repository *repo)
{
return repo->attrcache;
}
int git_repository_head_tree(git_tree **tree, git_repository *repo);
int git_repository_create_head(const char *git_dir, const char *ref_name);
typedef int (*git_repository_foreach_worktree_cb)(git_repository *, void *);
int git_repository_foreach_worktree(git_repository *repo,
git_repository_foreach_worktree_cb cb,
void *payload);
/*
* Weak pointers to repository internals.
*
* The returned pointers do not need to be freed. Do not keep
* permanent references to these (i.e. between API calls), since they may
* become invalidated if the user replaces a repository internal.
*/
int git_repository_config__weakptr(git_config **out, git_repository *repo);
int git_repository_odb__weakptr(git_odb **out, git_repository *repo);
int git_repository_refdb__weakptr(git_refdb **out, git_repository *repo);
int git_repository_index__weakptr(git_index **out, git_repository *repo);
/*
* Configuration map cache
*
* Efficient access to the most used config variables of a repository.
* The cache is cleared every time the config backend is replaced.
*/
int git_repository__configmap_lookup(int *out, git_repository *repo, git_configmap_item item);
void git_repository__configmap_lookup_cache_clear(git_repository *repo);
GIT_INLINE(int) git_repository__ensure_not_bare(
git_repository *repo,
const char *operation_name)
{
if (!git_repository_is_bare(repo))
return 0;
git_error_set(
GIT_ERROR_REPOSITORY,
"cannot %s. This operation is not allowed against bare repositories.",
operation_name);
return GIT_EBAREREPO;
}
int git_repository__set_orig_head(git_repository *repo, const git_oid *orig_head);
int git_repository__cleanup_files(git_repository *repo, const char *files[], size_t files_len);
/* The default "reserved names" for a repository */
extern git_buf git_repository__reserved_names_win32[];
extern size_t git_repository__reserved_names_win32_len;
extern git_buf git_repository__reserved_names_posix[];
extern size_t git_repository__reserved_names_posix_len;
/*
* Gets any "reserved names" in the repository. This will return paths
* that should not be allowed in the repository (like ".git") to avoid
* conflicting with the repository path, or with alternate mechanisms to
* the repository path (eg, "GIT~1"). Every attempt will be made to look
* up all possible reserved names - if there was a conflict for the shortname
* GIT~1, for example, this function will try to look up the alternate
* shortname. If that fails, this function returns false, but out and outlen
* will still be populated with good defaults.
*/
bool git_repository__reserved_names(
git_buf **out, size_t *outlen, git_repository *repo, bool include_ntfs);
/*
* The default branch for the repository; the `init.defaultBranch`
* configuration option, if set, or `master` if it is not.
*/
int git_repository_initialbranch(git_buf *out, git_repository *repo);
/*
* Given a relative `path`, this makes it absolute based on the
* repository's working directory. This will perform validation
* to ensure that the path is not longer than MAX_PATH on Windows
* (unless `core.longpaths` is set in the repo config).
*/
int git_repository_workdir_path(git_buf *out, git_repository *repo, const char *path);
int git_repository__extensions(char ***out, size_t *out_len);
int git_repository__set_extensions(const char **extensions, size_t len);
void git_repository__free_extensions(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/util.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 "util.h"
#include "common.h"
#ifdef GIT_WIN32
# include "win32/utf-conv.h"
# include "win32/w32_buffer.h"
# ifndef WIN32_LEAN_AND_MEAN
# define WIN32_LEAN_AND_MEAN
# endif
# include <windows.h>
# ifdef HAVE_QSORT_S
# include <search.h>
# endif
#endif
#ifdef _MSC_VER
# include <Shlwapi.h>
#endif
#if defined(hpux) || defined(__hpux) || defined(_hpux)
# include <sys/pstat.h>
#endif
int git__strntol64(int64_t *result, const char *nptr, size_t nptr_len, const char **endptr, int base)
{
const char *p;
int64_t n, nn, v;
int c, ovfl, neg, ndig;
p = nptr;
neg = 0;
n = 0;
ndig = 0;
ovfl = 0;
/*
* White space
*/
while (nptr_len && git__isspace(*p))
p++, nptr_len--;
if (!nptr_len)
goto Return;
/*
* Sign
*/
if (*p == '-' || *p == '+') {
if (*p == '-')
neg = 1;
p++;
nptr_len--;
}
if (!nptr_len)
goto Return;
/*
* Automatically detect the base if none was given to us.
* Right now, we assume that a number starting with '0x'
* is hexadecimal and a number starting with '0' is
* octal.
*/
if (base == 0) {
if (*p != '0')
base = 10;
else if (nptr_len > 2 && (p[1] == 'x' || p[1] == 'X'))
base = 16;
else
base = 8;
}
if (base < 0 || 36 < base)
goto Return;
/*
* Skip prefix of '0x'-prefixed hexadecimal numbers. There is no
* need to do the same for '0'-prefixed octal numbers as a
* leading '0' does not have any impact. Also, if we skip a
* leading '0' in such a string, then we may end up with no
* digits left and produce an error later on which isn't one.
*/
if (base == 16 && nptr_len > 2 && p[0] == '0' && (p[1] == 'x' || p[1] == 'X')) {
p += 2;
nptr_len -= 2;
}
/*
* Non-empty sequence of digits
*/
for (; nptr_len > 0; p++,ndig++,nptr_len--) {
c = *p;
v = base;
if ('0'<=c && c<='9')
v = c - '0';
else if ('a'<=c && c<='z')
v = c - 'a' + 10;
else if ('A'<=c && c<='Z')
v = c - 'A' + 10;
if (v >= base)
break;
v = neg ? -v : v;
if (git__multiply_int64_overflow(&nn, n, base) || git__add_int64_overflow(&n, nn, v)) {
ovfl = 1;
/* Keep on iterating until the end of this number */
continue;
}
}
Return:
if (ndig == 0) {
git_error_set(GIT_ERROR_INVALID, "failed to convert string to long: not a number");
return -1;
}
if (endptr)
*endptr = p;
if (ovfl) {
git_error_set(GIT_ERROR_INVALID, "failed to convert string to long: overflow error");
return -1;
}
*result = n;
return 0;
}
int git__strntol32(int32_t *result, const char *nptr, size_t nptr_len, const char **endptr, int base)
{
const char *tmp_endptr;
int32_t tmp_int;
int64_t tmp_long;
int error;
if ((error = git__strntol64(&tmp_long, nptr, nptr_len, &tmp_endptr, base)) < 0)
return error;
tmp_int = tmp_long & 0xFFFFFFFF;
if (tmp_int != tmp_long) {
int len = (int)(tmp_endptr - nptr);
git_error_set(GIT_ERROR_INVALID, "failed to convert: '%.*s' is too large", len, nptr);
return -1;
}
*result = tmp_int;
if (endptr)
*endptr = tmp_endptr;
return error;
}
int git__strcasecmp(const char *a, const char *b)
{
while (*a && *b && git__tolower(*a) == git__tolower(*b))
++a, ++b;
return ((unsigned char)git__tolower(*a) - (unsigned char)git__tolower(*b));
}
int git__strcasesort_cmp(const char *a, const char *b)
{
int cmp = 0;
while (*a && *b) {
if (*a != *b) {
if (git__tolower(*a) != git__tolower(*b))
break;
/* use case in sort order even if not in equivalence */
if (!cmp)
cmp = (int)(*(const uint8_t *)a) - (int)(*(const uint8_t *)b);
}
++a, ++b;
}
if (*a || *b)
return (unsigned char)git__tolower(*a) - (unsigned char)git__tolower(*b);
return cmp;
}
int git__strncasecmp(const char *a, const char *b, size_t sz)
{
int al, bl;
do {
al = (unsigned char)git__tolower(*a);
bl = (unsigned char)git__tolower(*b);
++a, ++b;
} while (--sz && al && al == bl);
return al - bl;
}
void git__strntolower(char *str, size_t len)
{
size_t i;
for (i = 0; i < len; ++i) {
str[i] = (char)git__tolower(str[i]);
}
}
void git__strtolower(char *str)
{
git__strntolower(str, strlen(str));
}
GIT_INLINE(int) prefixcmp(const char *str, size_t str_n, const char *prefix, bool icase)
{
int s, p;
while (str_n--) {
s = (unsigned char)*str++;
p = (unsigned char)*prefix++;
if (icase) {
s = git__tolower(s);
p = git__tolower(p);
}
if (!p)
return 0;
if (s != p)
return s - p;
}
return (0 - *prefix);
}
int git__prefixcmp(const char *str, const char *prefix)
{
unsigned char s, p;
while (1) {
p = *prefix++;
s = *str++;
if (!p)
return 0;
if (s != p)
return s - p;
}
}
int git__prefixncmp(const char *str, size_t str_n, const char *prefix)
{
return prefixcmp(str, str_n, prefix, false);
}
int git__prefixcmp_icase(const char *str, const char *prefix)
{
return prefixcmp(str, SIZE_MAX, prefix, true);
}
int git__prefixncmp_icase(const char *str, size_t str_n, const char *prefix)
{
return prefixcmp(str, str_n, prefix, true);
}
int git__suffixcmp(const char *str, const char *suffix)
{
size_t a = strlen(str);
size_t b = strlen(suffix);
if (a < b)
return -1;
return strcmp(str + (a - b), suffix);
}
char *git__strtok(char **end, const char *sep)
{
char *ptr = *end;
while (*ptr && strchr(sep, *ptr))
++ptr;
if (*ptr) {
char *start = ptr;
*end = start + 1;
while (**end && !strchr(sep, **end))
++*end;
if (**end) {
**end = '\0';
++*end;
}
return start;
}
return NULL;
}
/* Similar to strtok, but does not collapse repeated tokens. */
char *git__strsep(char **end, const char *sep)
{
char *start = *end, *ptr = *end;
while (*ptr && !strchr(sep, *ptr))
++ptr;
if (*ptr) {
*end = ptr + 1;
*ptr = '\0';
return start;
}
return NULL;
}
size_t git__linenlen(const char *buffer, size_t buffer_len)
{
char *nl = memchr(buffer, '\n', buffer_len);
return nl ? (size_t)(nl - buffer) + 1 : buffer_len;
}
/*
* Adapted Not So Naive algorithm from http://www-igm.univ-mlv.fr/~lecroq/string/
*/
const void * git__memmem(const void *haystack, size_t haystacklen,
const void *needle, size_t needlelen)
{
const char *h, *n;
size_t j, k, l;
if (needlelen > haystacklen || !haystacklen || !needlelen)
return NULL;
h = (const char *) haystack,
n = (const char *) needle;
if (needlelen == 1)
return memchr(haystack, *n, haystacklen);
if (n[0] == n[1]) {
k = 2;
l = 1;
} else {
k = 1;
l = 2;
}
j = 0;
while (j <= haystacklen - needlelen) {
if (n[1] != h[j + 1]) {
j += k;
} else {
if (memcmp(n + 2, h + j + 2, needlelen - 2) == 0 &&
n[0] == h[j])
return h + j;
j += l;
}
}
return NULL;
}
void git__hexdump(const char *buffer, size_t len)
{
static const size_t LINE_WIDTH = 16;
size_t line_count, last_line, i, j;
const char *line;
line_count = (len / LINE_WIDTH);
last_line = (len % LINE_WIDTH);
for (i = 0; i < line_count; ++i) {
printf("%08" PRIxZ " ", (i * LINE_WIDTH));
line = buffer + (i * LINE_WIDTH);
for (j = 0; j < LINE_WIDTH; ++j, ++line) {
printf("%02x ", (unsigned char)*line & 0xFF);
if (j == (LINE_WIDTH / 2))
printf(" ");
}
printf(" |");
line = buffer + (i * LINE_WIDTH);
for (j = 0; j < LINE_WIDTH; ++j, ++line)
printf("%c", (*line >= 32 && *line <= 126) ? *line : '.');
printf("|\n");
}
if (last_line > 0) {
printf("%08" PRIxZ " ", (line_count * LINE_WIDTH));
line = buffer + (line_count * LINE_WIDTH);
for (j = 0; j < last_line; ++j, ++line) {
printf("%02x ", (unsigned char)*line & 0xFF);
if (j == (LINE_WIDTH / 2))
printf(" ");
}
if (j < (LINE_WIDTH / 2))
printf(" ");
for (j = 0; j < (LINE_WIDTH - last_line); ++j)
printf(" ");
printf(" |");
line = buffer + (line_count * LINE_WIDTH);
for (j = 0; j < last_line; ++j, ++line)
printf("%c", (*line >= 32 && *line <= 126) ? *line : '.');
printf("|\n");
}
printf("\n");
}
#ifdef GIT_LEGACY_HASH
uint32_t git__hash(const void *key, int len, unsigned int seed)
{
const uint32_t m = 0x5bd1e995;
const int r = 24;
uint32_t h = seed ^ len;
const unsigned char *data = (const unsigned char *)key;
while(len >= 4) {
uint32_t k = *(uint32_t *)data;
k *= m;
k ^= k >> r;
k *= m;
h *= m;
h ^= k;
data += 4;
len -= 4;
}
switch(len) {
case 3: h ^= data[2] << 16;
case 2: h ^= data[1] << 8;
case 1: h ^= data[0];
h *= m;
};
h ^= h >> 13;
h *= m;
h ^= h >> 15;
return h;
}
#else
/*
Cross-platform version of Murmurhash3
http://code.google.com/p/smhasher/wiki/MurmurHash3
by Austin Appleby ([email protected])
This code is on the public domain.
*/
uint32_t git__hash(const void *key, int len, uint32_t seed)
{
#define MURMUR_BLOCK() {\
k1 *= c1; \
k1 = git__rotl(k1,11);\
k1 *= c2;\
h1 ^= k1;\
h1 = h1*3 + 0x52dce729;\
c1 = c1*5 + 0x7b7d159c;\
c2 = c2*5 + 0x6bce6396;\
}
const uint8_t *data = (const uint8_t*)key;
const int nblocks = len / 4;
const uint32_t *blocks = (const uint32_t *)(data + nblocks * 4);
const uint8_t *tail = (const uint8_t *)(data + nblocks * 4);
uint32_t h1 = 0x971e137b ^ seed;
uint32_t k1;
uint32_t c1 = 0x95543787;
uint32_t c2 = 0x2ad7eb25;
int i;
for (i = -nblocks; i; i++) {
k1 = blocks[i];
MURMUR_BLOCK();
}
k1 = 0;
switch(len & 3) {
case 3: k1 ^= tail[2] << 16;
/* fall through */
case 2: k1 ^= tail[1] << 8;
/* fall through */
case 1: k1 ^= tail[0];
MURMUR_BLOCK();
}
h1 ^= len;
h1 ^= h1 >> 16;
h1 *= 0x85ebca6b;
h1 ^= h1 >> 13;
h1 *= 0xc2b2ae35;
h1 ^= h1 >> 16;
return h1;
}
#endif
/**
* A modified `bsearch` from the BSD glibc.
*
* Copyright (c) 1990 Regents of the University of California.
* All rights reserved.
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. [rescinded 22 July 1999]
* 4. Neither the name of the University nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*/
int git__bsearch(
void **array,
size_t array_len,
const void *key,
int (*compare)(const void *, const void *),
size_t *position)
{
size_t lim;
int cmp = -1;
void **part, **base = array;
for (lim = array_len; lim != 0; lim >>= 1) {
part = base + (lim >> 1);
cmp = (*compare)(key, *part);
if (cmp == 0) {
base = part;
break;
}
if (cmp > 0) { /* key > p; take right partition */
base = part + 1;
lim--;
} /* else take left partition */
}
if (position)
*position = (base - array);
return (cmp == 0) ? 0 : GIT_ENOTFOUND;
}
int git__bsearch_r(
void **array,
size_t array_len,
const void *key,
int (*compare_r)(const void *, const void *, void *),
void *payload,
size_t *position)
{
size_t lim;
int cmp = -1;
void **part, **base = array;
for (lim = array_len; lim != 0; lim >>= 1) {
part = base + (lim >> 1);
cmp = (*compare_r)(key, *part, payload);
if (cmp == 0) {
base = part;
break;
}
if (cmp > 0) { /* key > p; take right partition */
base = part + 1;
lim--;
} /* else take left partition */
}
if (position)
*position = (base - array);
return (cmp == 0) ? 0 : GIT_ENOTFOUND;
}
/**
* A strcmp wrapper
*
* We don't want direct pointers to the CRT on Windows, we may
* get stdcall conflicts.
*/
int git__strcmp_cb(const void *a, const void *b)
{
return strcmp((const char *)a, (const char *)b);
}
int git__strcasecmp_cb(const void *a, const void *b)
{
return strcasecmp((const char *)a, (const char *)b);
}
int git__parse_bool(int *out, const char *value)
{
/* A missing value means true */
if (value == NULL ||
!strcasecmp(value, "true") ||
!strcasecmp(value, "yes") ||
!strcasecmp(value, "on")) {
*out = 1;
return 0;
}
if (!strcasecmp(value, "false") ||
!strcasecmp(value, "no") ||
!strcasecmp(value, "off") ||
value[0] == '\0') {
*out = 0;
return 0;
}
return -1;
}
size_t git__unescape(char *str)
{
char *scan, *pos = str;
if (!str)
return 0;
for (scan = str; *scan; pos++, scan++) {
if (*scan == '\\' && *(scan + 1) != '\0')
scan++; /* skip '\' but include next char */
if (pos != scan)
*pos = *scan;
}
if (pos != scan) {
*pos = '\0';
}
return (pos - str);
}
#if defined(HAVE_QSORT_S) || defined(HAVE_QSORT_R_BSD)
typedef struct {
git__sort_r_cmp cmp;
void *payload;
} git__qsort_r_glue;
static int GIT_LIBGIT2_CALL git__qsort_r_glue_cmp(
void *payload, const void *a, const void *b)
{
git__qsort_r_glue *glue = payload;
return glue->cmp(a, b, glue->payload);
}
#endif
#if !defined(HAVE_QSORT_R_BSD) && \
!defined(HAVE_QSORT_R_GNU) && \
!defined(HAVE_QSORT_S)
static void swap(uint8_t *a, uint8_t *b, size_t elsize)
{
char tmp[256];
while (elsize) {
size_t n = elsize < sizeof(tmp) ? elsize : sizeof(tmp);
memcpy(tmp, a + elsize - n, n);
memcpy(a + elsize - n, b + elsize - n, n);
memcpy(b + elsize - n, tmp, n);
elsize -= n;
}
}
static void insertsort(
void *els, size_t nel, size_t elsize,
git__sort_r_cmp cmp, void *payload)
{
uint8_t *base = els;
uint8_t *end = base + nel * elsize;
uint8_t *i, *j;
for (i = base + elsize; i < end; i += elsize)
for (j = i; j > base && cmp(j, j - elsize, payload) < 0; j -= elsize)
swap(j, j - elsize, elsize);
}
#endif
void git__qsort_r(
void *els, size_t nel, size_t elsize, git__sort_r_cmp cmp, void *payload)
{
#if defined(HAVE_QSORT_R_BSD)
git__qsort_r_glue glue = { cmp, payload };
qsort_r(els, nel, elsize, &glue, git__qsort_r_glue_cmp);
#elif defined(HAVE_QSORT_R_GNU)
qsort_r(els, nel, elsize, cmp, payload);
#elif defined(HAVE_QSORT_S)
git__qsort_r_glue glue = { cmp, payload };
qsort_s(els, nel, elsize, git__qsort_r_glue_cmp, &glue);
#else
insertsort(els, nel, elsize, cmp, payload);
#endif
}
#ifdef GIT_WIN32
int git__getenv(git_buf *out, const char *name)
{
wchar_t *wide_name = NULL, *wide_value = NULL;
DWORD value_len;
int error = -1;
git_buf_clear(out);
if (git__utf8_to_16_alloc(&wide_name, name) < 0)
return -1;
if ((value_len = GetEnvironmentVariableW(wide_name, NULL, 0)) > 0) {
wide_value = git__malloc(value_len * sizeof(wchar_t));
GIT_ERROR_CHECK_ALLOC(wide_value);
value_len = GetEnvironmentVariableW(wide_name, wide_value, value_len);
}
if (value_len)
error = git_buf_put_w(out, wide_value, value_len);
else if (GetLastError() == ERROR_SUCCESS || GetLastError() == ERROR_ENVVAR_NOT_FOUND)
error = GIT_ENOTFOUND;
else
git_error_set(GIT_ERROR_OS, "could not read environment variable '%s'", name);
git__free(wide_name);
git__free(wide_value);
return error;
}
#else
int git__getenv(git_buf *out, const char *name)
{
const char *val = getenv(name);
git_buf_clear(out);
if (!val)
return GIT_ENOTFOUND;
return git_buf_puts(out, val);
}
#endif
/*
* By doing this in two steps we can at least get
* the function to be somewhat coherent, even
* with this disgusting nest of #ifdefs.
*/
#ifndef _SC_NPROCESSORS_ONLN
# ifdef _SC_NPROC_ONLN
# define _SC_NPROCESSORS_ONLN _SC_NPROC_ONLN
# elif defined _SC_CRAY_NCPU
# define _SC_NPROCESSORS_ONLN _SC_CRAY_NCPU
# endif
#endif
int git__online_cpus(void)
{
#ifdef _SC_NPROCESSORS_ONLN
long ncpus;
#endif
#ifdef _WIN32
SYSTEM_INFO info;
GetSystemInfo(&info);
if ((int)info.dwNumberOfProcessors > 0)
return (int)info.dwNumberOfProcessors;
#elif defined(hpux) || defined(__hpux) || defined(_hpux)
struct pst_dynamic psd;
if (!pstat_getdynamic(&psd, sizeof(psd), (size_t)1, 0))
return (int)psd.psd_proc_cnt;
#endif
#ifdef _SC_NPROCESSORS_ONLN
if ((ncpus = (long)sysconf(_SC_NPROCESSORS_ONLN)) > 0)
return (int)ncpus;
#endif
return 1;
}
|
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.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 "sysdir.h"
#include "runtime.h"
#include "buffer.h"
#include "path.h"
#include <ctype.h>
#if GIT_WIN32
#include "win32/findfile.h"
#else
#include <unistd.h>
#include <pwd.h>
#endif
static int git_sysdir_guess_programdata_dirs(git_buf *out)
{
#ifdef GIT_WIN32
return git_win32__find_programdata_dirs(out);
#else
git_buf_clear(out);
return 0;
#endif
}
static int git_sysdir_guess_system_dirs(git_buf *out)
{
#ifdef GIT_WIN32
return git_win32__find_system_dirs(out, L"etc\\");
#else
return git_buf_sets(out, "/etc");
#endif
}
#ifndef GIT_WIN32
static int get_passwd_home(git_buf *out, uid_t uid)
{
struct passwd pwd, *pwdptr;
char *buf = NULL;
long buflen;
int error;
GIT_ASSERT_ARG(out);
if ((buflen = sysconf(_SC_GETPW_R_SIZE_MAX)) == -1)
buflen = 1024;
do {
buf = git__realloc(buf, buflen);
error = getpwuid_r(uid, &pwd, buf, buflen, &pwdptr);
buflen *= 2;
} while (error == ERANGE && buflen <= 8192);
if (error) {
git_error_set(GIT_ERROR_OS, "failed to get passwd entry");
goto out;
}
if (!pwdptr) {
git_error_set(GIT_ERROR_OS, "no passwd entry found for user");
goto out;
}
if ((error = git_buf_puts(out, pwdptr->pw_dir)) < 0)
goto out;
out:
git__free(buf);
return error;
}
#endif
static int git_sysdir_guess_global_dirs(git_buf *out)
{
#ifdef GIT_WIN32
return git_win32__find_global_dirs(out);
#else
int error;
uid_t uid, euid;
const char *sandbox_id;
uid = getuid();
euid = geteuid();
/**
* If APP_SANDBOX_CONTAINER_ID is set, we are running in a
* sandboxed environment on macOS.
*/
sandbox_id = getenv("APP_SANDBOX_CONTAINER_ID");
/*
* In case we are running setuid, use the configuration
* of the effective user.
*
* If we are running in a sandboxed environment on macOS,
* we have to get the HOME dir from the password entry file.
*/
if (!sandbox_id && uid == euid)
error = git__getenv(out, "HOME");
else
error = get_passwd_home(out, euid);
if (error == GIT_ENOTFOUND) {
git_error_clear();
error = 0;
}
return error;
#endif
}
static int git_sysdir_guess_xdg_dirs(git_buf *out)
{
#ifdef GIT_WIN32
return git_win32__find_xdg_dirs(out);
#else
git_buf env = GIT_BUF_INIT;
int error;
uid_t uid, euid;
uid = getuid();
euid = geteuid();
/*
* In case we are running setuid, only look up passwd
* directory of the effective user.
*/
if (uid == euid) {
if ((error = git__getenv(&env, "XDG_CONFIG_HOME")) == 0)
error = git_buf_joinpath(out, env.ptr, "git");
if (error == GIT_ENOTFOUND && (error = git__getenv(&env, "HOME")) == 0)
error = git_buf_joinpath(out, env.ptr, ".config/git");
} else {
if ((error = get_passwd_home(&env, euid)) == 0)
error = git_buf_joinpath(out, env.ptr, ".config/git");
}
if (error == GIT_ENOTFOUND) {
git_error_clear();
error = 0;
}
git_buf_dispose(&env);
return error;
#endif
}
static int git_sysdir_guess_template_dirs(git_buf *out)
{
#ifdef GIT_WIN32
return git_win32__find_system_dirs(out, L"share\\git-core\\templates");
#else
return git_buf_sets(out, "/usr/share/git-core/templates");
#endif
}
struct git_sysdir__dir {
git_buf buf;
int (*guess)(git_buf *out);
};
static struct git_sysdir__dir git_sysdir__dirs[] = {
{ GIT_BUF_INIT, git_sysdir_guess_system_dirs },
{ GIT_BUF_INIT, git_sysdir_guess_global_dirs },
{ GIT_BUF_INIT, git_sysdir_guess_xdg_dirs },
{ GIT_BUF_INIT, git_sysdir_guess_programdata_dirs },
{ GIT_BUF_INIT, git_sysdir_guess_template_dirs },
};
static void git_sysdir_global_shutdown(void)
{
size_t i;
for (i = 0; i < ARRAY_SIZE(git_sysdir__dirs); ++i)
git_buf_dispose(&git_sysdir__dirs[i].buf);
}
int git_sysdir_global_init(void)
{
size_t i;
int error = 0;
for (i = 0; !error && i < ARRAY_SIZE(git_sysdir__dirs); i++)
error = git_sysdir__dirs[i].guess(&git_sysdir__dirs[i].buf);
return git_runtime_shutdown_register(git_sysdir_global_shutdown);
}
static int git_sysdir_check_selector(git_sysdir_t which)
{
if (which < ARRAY_SIZE(git_sysdir__dirs))
return 0;
git_error_set(GIT_ERROR_INVALID, "config directory selector out of range");
return -1;
}
int git_sysdir_get(const git_buf **out, git_sysdir_t which)
{
GIT_ASSERT_ARG(out);
*out = NULL;
GIT_ERROR_CHECK_ERROR(git_sysdir_check_selector(which));
*out = &git_sysdir__dirs[which].buf;
return 0;
}
#define PATH_MAGIC "$PATH"
int git_sysdir_set(git_sysdir_t which, const char *search_path)
{
const char *expand_path = NULL;
git_buf merge = GIT_BUF_INIT;
GIT_ERROR_CHECK_ERROR(git_sysdir_check_selector(which));
if (search_path != NULL)
expand_path = strstr(search_path, PATH_MAGIC);
/* reset the default if this path has been cleared */
if (!search_path)
git_sysdir__dirs[which].guess(&git_sysdir__dirs[which].buf);
/* if $PATH is not referenced, then just set the path */
if (!expand_path) {
if (search_path)
git_buf_sets(&git_sysdir__dirs[which].buf, search_path);
goto done;
}
/* otherwise set to join(before $PATH, old value, after $PATH) */
if (expand_path > search_path)
git_buf_set(&merge, search_path, expand_path - search_path);
if (git_buf_len(&git_sysdir__dirs[which].buf))
git_buf_join(&merge, GIT_PATH_LIST_SEPARATOR,
merge.ptr, git_sysdir__dirs[which].buf.ptr);
expand_path += strlen(PATH_MAGIC);
if (*expand_path)
git_buf_join(&merge, GIT_PATH_LIST_SEPARATOR, merge.ptr, expand_path);
git_buf_swap(&git_sysdir__dirs[which].buf, &merge);
git_buf_dispose(&merge);
done:
if (git_buf_oom(&git_sysdir__dirs[which].buf))
return -1;
return 0;
}
static int git_sysdir_find_in_dirlist(
git_buf *path,
const char *name,
git_sysdir_t which,
const char *label)
{
size_t len;
const char *scan, *next = NULL;
const git_buf *syspath;
GIT_ERROR_CHECK_ERROR(git_sysdir_get(&syspath, which));
if (!syspath || !git_buf_len(syspath))
goto done;
for (scan = git_buf_cstr(syspath); scan; scan = next) {
/* find unescaped separator or end of string */
for (next = scan; *next; ++next) {
if (*next == GIT_PATH_LIST_SEPARATOR &&
(next <= scan || next[-1] != '\\'))
break;
}
len = (size_t)(next - scan);
next = (*next ? next + 1 : NULL);
if (!len)
continue;
GIT_ERROR_CHECK_ERROR(git_buf_set(path, scan, len));
if (name)
GIT_ERROR_CHECK_ERROR(git_buf_joinpath(path, path->ptr, name));
if (git_path_exists(path->ptr))
return 0;
}
done:
if (name)
git_error_set(GIT_ERROR_OS, "the %s file '%s' doesn't exist", label, name);
else
git_error_set(GIT_ERROR_OS, "the %s directory doesn't exist", label);
git_buf_dispose(path);
return GIT_ENOTFOUND;
}
int git_sysdir_find_system_file(git_buf *path, const char *filename)
{
return git_sysdir_find_in_dirlist(
path, filename, GIT_SYSDIR_SYSTEM, "system");
}
int git_sysdir_find_global_file(git_buf *path, const char *filename)
{
return git_sysdir_find_in_dirlist(
path, filename, GIT_SYSDIR_GLOBAL, "global");
}
int git_sysdir_find_xdg_file(git_buf *path, const char *filename)
{
return git_sysdir_find_in_dirlist(
path, filename, GIT_SYSDIR_XDG, "global/xdg");
}
int git_sysdir_find_programdata_file(git_buf *path, const char *filename)
{
return git_sysdir_find_in_dirlist(
path, filename, GIT_SYSDIR_PROGRAMDATA, "ProgramData");
}
int git_sysdir_find_template_dir(git_buf *path)
{
return git_sysdir_find_in_dirlist(
path, NULL, GIT_SYSDIR_TEMPLATE, "template");
}
int git_sysdir_expand_global_file(git_buf *path, const char *filename)
{
int error;
if ((error = git_sysdir_find_global_file(path, NULL)) == 0) {
if (filename)
error = git_buf_joinpath(path, path->ptr, filename);
}
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/idxmap.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_idxmap_h__
#define INCLUDE_idxmap_h__
#include "common.h"
#include "git2/index.h"
/** A map with `git_index_entry`s as key. */
typedef struct kh_idx_s git_idxmap;
/** A map with case-insensitive `git_index_entry`s as key */
typedef struct kh_idxicase_s git_idxmap_icase;
/**
* Allocate a new index entry map.
*
* @param out Pointer to the map that shall be allocated.
* @return 0 on success, an error code if allocation has failed.
*/
int git_idxmap_new(git_idxmap **out);
/**
* Allocate a new case-insensitive index entry map.
*
* @param out Pointer to the map that shall be allocated.
* @return 0 on success, an error code if allocation has failed.
*/
int git_idxmap_icase_new(git_idxmap_icase **out);
/**
* Free memory associated with the map.
*
* Note that this function will _not_ free values added to this
* map.
*
* @param map Pointer to the map that is to be free'd. May be
* `NULL`.
*/
void git_idxmap_free(git_idxmap *map);
/**
* Free memory associated with the map.
*
* Note that this function will _not_ free values added to this
* map.
*
* @param map Pointer to the map that is to be free'd. May be
* `NULL`.
*/
void git_idxmap_icase_free(git_idxmap_icase *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_idxmap_clear(git_idxmap *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_idxmap_icase_clear(git_idxmap_icase *map);
/**
* Resize the map by allocating more memory.
*
* @param map map that shall be resized
* @param size count of entries that the map shall hold
* @return `0` if the map was successfully resized, a negative
* error code otherwise
*/
int git_idxmap_resize(git_idxmap *map, size_t size);
/**
* Resize the map by allocating more memory.
*
* @param map map that shall be resized
* @param size count of entries that the map shall hold
* @return `0` if the map was successfully resized, a negative
* error code otherwise
*/
int git_idxmap_icase_resize(git_idxmap_icase *map, size_t size);
/**
* Return value associated with the given key.
*
* @param map map to search key in
* @param key key to search for; the index entry will be searched
* for by its case-sensitive path
* @return value associated with the given key or NULL if the key was not found
*/
void *git_idxmap_get(git_idxmap *map, const git_index_entry *key);
/**
* Return value associated with the given key.
*
* @param map map to search key in
* @param key key to search for; the index entry will be searched
* for by its case-insensitive path
* @return value associated with the given key or NULL if the key was not found
*/
void *git_idxmap_icase_get(git_idxmap_icase *map, const git_index_entry *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_idxmap_set(git_idxmap *map, const git_index_entry *key, void *value);
/**
* 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_idxmap_icase_set(git_idxmap_icase *map, const git_index_entry *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_idxmap_delete(git_idxmap *map, const git_index_entry *key);
/**
* 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_idxmap_icase_delete(git_idxmap_icase *map, const git_index_entry *key);
#endif
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.