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/src
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2/src/win32/utf-conv.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 "utf-conv.h" GIT_INLINE(void) git__set_errno(void) { if (GetLastError() == ERROR_INSUFFICIENT_BUFFER) errno = ENAMETOOLONG; else errno = EINVAL; } /** * Converts a UTF-8 string to wide characters. * * @param dest The buffer to receive the wide string. * @param dest_size The size of the buffer, in characters. * @param src The UTF-8 string to convert. * @return The length of the wide string, in characters (not counting the NULL terminator), or < 0 for failure */ int git__utf8_to_16(wchar_t *dest, size_t dest_size, const char *src) { int len; /* Length of -1 indicates NULL termination of the input string. Subtract 1 from the result to * turn 0 into -1 (an error code) and to not count the NULL terminator as part of the string's * length. MultiByteToWideChar never returns int's minvalue, so underflow is not possible */ if ((len = MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS, src, -1, dest, (int)dest_size) - 1) < 0) git__set_errno(); return len; } /** * Converts a wide string to UTF-8. * * @param dest The buffer to receive the UTF-8 string. * @param dest_size The size of the buffer, in bytes. * @param src The wide string to convert. * @return The length of the UTF-8 string, in bytes (not counting the NULL terminator), or < 0 for failure */ int git__utf16_to_8(char *dest, size_t dest_size, const wchar_t *src) { int len; /* Length of -1 indicates NULL termination of the input string. Subtract 1 from the result to * turn 0 into -1 (an error code) and to not count the NULL terminator as part of the string's * length. WideCharToMultiByte never returns int's minvalue, so underflow is not possible */ if ((len = WideCharToMultiByte(CP_UTF8, WC_ERR_INVALID_CHARS, src, -1, dest, (int)dest_size, NULL, NULL) - 1) < 0) git__set_errno(); return len; } /** * Converts a UTF-8 string to wide characters. * Memory is allocated to hold the converted string. * The caller is responsible for freeing the string with git__free. * * @param dest Receives a pointer to the wide string. * @param src The UTF-8 string to convert. * @return The length of the wide string, in characters (not counting the NULL terminator), or < 0 for failure */ int git__utf8_to_16_alloc(wchar_t **dest, const char *src) { int utf16_size; *dest = NULL; /* Length of -1 indicates NULL termination of the input string */ utf16_size = MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS, src, -1, NULL, 0); if (!utf16_size) { git__set_errno(); return -1; } if (!(*dest = git__mallocarray(utf16_size, sizeof(wchar_t)))) { errno = ENOMEM; return -1; } utf16_size = MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS, src, -1, *dest, utf16_size); if (!utf16_size) { git__set_errno(); git__free(*dest); *dest = NULL; } /* Subtract 1 from the result to turn 0 into -1 (an error code) and to not count the NULL * terminator as part of the string's length. MultiByteToWideChar never returns int's minvalue, * so underflow is not possible */ return utf16_size - 1; } /** * Converts a wide string to UTF-8. * Memory is allocated to hold the converted string. * The caller is responsible for freeing the string with git__free. * * @param dest Receives a pointer to the UTF-8 string. * @param src The wide string to convert. * @return The length of the UTF-8 string, in bytes (not counting the NULL terminator), or < 0 for failure */ int git__utf16_to_8_alloc(char **dest, const wchar_t *src) { int utf8_size; *dest = NULL; /* Length of -1 indicates NULL termination of the input string */ utf8_size = WideCharToMultiByte(CP_UTF8, WC_ERR_INVALID_CHARS, src, -1, NULL, 0, NULL, NULL); if (!utf8_size) { git__set_errno(); return -1; } *dest = git__malloc(utf8_size); if (!*dest) { errno = ENOMEM; return -1; } utf8_size = WideCharToMultiByte(CP_UTF8, WC_ERR_INVALID_CHARS, src, -1, *dest, utf8_size, NULL, NULL); if (!utf8_size) { git__set_errno(); git__free(*dest); *dest = NULL; } /* Subtract 1 from the result to turn 0 into -1 (an error code) and to not count the NULL * terminator as part of the string's length. MultiByteToWideChar never returns int's minvalue, * so underflow is not possible */ return utf8_size - 1; }
0
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2/src
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2/src/win32/posix.h
/* * Copyright (C) the libgit2 contributors. All rights reserved. * * This file is part of libgit2, distributed under the GNU GPL v2 with * a Linking Exception. For full terms see the included COPYING file. */ #ifndef INCLUDE_win32_posix_h__ #define INCLUDE_win32_posix_h__ #include "common.h" #include "../posix.h" #include "win32-compat.h" #include "path_w32.h" #include "utf-conv.h" #include "dir.h" extern unsigned long git_win32__createfile_sharemode; extern int git_win32__retries; typedef SOCKET GIT_SOCKET; #define p_lseek(f,n,w) _lseeki64(f, n, w) extern int p_fstat(int fd, struct stat *buf); extern int p_lstat(const char *file_name, struct stat *buf); extern int p_stat(const char *path, struct stat *buf); extern int p_utimes(const char *filename, const struct p_timeval times[2]); extern int p_futimes(int fd, const struct p_timeval times[2]); extern int p_readlink(const char *path, char *buf, size_t bufsiz); extern int p_symlink(const char *old, const char *new); extern int p_link(const char *old, const char *new); extern int p_unlink(const char *path); extern int p_mkdir(const char *path, mode_t mode); extern int p_fsync(int fd); extern char *p_realpath(const char *orig_path, char *buffer); extern int p_recv(GIT_SOCKET socket, void *buffer, size_t length, int flags); extern int p_send(GIT_SOCKET socket, const void *buffer, size_t length, int flags); extern int p_inet_pton(int af, const char *src, void* dst); extern int p_vsnprintf(char *buffer, size_t count, const char *format, va_list argptr); extern int p_snprintf(char *buffer, size_t count, const char *format, ...) GIT_FORMAT_PRINTF(3, 4); extern int p_mkstemp(char *tmp_path); extern int p_chdir(const char *path); extern int p_chmod(const char *path, mode_t mode); extern int p_rmdir(const char *path); extern int p_access(const char *path, mode_t mode); extern int p_ftruncate(int fd, off64_t size); /* p_lstat is almost but not quite POSIX correct. Specifically, the use of * ENOTDIR is wrong, in that it does not mean precisely that a non-directory * entry was encountered. Making it correct is potentially expensive, * however, so this is a separate version of p_lstat to use when correct * POSIX ENOTDIR semantics is required. */ extern int p_lstat_posixly(const char *filename, struct stat *buf); extern struct tm * p_localtime_r(const time_t *timer, struct tm *result); extern struct tm * p_gmtime_r(const time_t *timer, struct tm *result); #endif
0
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2/src
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2/src/win32/findfile.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 "findfile.h" #include "path_w32.h" #include "utf-conv.h" #include "path.h" #define REG_MSYSGIT_INSTALL_LOCAL L"SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\Git_is1" #ifndef _WIN64 #define REG_MSYSGIT_INSTALL REG_MSYSGIT_INSTALL_LOCAL #else #define REG_MSYSGIT_INSTALL L"SOFTWARE\\Wow6432Node\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\Git_is1" #endif typedef struct { git_win32_path path; DWORD len; } _findfile_path; static int git_win32__expand_path(_findfile_path *dest, const wchar_t *src) { dest->len = ExpandEnvironmentStringsW(src, dest->path, ARRAY_SIZE(dest->path)); if (!dest->len || dest->len > ARRAY_SIZE(dest->path)) return -1; return 0; } static int win32_path_to_8(git_buf *dest, const wchar_t *src) { git_win32_utf8_path utf8_path; if (git_win32_path_to_utf8(utf8_path, src) < 0) { git_error_set(GIT_ERROR_OS, "unable to convert path to UTF-8"); return -1; } /* Convert backslashes to forward slashes */ git_path_mkposix(utf8_path); return git_buf_sets(dest, utf8_path); } static wchar_t *win32_walkpath(wchar_t *path, wchar_t *buf, size_t buflen) { wchar_t term, *base = path; GIT_ASSERT_ARG_WITH_RETVAL(path, NULL); GIT_ASSERT_ARG_WITH_RETVAL(buf, NULL); GIT_ASSERT_ARG_WITH_RETVAL(buflen, NULL); term = (*path == L'"') ? *path++ : L';'; for (buflen--; *path && *path != term && buflen; buflen--) *buf++ = *path++; *buf = L'\0'; /* reserved a byte via initial subtract */ while (*path == term || *path == L';') path++; return (path != base) ? path : NULL; } static int win32_find_git_in_path(git_buf *buf, const wchar_t *gitexe, const wchar_t *subdir) { wchar_t *env = _wgetenv(L"PATH"), lastch; _findfile_path root; size_t gitexe_len = wcslen(gitexe); if (!env) return -1; while ((env = win32_walkpath(env, root.path, MAX_PATH-1)) && *root.path) { root.len = (DWORD)wcslen(root.path); lastch = root.path[root.len - 1]; /* ensure trailing slash (MAX_PATH-1 to walkpath guarantees space) */ if (lastch != L'/' && lastch != L'\\') { root.path[root.len++] = L'\\'; root.path[root.len] = L'\0'; } if (root.len + gitexe_len >= MAX_PATH) continue; wcscpy(&root.path[root.len], gitexe); if (_waccess(root.path, F_OK) == 0 && root.len > 5) { /* replace "bin\\" or "cmd\\" with subdir */ wcscpy(&root.path[root.len - 4], subdir); win32_path_to_8(buf, root.path); return 0; } } return GIT_ENOTFOUND; } static int win32_find_git_in_registry( git_buf *buf, const HKEY hive, const wchar_t *key, const wchar_t *subdir) { HKEY hKey; int error = GIT_ENOTFOUND; GIT_ASSERT_ARG(buf); if (!RegOpenKeyExW(hive, key, 0, KEY_READ, &hKey)) { DWORD dwType, cbData; git_win32_path path; /* Ensure that the buffer is big enough to have the suffix attached * after we receive the result. */ cbData = (DWORD)(sizeof(path) - wcslen(subdir) * sizeof(wchar_t)); /* InstallLocation points to the root of the git directory */ if (!RegQueryValueExW(hKey, L"InstallLocation", NULL, &dwType, (LPBYTE)path, &cbData) && dwType == REG_SZ) { /* Append the suffix */ wcscat(path, subdir); /* Convert to UTF-8, with forward slashes, and output the path * to the provided buffer */ if (!win32_path_to_8(buf, path)) error = 0; } RegCloseKey(hKey); } return error; } static int win32_find_existing_dirs( git_buf *out, const wchar_t *tmpl[]) { _findfile_path path16; git_buf buf = GIT_BUF_INIT; git_buf_clear(out); for (; *tmpl != NULL; tmpl++) { if (!git_win32__expand_path(&path16, *tmpl) && path16.path[0] != L'%' && !_waccess(path16.path, F_OK)) { win32_path_to_8(&buf, path16.path); if (buf.size) git_buf_join(out, GIT_PATH_LIST_SEPARATOR, out->ptr, buf.ptr); } } git_buf_dispose(&buf); return (git_buf_oom(out) ? -1 : 0); } int git_win32__find_system_dirs(git_buf *out, const wchar_t *subdir) { git_buf buf = GIT_BUF_INIT; /* directories where git.exe & git.cmd are found */ if (!win32_find_git_in_path(&buf, L"git.exe", subdir) && buf.size) git_buf_set(out, buf.ptr, buf.size); else git_buf_clear(out); if (!win32_find_git_in_path(&buf, L"git.cmd", subdir) && buf.size) git_buf_join(out, GIT_PATH_LIST_SEPARATOR, out->ptr, buf.ptr); /* directories where git is installed according to registry */ if (!win32_find_git_in_registry( &buf, HKEY_CURRENT_USER, REG_MSYSGIT_INSTALL_LOCAL, subdir) && buf.size) git_buf_join(out, GIT_PATH_LIST_SEPARATOR, out->ptr, buf.ptr); if (!win32_find_git_in_registry( &buf, HKEY_LOCAL_MACHINE, REG_MSYSGIT_INSTALL, subdir) && buf.size) git_buf_join(out, GIT_PATH_LIST_SEPARATOR, out->ptr, buf.ptr); git_buf_dispose(&buf); return (git_buf_oom(out) ? -1 : 0); } int git_win32__find_global_dirs(git_buf *out) { static const wchar_t *global_tmpls[4] = { L"%HOME%\\", L"%HOMEDRIVE%%HOMEPATH%\\", L"%USERPROFILE%\\", NULL, }; return win32_find_existing_dirs(out, global_tmpls); } int git_win32__find_xdg_dirs(git_buf *out) { static const wchar_t *global_tmpls[7] = { L"%XDG_CONFIG_HOME%\\git", L"%APPDATA%\\git", L"%LOCALAPPDATA%\\git", L"%HOME%\\.config\\git", L"%HOMEDRIVE%%HOMEPATH%\\.config\\git", L"%USERPROFILE%\\.config\\git", NULL, }; return win32_find_existing_dirs(out, global_tmpls); } int git_win32__find_programdata_dirs(git_buf *out) { static const wchar_t *programdata_tmpls[2] = { L"%PROGRAMDATA%\\Git", NULL, }; return win32_find_existing_dirs(out, programdata_tmpls); }
0
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2/src
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2/src/win32/msvc-compat.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_win32_msvc_compat_h__ #define INCLUDE_win32_msvc_compat_h__ #if defined(_MSC_VER) typedef unsigned short mode_t; typedef SSIZE_T ssize_t; #ifdef _WIN64 # define SSIZE_MAX _I64_MAX #else # define SSIZE_MAX LONG_MAX #endif #define strcasecmp(s1, s2) _stricmp(s1, s2) #define strncasecmp(s1, s2, c) _strnicmp(s1, s2, c) #endif /* * Offer GIT_LIBGIT2_CALL for our calling conventions (__cdecl, always). * This is useful for providing callbacks to userspace code. * * Offer GIT_SYSTEM_CALL for the system calling conventions (__stdcall on * Win32). Useful for providing callbacks to system libraries. */ #define GIT_LIBGIT2_CALL __cdecl #define GIT_SYSTEM_CALL NTAPI #endif
0
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2/src
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2/src/win32/path_w32.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_w32.h" #include "path.h" #include "utf-conv.h" #include "posix.h" #include "reparse.h" #include "dir.h" #define PATH__NT_NAMESPACE L"\\\\?\\" #define PATH__NT_NAMESPACE_LEN 4 #define PATH__ABSOLUTE_LEN 3 #define path__is_nt_namespace(p) \ (((p)[0] == '\\' && (p)[1] == '\\' && (p)[2] == '?' && (p)[3] == '\\') || \ ((p)[0] == '/' && (p)[1] == '/' && (p)[2] == '?' && (p)[3] == '/')) #define path__is_unc(p) \ (((p)[0] == '\\' && (p)[1] == '\\') || ((p)[0] == '/' && (p)[1] == '/')) #define path__startswith_slash(p) \ ((p)[0] == '\\' || (p)[0] == '/') GIT_INLINE(int) path__cwd(wchar_t *path, int size) { int len; if ((len = GetCurrentDirectoryW(size, path)) == 0) { errno = GetLastError() == ERROR_ACCESS_DENIED ? EACCES : ENOENT; return -1; } else if (len > size) { errno = ENAMETOOLONG; return -1; } /* The Win32 APIs may return "\\?\" once you've used it first. * But it may not. What a gloriously predictible API! */ if (wcsncmp(path, PATH__NT_NAMESPACE, PATH__NT_NAMESPACE_LEN)) return len; len -= PATH__NT_NAMESPACE_LEN; memmove(path, path + PATH__NT_NAMESPACE_LEN, sizeof(wchar_t) * len); return len; } static wchar_t *path__skip_server(wchar_t *path) { wchar_t *c; for (c = path; *c; c++) { if (git_path_is_dirsep(*c)) return c + 1; } return c; } static wchar_t *path__skip_prefix(wchar_t *path) { if (path__is_nt_namespace(path)) { path += PATH__NT_NAMESPACE_LEN; if (wcsncmp(path, L"UNC\\", 4) == 0) path = path__skip_server(path + 4); else if (git_path_is_absolute(path)) path += PATH__ABSOLUTE_LEN; } else if (git_path_is_absolute(path)) { path += PATH__ABSOLUTE_LEN; } else if (path__is_unc(path)) { path = path__skip_server(path + 2); } return path; } int git_win32_path_canonicalize(git_win32_path path) { wchar_t *base, *from, *to, *next; size_t len; base = to = path__skip_prefix(path); /* Unposixify if the prefix */ for (from = path; from < to; from++) { if (*from == L'/') *from = L'\\'; } while (*from) { for (next = from; *next; ++next) { if (*next == L'/') { *next = L'\\'; break; } if (*next == L'\\') break; } len = next - from; if (len == 1 && from[0] == L'.') /* do nothing with singleton dot */; else if (len == 2 && from[0] == L'.' && from[1] == L'.') { if (to == base) { /* no more path segments to strip, eat the "../" */ if (*next == L'\\') len++; base = to; } else { /* back up a path segment */ while (to > base && to[-1] == L'\\') to--; while (to > base && to[-1] != L'\\') to--; } } else { if (*next == L'\\' && *from != L'\\') len++; if (to != from) memmove(to, from, sizeof(wchar_t) * len); to += len; } from += len; while (*from == L'\\') from++; } /* Strip trailing backslashes */ while (to > base && to[-1] == L'\\') to--; *to = L'\0'; if ((to - path) > INT_MAX) { SetLastError(ERROR_FILENAME_EXCED_RANGE); return -1; } return (int)(to - path); } static int win32_path_cwd(wchar_t *out, size_t len) { int cwd_len; if (len > INT_MAX) { errno = ENAMETOOLONG; return -1; } if ((cwd_len = path__cwd(out, (int)len)) < 0) return -1; /* UNC paths */ if (wcsncmp(L"\\\\", out, 2) == 0) { /* Our buffer must be at least 5 characters larger than the * current working directory: we swallow one of the leading * '\'s, but we we add a 'UNC' specifier to the path, plus * a trailing directory separator, plus a NUL. */ if (cwd_len > GIT_WIN_PATH_MAX - 4) { errno = ENAMETOOLONG; return -1; } memmove(out+2, out, sizeof(wchar_t) * cwd_len); out[0] = L'U'; out[1] = L'N'; out[2] = L'C'; cwd_len += 2; } /* Our buffer must be at least 2 characters larger than the current * working directory. (One character for the directory separator, * one for the null. */ else if (cwd_len > GIT_WIN_PATH_MAX - 2) { errno = ENAMETOOLONG; return -1; } return cwd_len; } int git_win32_path_from_utf8(git_win32_path out, const char *src) { wchar_t *dest = out; /* All win32 paths are in NT-prefixed format, beginning with "\\?\". */ memcpy(dest, PATH__NT_NAMESPACE, sizeof(wchar_t) * PATH__NT_NAMESPACE_LEN); dest += PATH__NT_NAMESPACE_LEN; /* See if this is an absolute path (beginning with a drive letter) */ if (git_path_is_absolute(src)) { if (git__utf8_to_16(dest, GIT_WIN_PATH_MAX, src) < 0) goto on_error; } /* File-prefixed NT-style paths beginning with \\?\ */ else if (path__is_nt_namespace(src)) { /* Skip the NT prefix, the destination already contains it */ if (git__utf8_to_16(dest, GIT_WIN_PATH_MAX, src + PATH__NT_NAMESPACE_LEN) < 0) goto on_error; } /* UNC paths */ else if (path__is_unc(src)) { memcpy(dest, L"UNC\\", sizeof(wchar_t) * 4); dest += 4; /* Skip the leading "\\" */ if (git__utf8_to_16(dest, GIT_WIN_PATH_MAX - 2, src + 2) < 0) goto on_error; } /* Absolute paths omitting the drive letter */ else if (path__startswith_slash(src)) { if (path__cwd(dest, GIT_WIN_PATH_MAX) < 0) goto on_error; if (!git_path_is_absolute(dest)) { errno = ENOENT; goto on_error; } /* Skip the drive letter specification ("C:") */ if (git__utf8_to_16(dest + 2, GIT_WIN_PATH_MAX - 2, src) < 0) goto on_error; } /* Relative paths */ else { int cwd_len; if ((cwd_len = win32_path_cwd(dest, GIT_WIN_PATH_MAX)) < 0) goto on_error; dest[cwd_len++] = L'\\'; if (git__utf8_to_16(dest + cwd_len, GIT_WIN_PATH_MAX - cwd_len, src) < 0) goto on_error; } return git_win32_path_canonicalize(out); on_error: /* set windows error code so we can use its error message */ if (errno == ENAMETOOLONG) SetLastError(ERROR_FILENAME_EXCED_RANGE); return -1; } int git_win32_path_relative_from_utf8(git_win32_path out, const char *src) { wchar_t *dest = out, *p; int len; /* Handle absolute paths */ if (git_path_is_absolute(src) || path__is_nt_namespace(src) || path__is_unc(src) || path__startswith_slash(src)) { return git_win32_path_from_utf8(out, src); } if ((len = git__utf8_to_16(dest, GIT_WIN_PATH_MAX, src)) < 0) return -1; for (p = dest; p < (dest + len); p++) { if (*p == L'/') *p = L'\\'; } return len; } int git_win32_path_to_utf8(git_win32_utf8_path dest, const wchar_t *src) { char *out = dest; int len; /* Strip NT namespacing "\\?\" */ if (path__is_nt_namespace(src)) { src += 4; /* "\\?\UNC\server\share" -> "\\server\share" */ if (wcsncmp(src, L"UNC\\", 4) == 0) { src += 4; memcpy(dest, "\\\\", 2); out = dest + 2; } } if ((len = git__utf16_to_8(out, GIT_WIN_PATH_UTF8, src)) < 0) return len; git_path_mkposix(dest); return len; } char *git_win32_path_8dot3_name(const char *path) { git_win32_path longpath, shortpath; wchar_t *start; char *shortname; int len, namelen = 1; if (git_win32_path_from_utf8(longpath, path) < 0) return NULL; len = GetShortPathNameW(longpath, shortpath, GIT_WIN_PATH_UTF16); while (len && shortpath[len-1] == L'\\') shortpath[--len] = L'\0'; if (len == 0 || len >= GIT_WIN_PATH_UTF16) return NULL; for (start = shortpath + (len - 1); start > shortpath && *(start-1) != '/' && *(start-1) != '\\'; start--) namelen++; /* We may not have actually been given a short name. But if we have, * it will be in the ASCII byte range, so we don't need to worry about * multi-byte sequences and can allocate naively. */ if (namelen > 12 || (shortname = git__malloc(namelen + 1)) == NULL) return NULL; if ((len = git__utf16_to_8(shortname, namelen + 1, start)) < 0) return NULL; return shortname; } static bool path_is_volume(wchar_t *target, size_t target_len) { return (target_len && wcsncmp(target, L"\\??\\Volume{", 11) == 0); } /* On success, returns the length, in characters, of the path stored in dest. * On failure, returns a negative value. */ int git_win32_path_readlink_w(git_win32_path dest, const git_win32_path path) { BYTE buf[MAXIMUM_REPARSE_DATA_BUFFER_SIZE]; GIT_REPARSE_DATA_BUFFER *reparse_buf = (GIT_REPARSE_DATA_BUFFER *)buf; HANDLE handle = NULL; DWORD ioctl_ret; wchar_t *target; size_t target_len; int error = -1; handle = CreateFileW(path, GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_DELETE, NULL, OPEN_EXISTING, FILE_FLAG_OPEN_REPARSE_POINT | FILE_FLAG_BACKUP_SEMANTICS, NULL); if (handle == INVALID_HANDLE_VALUE) { errno = ENOENT; return -1; } if (!DeviceIoControl(handle, FSCTL_GET_REPARSE_POINT, NULL, 0, reparse_buf, sizeof(buf), &ioctl_ret, NULL)) { errno = EINVAL; goto on_error; } switch (reparse_buf->ReparseTag) { case IO_REPARSE_TAG_SYMLINK: target = reparse_buf->ReparseBuffer.SymbolicLink.PathBuffer + (reparse_buf->ReparseBuffer.SymbolicLink.SubstituteNameOffset / sizeof(WCHAR)); target_len = reparse_buf->ReparseBuffer.SymbolicLink.SubstituteNameLength / sizeof(WCHAR); break; case IO_REPARSE_TAG_MOUNT_POINT: target = reparse_buf->ReparseBuffer.MountPoint.PathBuffer + (reparse_buf->ReparseBuffer.MountPoint.SubstituteNameOffset / sizeof(WCHAR)); target_len = reparse_buf->ReparseBuffer.MountPoint.SubstituteNameLength / sizeof(WCHAR); break; default: errno = EINVAL; goto on_error; } if (path_is_volume(target, target_len)) { /* This path is a reparse point that represents another volume mounted * at this location, it is not a symbolic link our input was canonical. */ errno = EINVAL; error = -1; } else if (target_len) { /* The path may need to have a namespace prefix removed. */ target_len = git_win32_path_remove_namespace(target, target_len); /* Need one additional character in the target buffer * for the terminating NULL. */ if (GIT_WIN_PATH_UTF16 > target_len) { wcscpy(dest, target); error = (int)target_len; } } on_error: CloseHandle(handle); return error; } /** * Removes any trailing backslashes from a path, except in the case of a drive * letter path (C:\, D:\, etc.). This function cannot fail. * * @param path The path which should be trimmed. * @return The length of the modified string (<= the input length) */ size_t git_win32_path_trim_end(wchar_t *str, size_t len) { while (1) { if (!len || str[len - 1] != L'\\') break; /* * Don't trim backslashes from drive letter paths, which * are 3 characters long and of the form C:\, D:\, etc. */ if (len == 3 && git_win32__isalpha(str[0]) && str[1] == ':') break; len--; } str[len] = L'\0'; return len; } /** * Removes any of the following namespace prefixes from a path, * if found: "\??\", "\\?\", "\\?\UNC\". This function cannot fail. * * @param path The path which should be converted. * @return The length of the modified string (<= the input length) */ size_t git_win32_path_remove_namespace(wchar_t *str, size_t len) { static const wchar_t dosdevices_namespace[] = L"\\\?\?\\"; static const wchar_t nt_namespace[] = L"\\\\?\\"; static const wchar_t unc_namespace_remainder[] = L"UNC\\"; static const wchar_t unc_prefix[] = L"\\\\"; const wchar_t *prefix = NULL, *remainder = NULL; size_t prefix_len = 0, remainder_len = 0; /* "\??\" -- DOS Devices prefix */ if (len >= CONST_STRLEN(dosdevices_namespace) && !wcsncmp(str, dosdevices_namespace, CONST_STRLEN(dosdevices_namespace))) { remainder = str + CONST_STRLEN(dosdevices_namespace); remainder_len = len - CONST_STRLEN(dosdevices_namespace); } /* "\\?\" -- NT namespace prefix */ else if (len >= CONST_STRLEN(nt_namespace) && !wcsncmp(str, nt_namespace, CONST_STRLEN(nt_namespace))) { remainder = str + CONST_STRLEN(nt_namespace); remainder_len = len - CONST_STRLEN(nt_namespace); } /* "\??\UNC\", "\\?\UNC\" -- UNC prefix */ if (remainder_len >= CONST_STRLEN(unc_namespace_remainder) && !wcsncmp(remainder, unc_namespace_remainder, CONST_STRLEN(unc_namespace_remainder))) { /* * The proper Win32 path for a UNC share has "\\" at beginning of it * and looks like "\\server\share\<folderStructure>". So remove the * UNC namespace and add a prefix of "\\" in its place. */ remainder += CONST_STRLEN(unc_namespace_remainder); remainder_len -= CONST_STRLEN(unc_namespace_remainder); prefix = unc_prefix; prefix_len = CONST_STRLEN(unc_prefix); } /* * Sanity check that the new string isn't longer than the old one. * (This could only happen due to programmer error introducing a * prefix longer than the namespace it replaces.) */ if (remainder && len >= remainder_len + prefix_len) { if (prefix) memmove(str, prefix, prefix_len * sizeof(wchar_t)); memmove(str + prefix_len, remainder, remainder_len * sizeof(wchar_t)); len = remainder_len + prefix_len; str[len] = L'\0'; } return git_win32_path_trim_end(str, len); }
0
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2/src
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2/src/win32/thread.c
/* * Copyright (C) the libgit2 contributors. All rights reserved. * * This file is part of libgit2, distributed under the GNU GPL v2 with * a Linking Exception. For full terms see the included COPYING file. */ #include "thread.h" #include "runtime.h" #define CLEAN_THREAD_EXIT 0x6F012842 typedef void (WINAPI *win32_srwlock_fn)(GIT_SRWLOCK *); static win32_srwlock_fn win32_srwlock_initialize; static win32_srwlock_fn win32_srwlock_acquire_shared; static win32_srwlock_fn win32_srwlock_release_shared; static win32_srwlock_fn win32_srwlock_acquire_exclusive; static win32_srwlock_fn win32_srwlock_release_exclusive; static DWORD fls_index; /* The thread procedure stub used to invoke the caller's procedure * and capture the return value for later collection. Windows will * only hold a DWORD, but we need to be able to store an entire * void pointer. This requires the indirection. */ static DWORD WINAPI git_win32__threadproc(LPVOID lpParameter) { git_thread *thread = lpParameter; /* Set the current thread for `git_thread_exit` */ FlsSetValue(fls_index, thread); thread->result = thread->proc(thread->param); return CLEAN_THREAD_EXIT; } static void git_threads_global_shutdown(void) { FlsFree(fls_index); } int git_threads_global_init(void) { HMODULE hModule = GetModuleHandleW(L"kernel32"); if (hModule) { win32_srwlock_initialize = (win32_srwlock_fn)(void *) GetProcAddress(hModule, "InitializeSRWLock"); win32_srwlock_acquire_shared = (win32_srwlock_fn)(void *) GetProcAddress(hModule, "AcquireSRWLockShared"); win32_srwlock_release_shared = (win32_srwlock_fn)(void *) GetProcAddress(hModule, "ReleaseSRWLockShared"); win32_srwlock_acquire_exclusive = (win32_srwlock_fn)(void *) GetProcAddress(hModule, "AcquireSRWLockExclusive"); win32_srwlock_release_exclusive = (win32_srwlock_fn)(void *) GetProcAddress(hModule, "ReleaseSRWLockExclusive"); } if ((fls_index = FlsAlloc(NULL)) == FLS_OUT_OF_INDEXES) return -1; return git_runtime_shutdown_register(git_threads_global_shutdown); } int git_thread_create( git_thread *GIT_RESTRICT thread, void *(*start_routine)(void*), void *GIT_RESTRICT arg) { thread->result = NULL; thread->param = arg; thread->proc = start_routine; thread->thread = CreateThread( NULL, 0, git_win32__threadproc, thread, 0, NULL); return thread->thread ? 0 : -1; } int git_thread_join( git_thread *thread, void **value_ptr) { DWORD exit; if (WaitForSingleObject(thread->thread, INFINITE) != WAIT_OBJECT_0) return -1; if (!GetExitCodeThread(thread->thread, &exit)) { CloseHandle(thread->thread); return -1; } /* Check for the thread having exited uncleanly. If exit was unclean, * then we don't have a return value to give back to the caller. */ GIT_ASSERT(exit == CLEAN_THREAD_EXIT); if (value_ptr) *value_ptr = thread->result; CloseHandle(thread->thread); return 0; } void git_thread_exit(void *value) { git_thread *thread = FlsGetValue(fls_index); if (thread) thread->result = value; ExitThread(CLEAN_THREAD_EXIT); } size_t git_thread_currentid(void) { return GetCurrentThreadId(); } int git_mutex_init(git_mutex *GIT_RESTRICT mutex) { InitializeCriticalSection(mutex); return 0; } int git_mutex_free(git_mutex *mutex) { DeleteCriticalSection(mutex); return 0; } int git_mutex_lock(git_mutex *mutex) { EnterCriticalSection(mutex); return 0; } int git_mutex_unlock(git_mutex *mutex) { LeaveCriticalSection(mutex); return 0; } int git_cond_init(git_cond *cond) { /* This is an auto-reset event. */ *cond = CreateEventW(NULL, FALSE, FALSE, NULL); GIT_ASSERT(*cond); /* If we can't create the event, claim that the reason was out-of-memory. * The actual reason can be fetched with GetLastError(). */ return *cond ? 0 : ENOMEM; } int git_cond_free(git_cond *cond) { BOOL closed; if (!cond) return EINVAL; closed = CloseHandle(*cond); GIT_ASSERT(closed); GIT_UNUSED(closed); *cond = NULL; return 0; } int git_cond_wait(git_cond *cond, git_mutex *mutex) { int error; DWORD wait_result; if (!cond || !mutex) return EINVAL; /* The caller must be holding the mutex. */ error = git_mutex_unlock(mutex); if (error) return error; wait_result = WaitForSingleObject(*cond, INFINITE); GIT_ASSERT(WAIT_OBJECT_0 == wait_result); GIT_UNUSED(wait_result); return git_mutex_lock(mutex); } int git_cond_signal(git_cond *cond) { BOOL signaled; if (!cond) return EINVAL; signaled = SetEvent(*cond); GIT_ASSERT(signaled); GIT_UNUSED(signaled); return 0; } int git_rwlock_init(git_rwlock *GIT_RESTRICT lock) { if (win32_srwlock_initialize) win32_srwlock_initialize(&lock->native.srwl); else InitializeCriticalSection(&lock->native.csec); return 0; } int git_rwlock_rdlock(git_rwlock *lock) { if (win32_srwlock_acquire_shared) win32_srwlock_acquire_shared(&lock->native.srwl); else EnterCriticalSection(&lock->native.csec); return 0; } int git_rwlock_rdunlock(git_rwlock *lock) { if (win32_srwlock_release_shared) win32_srwlock_release_shared(&lock->native.srwl); else LeaveCriticalSection(&lock->native.csec); return 0; } int git_rwlock_wrlock(git_rwlock *lock) { if (win32_srwlock_acquire_exclusive) win32_srwlock_acquire_exclusive(&lock->native.srwl); else EnterCriticalSection(&lock->native.csec); return 0; } int git_rwlock_wrunlock(git_rwlock *lock) { if (win32_srwlock_release_exclusive) win32_srwlock_release_exclusive(&lock->native.srwl); else LeaveCriticalSection(&lock->native.csec); return 0; } int git_rwlock_free(git_rwlock *lock) { if (!win32_srwlock_initialize) DeleteCriticalSection(&lock->native.csec); git__memzero(lock, sizeof(*lock)); return 0; }
0
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2/src
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2/src/win32/git2.rc
#include <winver.h> #include "../../include/git2/version.h" #ifndef LIBGIT2_FILENAME # ifdef __GNUC__ # define LIBGIT2_FILENAME git2 # else # define LIBGIT2_FILENAME "git2" # endif #endif #ifndef LIBGIT2_COMMENTS # define LIBGIT2_COMMENTS "For more information visit http://libgit2.github.com/" #endif #ifdef __GNUC__ # define _STR(x) #x # define STR(x) _STR(x) #else # define STR(x) x #endif #ifdef __GNUC__ VS_VERSION_INFO VERSIONINFO #else VS_VERSION_INFO VERSIONINFO MOVEABLE IMPURE LOADONCALL DISCARDABLE #endif FILEVERSION LIBGIT2_VER_MAJOR,LIBGIT2_VER_MINOR,LIBGIT2_VER_REVISION,LIBGIT2_VER_PATCH PRODUCTVERSION LIBGIT2_VER_MAJOR,LIBGIT2_VER_MINOR,LIBGIT2_VER_REVISION,LIBGIT2_VER_PATCH FILEFLAGSMASK VS_FFI_FILEFLAGSMASK #ifdef _DEBUG FILEFLAGS VS_FF_DEBUG #else FILEFLAGS 0 #endif FILEOS VOS_NT_WINDOWS32 FILETYPE VFT_DLL FILESUBTYPE VFT2_UNKNOWN BEGIN BLOCK "StringFileInfo" BEGIN BLOCK "040904E4" //language ID = U.S. English, char set = Windows, Multilingual BEGIN VALUE "FileDescription", "libgit2 - the Git linkable library\0" VALUE "FileVersion", LIBGIT2_VERSION "\0" VALUE "InternalName", STR(LIBGIT2_FILENAME) ".dll\0" VALUE "LegalCopyright", "Copyright (C) the libgit2 contributors. All rights reserved.\0" VALUE "OriginalFilename", STR(LIBGIT2_FILENAME) ".dll\0" VALUE "ProductName", "libgit2\0" VALUE "ProductVersion", LIBGIT2_VERSION "\0" VALUE "Comments", LIBGIT2_COMMENTS "\0" END END BLOCK "VarFileInfo" BEGIN VALUE "Translation", 0x0409, 1252 END END
0
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2/src
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2/src/win32/mingw-compat.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_win32_mingw_compat_h__ #define INCLUDE_win32_mingw_compat_h__ #if defined(__MINGW32__) #undef stat #if _WIN32_WINNT < 0x0600 && !defined(__MINGW64_VERSION_MAJOR) #undef MemoryBarrier void __mingworg_MemoryBarrier(void); #define MemoryBarrier __mingworg_MemoryBarrier #define VOLUME_NAME_DOS 0x0 #endif #endif #endif
0
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2/src
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2/src/win32/posix_w32.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 "../posix.h" #include "../futils.h" #include "path.h" #include "path_w32.h" #include "utf-conv.h" #include "repository.h" #include "reparse.h" #include "buffer.h" #include <errno.h> #include <io.h> #include <fcntl.h> #include <ws2tcpip.h> #ifndef FILE_NAME_NORMALIZED # define FILE_NAME_NORMALIZED 0 #endif #ifndef IO_REPARSE_TAG_SYMLINK #define IO_REPARSE_TAG_SYMLINK (0xA000000CL) #endif #ifndef SYMBOLIC_LINK_FLAG_ALLOW_UNPRIVILEGED_CREATE # define SYMBOLIC_LINK_FLAG_ALLOW_UNPRIVILEGED_CREATE 0x02 #endif #ifndef SYMBOLIC_LINK_FLAG_DIRECTORY # define SYMBOLIC_LINK_FLAG_DIRECTORY 0x01 #endif /* Allowable mode bits on Win32. Using mode bits that are not supported on * Win32 (eg S_IRWXU) is generally ignored, but Wine warns loudly about it * so we simply remove them. */ #define WIN32_MODE_MASK (_S_IREAD | _S_IWRITE) unsigned long git_win32__createfile_sharemode = FILE_SHARE_READ | FILE_SHARE_WRITE; int git_win32__retries = 10; GIT_INLINE(void) set_errno(void) { switch (GetLastError()) { case ERROR_FILE_NOT_FOUND: case ERROR_PATH_NOT_FOUND: case ERROR_INVALID_DRIVE: case ERROR_NO_MORE_FILES: case ERROR_BAD_NETPATH: case ERROR_BAD_NET_NAME: case ERROR_BAD_PATHNAME: case ERROR_FILENAME_EXCED_RANGE: errno = ENOENT; break; case ERROR_BAD_ENVIRONMENT: errno = E2BIG; break; case ERROR_BAD_FORMAT: case ERROR_INVALID_STARTING_CODESEG: case ERROR_INVALID_STACKSEG: case ERROR_INVALID_MODULETYPE: case ERROR_INVALID_EXE_SIGNATURE: case ERROR_EXE_MARKED_INVALID: case ERROR_BAD_EXE_FORMAT: case ERROR_ITERATED_DATA_EXCEEDS_64k: case ERROR_INVALID_MINALLOCSIZE: case ERROR_DYNLINK_FROM_INVALID_RING: case ERROR_IOPL_NOT_ENABLED: case ERROR_INVALID_SEGDPL: case ERROR_AUTODATASEG_EXCEEDS_64k: case ERROR_RING2SEG_MUST_BE_MOVABLE: case ERROR_RELOC_CHAIN_XEEDS_SEGLIM: case ERROR_INFLOOP_IN_RELOC_CHAIN: errno = ENOEXEC; break; case ERROR_INVALID_HANDLE: case ERROR_INVALID_TARGET_HANDLE: case ERROR_DIRECT_ACCESS_HANDLE: errno = EBADF; break; case ERROR_WAIT_NO_CHILDREN: case ERROR_CHILD_NOT_COMPLETE: errno = ECHILD; break; case ERROR_NO_PROC_SLOTS: case ERROR_MAX_THRDS_REACHED: case ERROR_NESTING_NOT_ALLOWED: errno = EAGAIN; break; case ERROR_ARENA_TRASHED: case ERROR_NOT_ENOUGH_MEMORY: case ERROR_INVALID_BLOCK: case ERROR_NOT_ENOUGH_QUOTA: errno = ENOMEM; break; case ERROR_ACCESS_DENIED: case ERROR_CURRENT_DIRECTORY: case ERROR_WRITE_PROTECT: case ERROR_BAD_UNIT: case ERROR_NOT_READY: case ERROR_BAD_COMMAND: case ERROR_CRC: case ERROR_BAD_LENGTH: case ERROR_SEEK: case ERROR_NOT_DOS_DISK: case ERROR_SECTOR_NOT_FOUND: case ERROR_OUT_OF_PAPER: case ERROR_WRITE_FAULT: case ERROR_READ_FAULT: case ERROR_GEN_FAILURE: case ERROR_SHARING_VIOLATION: case ERROR_LOCK_VIOLATION: case ERROR_WRONG_DISK: case ERROR_SHARING_BUFFER_EXCEEDED: case ERROR_NETWORK_ACCESS_DENIED: case ERROR_CANNOT_MAKE: case ERROR_FAIL_I24: case ERROR_DRIVE_LOCKED: case ERROR_SEEK_ON_DEVICE: case ERROR_NOT_LOCKED: case ERROR_LOCK_FAILED: errno = EACCES; break; case ERROR_FILE_EXISTS: case ERROR_ALREADY_EXISTS: errno = EEXIST; break; case ERROR_NOT_SAME_DEVICE: errno = EXDEV; break; case ERROR_INVALID_FUNCTION: case ERROR_INVALID_ACCESS: case ERROR_INVALID_DATA: case ERROR_INVALID_PARAMETER: case ERROR_NEGATIVE_SEEK: errno = EINVAL; break; case ERROR_TOO_MANY_OPEN_FILES: errno = EMFILE; break; case ERROR_DISK_FULL: errno = ENOSPC; break; case ERROR_BROKEN_PIPE: errno = EPIPE; break; case ERROR_DIR_NOT_EMPTY: errno = ENOTEMPTY; break; default: errno = EINVAL; } } GIT_INLINE(bool) last_error_retryable(void) { int os_error = GetLastError(); return (os_error == ERROR_SHARING_VIOLATION || os_error == ERROR_ACCESS_DENIED); } #define do_with_retries(fn, remediation) \ do { \ int __retry, __ret; \ for (__retry = git_win32__retries; __retry; __retry--) { \ if ((__ret = (fn)) != GIT_RETRY) \ return __ret; \ if (__retry > 1 && (__ret = (remediation)) != 0) { \ if (__ret == GIT_RETRY) \ continue; \ return __ret; \ } \ Sleep(5); \ } \ return -1; \ } while (0) \ static int ensure_writable(wchar_t *path) { DWORD attrs; if ((attrs = GetFileAttributesW(path)) == INVALID_FILE_ATTRIBUTES) goto on_error; if ((attrs & FILE_ATTRIBUTE_READONLY) == 0) return 0; if (!SetFileAttributesW(path, (attrs & ~FILE_ATTRIBUTE_READONLY))) goto on_error; return GIT_RETRY; on_error: set_errno(); return -1; } /** * Truncate or extend file. * * We now take a "git_off_t" rather than "long" because * files may be longer than 2Gb. */ int p_ftruncate(int fd, off64_t size) { if (size < 0) { errno = EINVAL; return -1; } #if !defined(__MINGW32__) || defined(MINGW_HAS_SECURE_API) return ((_chsize_s(fd, size) == 0) ? 0 : -1); #else /* TODO MINGW32 Find a replacement for _chsize() that handles big files. */ if (size > INT32_MAX) { errno = EFBIG; return -1; } return _chsize(fd, (long)size); #endif } int p_mkdir(const char *path, mode_t mode) { git_win32_path buf; GIT_UNUSED(mode); if (git_win32_path_from_utf8(buf, path) < 0) return -1; return _wmkdir(buf); } int p_link(const char *old, const char *new) { GIT_UNUSED(old); GIT_UNUSED(new); errno = ENOSYS; return -1; } GIT_INLINE(int) unlink_once(const wchar_t *path) { DWORD error; if (DeleteFileW(path)) return 0; if ((error = GetLastError()) == ERROR_ACCESS_DENIED) { WIN32_FILE_ATTRIBUTE_DATA fdata; if (!GetFileAttributesExW(path, GetFileExInfoStandard, &fdata) || !(fdata.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT) || !(fdata.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)) goto out; if (RemoveDirectoryW(path)) return 0; } out: SetLastError(error); if (last_error_retryable()) return GIT_RETRY; set_errno(); return -1; } int p_unlink(const char *path) { git_win32_path wpath; if (git_win32_path_from_utf8(wpath, path) < 0) return -1; do_with_retries(unlink_once(wpath), ensure_writable(wpath)); } int p_fsync(int fd) { HANDLE fh = (HANDLE)_get_osfhandle(fd); p_fsync__cnt++; if (fh == INVALID_HANDLE_VALUE) { errno = EBADF; return -1; } if (!FlushFileBuffers(fh)) { DWORD code = GetLastError(); if (code == ERROR_INVALID_HANDLE) errno = EINVAL; else errno = EIO; return -1; } return 0; } #define WIN32_IS_WSEP(CH) ((CH) == L'/' || (CH) == L'\\') static int lstat_w( wchar_t *path, struct stat *buf, bool posix_enotdir) { WIN32_FILE_ATTRIBUTE_DATA fdata; if (GetFileAttributesExW(path, GetFileExInfoStandard, &fdata)) { if (!buf) return 0; return git_win32__file_attribute_to_stat(buf, &fdata, path); } switch (GetLastError()) { case ERROR_ACCESS_DENIED: errno = EACCES; break; default: errno = ENOENT; break; } /* To match POSIX behavior, set ENOTDIR when any of the folders in the * file path is a regular file, otherwise set ENOENT. */ if (errno == ENOENT && posix_enotdir) { size_t path_len = wcslen(path); /* scan up path until we find an existing item */ while (1) { DWORD attrs; /* remove last directory component */ for (path_len--; path_len > 0 && !WIN32_IS_WSEP(path[path_len]); path_len--); if (path_len <= 0) break; path[path_len] = L'\0'; attrs = GetFileAttributesW(path); if (attrs != INVALID_FILE_ATTRIBUTES) { if (!(attrs & FILE_ATTRIBUTE_DIRECTORY)) errno = ENOTDIR; break; } } } return -1; } static int do_lstat(const char *path, struct stat *buf, bool posixly_correct) { git_win32_path path_w; int len; if ((len = git_win32_path_from_utf8(path_w, path)) < 0) return -1; git_win32_path_trim_end(path_w, len); return lstat_w(path_w, buf, posixly_correct); } int p_lstat(const char *filename, struct stat *buf) { return do_lstat(filename, buf, false); } int p_lstat_posixly(const char *filename, struct stat *buf) { return do_lstat(filename, buf, true); } int p_readlink(const char *path, char *buf, size_t bufsiz) { git_win32_path path_w, target_w; git_win32_utf8_path target; int len; /* readlink(2) does not NULL-terminate the string written * to the target buffer. Furthermore, the target buffer need * not be large enough to hold the entire result. A truncated * result should be written in this case. Since this truncation * could occur in the middle of the encoding of a code point, * we need to buffer the result on the stack. */ if (git_win32_path_from_utf8(path_w, path) < 0 || git_win32_path_readlink_w(target_w, path_w) < 0 || (len = git_win32_path_to_utf8(target, target_w)) < 0) return -1; bufsiz = min((size_t)len, bufsiz); memcpy(buf, target, bufsiz); return (int)bufsiz; } static bool target_is_dir(const char *target, const char *path) { git_buf resolved = GIT_BUF_INIT; git_win32_path resolved_w; bool isdir = true; if (git_path_is_absolute(target)) git_win32_path_from_utf8(resolved_w, target); else if (git_path_dirname_r(&resolved, path) < 0 || git_path_apply_relative(&resolved, target) < 0 || git_win32_path_from_utf8(resolved_w, resolved.ptr) < 0) goto out; isdir = GetFileAttributesW(resolved_w) & FILE_ATTRIBUTE_DIRECTORY; out: git_buf_dispose(&resolved); return isdir; } int p_symlink(const char *target, const char *path) { git_win32_path target_w, path_w; DWORD dwFlags; /* * Convert both target and path to Windows-style paths. Note that we do * not want to use `git_win32_path_from_utf8` for converting the target, * as that function will automatically pre-pend the current working * directory in case the path is not absolute. As Git will instead use * relative symlinks, this is not someting we want. */ if (git_win32_path_from_utf8(path_w, path) < 0 || git_win32_path_relative_from_utf8(target_w, target) < 0) return -1; dwFlags = SYMBOLIC_LINK_FLAG_ALLOW_UNPRIVILEGED_CREATE; if (target_is_dir(target, path)) dwFlags |= SYMBOLIC_LINK_FLAG_DIRECTORY; if (!CreateSymbolicLinkW(path_w, target_w, dwFlags)) return -1; return 0; } struct open_opts { DWORD access; DWORD sharing; SECURITY_ATTRIBUTES security; DWORD creation_disposition; DWORD attributes; int osf_flags; }; GIT_INLINE(void) open_opts_from_posix(struct open_opts *opts, int flags, mode_t mode) { memset(opts, 0, sizeof(struct open_opts)); switch (flags & (O_WRONLY | O_RDWR)) { case O_WRONLY: opts->access = GENERIC_WRITE; break; case O_RDWR: opts->access = GENERIC_READ | GENERIC_WRITE; break; default: opts->access = GENERIC_READ; break; } opts->sharing = (DWORD)git_win32__createfile_sharemode; switch (flags & (O_CREAT | O_TRUNC | O_EXCL)) { case O_CREAT | O_EXCL: case O_CREAT | O_TRUNC | O_EXCL: opts->creation_disposition = CREATE_NEW; break; case O_CREAT | O_TRUNC: opts->creation_disposition = CREATE_ALWAYS; break; case O_TRUNC: opts->creation_disposition = TRUNCATE_EXISTING; break; case O_CREAT: opts->creation_disposition = OPEN_ALWAYS; break; default: opts->creation_disposition = OPEN_EXISTING; break; } opts->attributes = ((flags & O_CREAT) && !(mode & S_IWRITE)) ? FILE_ATTRIBUTE_READONLY : FILE_ATTRIBUTE_NORMAL; opts->osf_flags = flags & (O_RDONLY | O_APPEND); opts->security.nLength = sizeof(SECURITY_ATTRIBUTES); opts->security.lpSecurityDescriptor = NULL; opts->security.bInheritHandle = 0; } GIT_INLINE(int) open_once( const wchar_t *path, struct open_opts *opts) { int fd; HANDLE handle = CreateFileW(path, opts->access, opts->sharing, &opts->security, opts->creation_disposition, opts->attributes, 0); if (handle == INVALID_HANDLE_VALUE) { if (last_error_retryable()) return GIT_RETRY; set_errno(); return -1; } if ((fd = _open_osfhandle((intptr_t)handle, opts->osf_flags)) < 0) CloseHandle(handle); return fd; } int p_open(const char *path, int flags, ...) { git_win32_path wpath; mode_t mode = 0; struct open_opts opts = {0}; #ifdef GIT_DEBUG_STRICT_OPEN if (strstr(path, "//") != NULL) { errno = EACCES; return -1; } #endif if (git_win32_path_from_utf8(wpath, path) < 0) return -1; if (flags & O_CREAT) { va_list arg_list; va_start(arg_list, flags); mode = (mode_t)va_arg(arg_list, int); va_end(arg_list); } open_opts_from_posix(&opts, flags, mode); do_with_retries( open_once(wpath, &opts), 0); } int p_creat(const char *path, mode_t mode) { return p_open(path, O_WRONLY | O_CREAT | O_TRUNC, mode); } int p_utimes(const char *path, const struct p_timeval times[2]) { git_win32_path wpath; int fd, error; DWORD attrs_orig, attrs_new = 0; struct open_opts opts = { 0 }; if (git_win32_path_from_utf8(wpath, path) < 0) return -1; attrs_orig = GetFileAttributesW(wpath); if (attrs_orig & FILE_ATTRIBUTE_READONLY) { attrs_new = attrs_orig & ~FILE_ATTRIBUTE_READONLY; if (!SetFileAttributesW(wpath, attrs_new)) { git_error_set(GIT_ERROR_OS, "failed to set attributes"); return -1; } } open_opts_from_posix(&opts, O_RDWR, 0); if ((fd = open_once(wpath, &opts)) < 0) { error = -1; goto done; } error = p_futimes(fd, times); close(fd); done: if (attrs_orig != attrs_new) { DWORD os_error = GetLastError(); SetFileAttributesW(wpath, attrs_orig); SetLastError(os_error); } return error; } int p_futimes(int fd, const struct p_timeval times[2]) { HANDLE handle; FILETIME atime = { 0 }, mtime = { 0 }; if (times == NULL) { SYSTEMTIME st; GetSystemTime(&st); SystemTimeToFileTime(&st, &atime); SystemTimeToFileTime(&st, &mtime); } else { git_win32__timeval_to_filetime(&atime, times[0]); git_win32__timeval_to_filetime(&mtime, times[1]); } if ((handle = (HANDLE)_get_osfhandle(fd)) == INVALID_HANDLE_VALUE) return -1; if (SetFileTime(handle, NULL, &atime, &mtime) == 0) return -1; return 0; } int p_getcwd(char *buffer_out, size_t size) { git_win32_path buf; wchar_t *cwd = _wgetcwd(buf, GIT_WIN_PATH_UTF16); if (!cwd) return -1; git_win32_path_remove_namespace(cwd, wcslen(cwd)); /* Convert the working directory back to UTF-8 */ if (git__utf16_to_8(buffer_out, size, cwd) < 0) { DWORD code = GetLastError(); if (code == ERROR_INSUFFICIENT_BUFFER) errno = ERANGE; else errno = EINVAL; return -1; } git_path_mkposix(buffer_out); return 0; } static int getfinalpath_w( git_win32_path dest, const wchar_t *path) { HANDLE hFile; DWORD dwChars; /* Use FILE_FLAG_BACKUP_SEMANTICS so we can open a directory. Do not * specify FILE_FLAG_OPEN_REPARSE_POINT; we want to open a handle to the * target of the link. */ hFile = CreateFileW(path, GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_DELETE, NULL, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL); if (INVALID_HANDLE_VALUE == hFile) return -1; /* Call GetFinalPathNameByHandle */ dwChars = GetFinalPathNameByHandleW(hFile, dest, GIT_WIN_PATH_UTF16, FILE_NAME_NORMALIZED); CloseHandle(hFile); if (!dwChars || dwChars >= GIT_WIN_PATH_UTF16) return -1; /* The path may be delivered to us with a namespace prefix; remove */ return (int)git_win32_path_remove_namespace(dest, dwChars); } static int follow_and_lstat_link(git_win32_path path, struct stat *buf) { git_win32_path target_w; if (getfinalpath_w(target_w, path) < 0) return -1; return lstat_w(target_w, buf, false); } int p_fstat(int fd, struct stat *buf) { BY_HANDLE_FILE_INFORMATION fhInfo; HANDLE fh = (HANDLE)_get_osfhandle(fd); if (fh == INVALID_HANDLE_VALUE || !GetFileInformationByHandle(fh, &fhInfo)) { errno = EBADF; return -1; } git_win32__file_information_to_stat(buf, &fhInfo); return 0; } int p_stat(const char *path, struct stat *buf) { git_win32_path path_w; int len; if ((len = git_win32_path_from_utf8(path_w, path)) < 0 || lstat_w(path_w, buf, false) < 0) return -1; /* The item is a symbolic link or mount point. No need to iterate * to follow multiple links; use GetFinalPathNameFromHandle. */ if (S_ISLNK(buf->st_mode)) return follow_and_lstat_link(path_w, buf); return 0; } int p_chdir(const char *path) { git_win32_path buf; if (git_win32_path_from_utf8(buf, path) < 0) return -1; return _wchdir(buf); } int p_chmod(const char *path, mode_t mode) { git_win32_path buf; if (git_win32_path_from_utf8(buf, path) < 0) return -1; return _wchmod(buf, mode); } int p_rmdir(const char *path) { git_win32_path buf; int error; if (git_win32_path_from_utf8(buf, path) < 0) return -1; error = _wrmdir(buf); if (error == -1) { switch (GetLastError()) { /* _wrmdir() is documented to return EACCES if "A program has an open * handle to the directory." This sounds like what everybody else calls * EBUSY. Let's convert appropriate error codes. */ case ERROR_SHARING_VIOLATION: errno = EBUSY; break; /* This error can be returned when trying to rmdir an extant file. */ case ERROR_DIRECTORY: errno = ENOTDIR; break; } } return error; } char *p_realpath(const char *orig_path, char *buffer) { git_win32_path orig_path_w, buffer_w; if (git_win32_path_from_utf8(orig_path_w, orig_path) < 0) return NULL; /* Note that if the path provided is a relative path, then the current directory * is used to resolve the path -- which is a concurrency issue because the current * directory is a process-wide variable. */ if (!GetFullPathNameW(orig_path_w, GIT_WIN_PATH_UTF16, buffer_w, NULL)) { if (GetLastError() == ERROR_INSUFFICIENT_BUFFER) errno = ENAMETOOLONG; else errno = EINVAL; return NULL; } /* The path must exist. */ if (GetFileAttributesW(buffer_w) == INVALID_FILE_ATTRIBUTES) { errno = ENOENT; return NULL; } if (!buffer && !(buffer = git__malloc(GIT_WIN_PATH_UTF8))) { errno = ENOMEM; return NULL; } /* Convert the path to UTF-8. If the caller provided a buffer, then it * is assumed to be GIT_WIN_PATH_UTF8 characters in size. If it isn't, * then we may overflow. */ if (git_win32_path_to_utf8(buffer, buffer_w) < 0) return NULL; git_path_mkposix(buffer); return buffer; } int p_vsnprintf(char *buffer, size_t count, const char *format, va_list argptr) { #if defined(_MSC_VER) int len; if (count == 0) return _vscprintf(format, argptr); #if _MSC_VER >= 1500 len = _vsnprintf_s(buffer, count, _TRUNCATE, format, argptr); #else len = _vsnprintf(buffer, count, format, argptr); #endif if (len < 0) return _vscprintf(format, argptr); return len; #else /* MinGW */ return vsnprintf(buffer, count, format, argptr); #endif } int p_snprintf(char *buffer, size_t count, const char *format, ...) { va_list va; int r; va_start(va, format); r = p_vsnprintf(buffer, count, format, va); va_end(va); return r; } /* TODO: wut? */ int p_mkstemp(char *tmp_path) { #if defined(_MSC_VER) && _MSC_VER >= 1500 if (_mktemp_s(tmp_path, strlen(tmp_path) + 1) != 0) return -1; #else if (_mktemp(tmp_path) == NULL) return -1; #endif return p_open(tmp_path, O_RDWR | O_CREAT | O_EXCL, 0744); /* -V536 */ } int p_access(const char *path, mode_t mode) { git_win32_path buf; if (git_win32_path_from_utf8(buf, path) < 0) return -1; return _waccess(buf, mode & WIN32_MODE_MASK); } GIT_INLINE(int) rename_once(const wchar_t *from, const wchar_t *to) { if (MoveFileExW(from, to, MOVEFILE_REPLACE_EXISTING | MOVEFILE_COPY_ALLOWED)) return 0; if (last_error_retryable()) return GIT_RETRY; set_errno(); return -1; } int p_rename(const char *from, const char *to) { git_win32_path wfrom, wto; if (git_win32_path_from_utf8(wfrom, from) < 0 || git_win32_path_from_utf8(wto, to) < 0) return -1; do_with_retries(rename_once(wfrom, wto), ensure_writable(wto)); } int p_recv(GIT_SOCKET socket, void *buffer, size_t length, int flags) { if ((size_t)((int)length) != length) return -1; /* git_error_set will be done by caller */ return recv(socket, buffer, (int)length, flags); } int p_send(GIT_SOCKET socket, const void *buffer, size_t length, int flags) { if ((size_t)((int)length) != length) return -1; /* git_error_set will be done by caller */ return send(socket, buffer, (int)length, flags); } /** * Borrowed from http://old.nabble.com/Porting-localtime_r-and-gmtime_r-td15282276.html * On Win32, `gmtime_r` doesn't exist but `gmtime` is threadsafe, so we can use that */ struct tm * p_localtime_r (const time_t *timer, struct tm *result) { struct tm *local_result; local_result = localtime (timer); if (local_result == NULL || result == NULL) return NULL; memcpy (result, local_result, sizeof (struct tm)); return result; } struct tm * p_gmtime_r (const time_t *timer, struct tm *result) { struct tm *local_result; local_result = gmtime (timer); if (local_result == NULL || result == NULL) return NULL; memcpy (result, local_result, sizeof (struct tm)); return result; } int p_inet_pton(int af, const char *src, void *dst) { struct sockaddr_storage sin; void *addr; int sin_len = sizeof(struct sockaddr_storage), addr_len; int error = 0; if (af == AF_INET) { addr = &((struct sockaddr_in *)&sin)->sin_addr; addr_len = sizeof(struct in_addr); } else if (af == AF_INET6) { addr = &((struct sockaddr_in6 *)&sin)->sin6_addr; addr_len = sizeof(struct in6_addr); } else { errno = EAFNOSUPPORT; return -1; } if ((error = WSAStringToAddressA((LPSTR)src, af, NULL, (LPSOCKADDR)&sin, &sin_len)) == 0) { memcpy(dst, addr, addr_len); return 1; } switch(WSAGetLastError()) { case WSAEINVAL: return 0; case WSAEFAULT: errno = ENOSPC; return -1; case WSA_NOT_ENOUGH_MEMORY: errno = ENOMEM; return -1; } errno = EINVAL; return -1; } ssize_t p_pread(int fd, void *data, size_t size, off64_t offset) { HANDLE fh; DWORD rsize = 0; OVERLAPPED ov = {0}; LARGE_INTEGER pos = {0}; off64_t final_offset = 0; /* Fail if the final offset would have overflowed to match POSIX semantics. */ if (!git__is_ssizet(size) || git__add_int64_overflow(&final_offset, offset, (int64_t)size)) { errno = EINVAL; return -1; } /* * Truncate large writes to the maximum allowable size: the caller * needs to always call this in a loop anyways. */ if (size > INT32_MAX) { size = INT32_MAX; } pos.QuadPart = offset; ov.Offset = pos.LowPart; ov.OffsetHigh = pos.HighPart; fh = (HANDLE)_get_osfhandle(fd); if (ReadFile(fh, data, (DWORD)size, &rsize, &ov)) { return (ssize_t)rsize; } set_errno(); return -1; } ssize_t p_pwrite(int fd, const void *data, size_t size, off64_t offset) { HANDLE fh; DWORD wsize = 0; OVERLAPPED ov = {0}; LARGE_INTEGER pos = {0}; off64_t final_offset = 0; /* Fail if the final offset would have overflowed to match POSIX semantics. */ if (!git__is_ssizet(size) || git__add_int64_overflow(&final_offset, offset, (int64_t)size)) { errno = EINVAL; return -1; } /* * Truncate large writes to the maximum allowable size: the caller * needs to always call this in a loop anyways. */ if (size > INT32_MAX) { size = INT32_MAX; } pos.QuadPart = offset; ov.Offset = pos.LowPart; ov.OffsetHigh = pos.HighPart; fh = (HANDLE)_get_osfhandle(fd); if (WriteFile(fh, data, (DWORD)size, &wsize, &ov)) { return (ssize_t)wsize; } set_errno(); return -1; }
0
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2/src
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2/src/win32/dir.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 "dir.h" #define GIT__WIN32_NO_WRAP_DIR #include "posix.h" git__DIR *git__opendir(const char *dir) { git_win32_path filter_w; git__DIR *new = NULL; size_t dirlen, alloclen; if (!dir || !git_win32__findfirstfile_filter(filter_w, dir)) return NULL; dirlen = strlen(dir); if (GIT_ADD_SIZET_OVERFLOW(&alloclen, sizeof(*new), dirlen) || GIT_ADD_SIZET_OVERFLOW(&alloclen, alloclen, 1) || !(new = git__calloc(1, alloclen))) return NULL; memcpy(new->dir, dir, dirlen); new->h = FindFirstFileW(filter_w, &new->f); if (new->h == INVALID_HANDLE_VALUE) { git_error_set(GIT_ERROR_OS, "could not open directory '%s'", dir); git__free(new); return NULL; } new->first = 1; return new; } int git__readdir_ext( git__DIR *d, struct git__dirent *entry, struct git__dirent **result, int *is_dir) { if (!d || !entry || !result || d->h == INVALID_HANDLE_VALUE) return -1; *result = NULL; if (d->first) d->first = 0; else if (!FindNextFileW(d->h, &d->f)) { if (GetLastError() == ERROR_NO_MORE_FILES) return 0; git_error_set(GIT_ERROR_OS, "could not read from directory '%s'", d->dir); return -1; } /* Convert the path to UTF-8 */ if (git_win32_path_to_utf8(entry->d_name, d->f.cFileName) < 0) return -1; entry->d_ino = 0; *result = entry; if (is_dir != NULL) *is_dir = ((d->f.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) != 0); return 0; } struct git__dirent *git__readdir(git__DIR *d) { struct git__dirent *result; if (git__readdir_ext(d, &d->entry, &result, NULL) < 0) return NULL; return result; } void git__rewinddir(git__DIR *d) { git_win32_path filter_w; if (!d) return; if (d->h != INVALID_HANDLE_VALUE) { FindClose(d->h); d->h = INVALID_HANDLE_VALUE; d->first = 0; } if (!git_win32__findfirstfile_filter(filter_w, d->dir)) return; d->h = FindFirstFileW(filter_w, &d->f); if (d->h == INVALID_HANDLE_VALUE) git_error_set(GIT_ERROR_OS, "could not open directory '%s'", d->dir); else d->first = 1; } int git__closedir(git__DIR *d) { if (!d) return 0; if (d->h != INVALID_HANDLE_VALUE) { FindClose(d->h); d->h = INVALID_HANDLE_VALUE; } git__free(d); return 0; }
0
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2/src
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2/src/win32/map.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 "map.h" #include <errno.h> #ifndef NO_MMAP static DWORD get_page_size(void) { static DWORD page_size; SYSTEM_INFO sys; if (!page_size) { GetSystemInfo(&sys); page_size = sys.dwPageSize; } return page_size; } static DWORD get_allocation_granularity(void) { static DWORD granularity; SYSTEM_INFO sys; if (!granularity) { GetSystemInfo(&sys); granularity = sys.dwAllocationGranularity; } return granularity; } int git__page_size(size_t *page_size) { *page_size = get_page_size(); return 0; } int git__mmap_alignment(size_t *page_size) { *page_size = get_allocation_granularity(); return 0; } int p_mmap(git_map *out, size_t len, int prot, int flags, int fd, off64_t offset) { HANDLE fh = (HANDLE)_get_osfhandle(fd); DWORD alignment = get_allocation_granularity(); DWORD fmap_prot = 0; DWORD view_prot = 0; DWORD off_low = 0; DWORD off_hi = 0; off64_t page_start; off64_t page_offset; GIT_MMAP_VALIDATE(out, len, prot, flags); out->data = NULL; out->len = 0; out->fmh = NULL; if (fh == INVALID_HANDLE_VALUE) { errno = EBADF; git_error_set(GIT_ERROR_OS, "failed to mmap. Invalid handle value"); return -1; } if (prot & GIT_PROT_WRITE) fmap_prot |= PAGE_READWRITE; else if (prot & GIT_PROT_READ) fmap_prot |= PAGE_READONLY; if (prot & GIT_PROT_WRITE) view_prot |= FILE_MAP_WRITE; if (prot & GIT_PROT_READ) view_prot |= FILE_MAP_READ; page_start = (offset / alignment) * alignment; page_offset = offset - page_start; if (page_offset != 0) { /* offset must be multiple of the allocation granularity */ errno = EINVAL; git_error_set(GIT_ERROR_OS, "failed to mmap. Offset must be multiple of allocation granularity"); return -1; } out->fmh = CreateFileMapping(fh, NULL, fmap_prot, 0, 0, NULL); if (!out->fmh || out->fmh == INVALID_HANDLE_VALUE) { git_error_set(GIT_ERROR_OS, "failed to mmap. Invalid handle value"); out->fmh = NULL; return -1; } off_low = (DWORD)(page_start); off_hi = (DWORD)(page_start >> 32); out->data = MapViewOfFile(out->fmh, view_prot, off_hi, off_low, len); if (!out->data) { git_error_set(GIT_ERROR_OS, "failed to mmap. No data written"); CloseHandle(out->fmh); out->fmh = NULL; return -1; } out->len = len; return 0; } int p_munmap(git_map *map) { int error = 0; GIT_ASSERT_ARG(map); if (map->data) { if (!UnmapViewOfFile(map->data)) { git_error_set(GIT_ERROR_OS, "failed to munmap. Could not unmap view of file"); error = -1; } map->data = NULL; } if (map->fmh) { if (!CloseHandle(map->fmh)) { git_error_set(GIT_ERROR_OS, "failed to munmap. Could not close handle"); error = -1; } map->fmh = NULL; } return error; } #endif
0
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2/src
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2/src/win32/version.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_win32_version_h__ #define INCLUDE_win32_version_h__ #include <windows.h> GIT_INLINE(int) git_has_win32_version(int major, int minor, int service_pack) { OSVERSIONINFOEX version_test = {0}; DWORD version_test_mask; DWORDLONG version_condition_mask = 0; version_test.dwOSVersionInfoSize = sizeof(OSVERSIONINFOEX); version_test.dwMajorVersion = major; version_test.dwMinorVersion = minor; version_test.wServicePackMajor = (WORD)service_pack; version_test.wServicePackMinor = 0; version_test_mask = (VER_MAJORVERSION | VER_MINORVERSION | VER_SERVICEPACKMAJOR | VER_SERVICEPACKMINOR); VER_SET_CONDITION(version_condition_mask, VER_MAJORVERSION, VER_GREATER_EQUAL); VER_SET_CONDITION(version_condition_mask, VER_MINORVERSION, VER_GREATER_EQUAL); VER_SET_CONDITION(version_condition_mask, VER_SERVICEPACKMAJOR, VER_GREATER_EQUAL); VER_SET_CONDITION(version_condition_mask, VER_SERVICEPACKMINOR, VER_GREATER_EQUAL); if (!VerifyVersionInfo(&version_test, version_test_mask, version_condition_mask)) return 0; return 1; } #endif
0
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2/src
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2/src/win32/precompiled.c
#include "precompiled.h"
0
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2/src
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2/src/win32/w32_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 "w32_util.h" /** * Creates a FindFirstFile(Ex) filter string from a UTF-8 path. * The filter string enumerates all items in the directory. * * @param dest The buffer to receive the filter string. * @param src The UTF-8 path of the directory to enumerate. * @return True if the filter string was created successfully; false otherwise */ bool git_win32__findfirstfile_filter(git_win32_path dest, const char *src) { static const wchar_t suffix[] = L"\\*"; int len = git_win32_path_from_utf8(dest, src); /* Ensure the path was converted */ if (len < 0) return false; /* Ensure that the path does not end with a trailing slash, * because we're about to add one. Don't rely our trim_end * helper, because we want to remove the backslash even for * drive letter paths, in this case. */ if (len > 0 && (dest[len - 1] == L'/' || dest[len - 1] == L'\\')) { dest[len - 1] = L'\0'; len--; } /* Ensure we have enough room to add the suffix */ if ((size_t)len >= GIT_WIN_PATH_UTF16 - CONST_STRLEN(suffix)) return false; wcscat(dest, suffix); return true; } /** * Ensures the given path (file or folder) has the +H (hidden) attribute set. * * @param path The path which should receive the +H bit. * @return 0 on success; -1 on failure */ int git_win32__set_hidden(const char *path, bool hidden) { git_win32_path buf; DWORD attrs, newattrs; if (git_win32_path_from_utf8(buf, path) < 0) return -1; attrs = GetFileAttributesW(buf); /* Ensure the path exists */ if (attrs == INVALID_FILE_ATTRIBUTES) return -1; if (hidden) newattrs = attrs | FILE_ATTRIBUTE_HIDDEN; else newattrs = attrs & ~FILE_ATTRIBUTE_HIDDEN; if (attrs != newattrs && !SetFileAttributesW(buf, newattrs)) { git_error_set(GIT_ERROR_OS, "failed to %s hidden bit for '%s'", hidden ? "set" : "unset", path); return -1; } return 0; } int git_win32__hidden(bool *out, const char *path) { git_win32_path buf; DWORD attrs; if (git_win32_path_from_utf8(buf, path) < 0) return -1; attrs = GetFileAttributesW(buf); /* Ensure the path exists */ if (attrs == INVALID_FILE_ATTRIBUTES) return -1; *out = (attrs & FILE_ATTRIBUTE_HIDDEN) ? true : false; return 0; } int git_win32__file_attribute_to_stat( struct stat *st, const WIN32_FILE_ATTRIBUTE_DATA *attrdata, const wchar_t *path) { git_win32__stat_init(st, attrdata->dwFileAttributes, attrdata->nFileSizeHigh, attrdata->nFileSizeLow, attrdata->ftCreationTime, attrdata->ftLastAccessTime, attrdata->ftLastWriteTime); if (attrdata->dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT && path) { git_win32_path target; if (git_win32_path_readlink_w(target, path) >= 0) { st->st_mode = (st->st_mode & ~S_IFMT) | S_IFLNK; /* st_size gets the UTF-8 length of the target name, in bytes, * not counting the NULL terminator */ if ((st->st_size = git__utf16_to_8(NULL, 0, target)) < 0) { git_error_set(GIT_ERROR_OS, "could not convert reparse point name for '%ls'", path); return -1; } } } return 0; }
0
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2/src
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2/src/win32/reparse.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_win32_reparse_h__ #define INCLUDE_win32_reparse_h__ /* This structure is defined on MSDN at * http://msdn.microsoft.com/en-us/library/windows/hardware/ff552012(v=vs.85).aspx * * It was formerly included in the Windows 2000 SDK and remains defined in * MinGW, so we must define it with a silly name to avoid conflicting. */ typedef struct _GIT_REPARSE_DATA_BUFFER { ULONG ReparseTag; USHORT ReparseDataLength; USHORT Reserved; union { struct { USHORT SubstituteNameOffset; USHORT SubstituteNameLength; USHORT PrintNameOffset; USHORT PrintNameLength; ULONG Flags; WCHAR PathBuffer[1]; } SymbolicLink; struct { USHORT SubstituteNameOffset; USHORT SubstituteNameLength; USHORT PrintNameOffset; USHORT PrintNameLength; WCHAR PathBuffer[1]; } MountPoint; struct { UCHAR DataBuffer[1]; } Generic; } ReparseBuffer; } GIT_REPARSE_DATA_BUFFER; #define REPARSE_DATA_HEADER_SIZE 8 #define REPARSE_DATA_MOUNTPOINT_HEADER_SIZE 8 #define REPARSE_DATA_UNION_SIZE 12 /* Missing in MinGW */ #ifndef FSCTL_GET_REPARSE_POINT # define FSCTL_GET_REPARSE_POINT 0x000900a8 #endif /* Missing in MinGW */ #ifndef FSCTL_SET_REPARSE_POINT # define FSCTL_SET_REPARSE_POINT 0x000900a4 #endif #endif
0
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2/src
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2/src/win32/dir.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_win32_dir_h__ #define INCLUDE_win32_dir_h__ #include "common.h" #include "w32_util.h" struct git__dirent { int d_ino; git_win32_utf8_path d_name; }; typedef struct { HANDLE h; WIN32_FIND_DATAW f; struct git__dirent entry; int first; char dir[GIT_FLEX_ARRAY]; } git__DIR; extern git__DIR *git__opendir(const char *); extern struct git__dirent *git__readdir(git__DIR *); extern int git__readdir_ext( git__DIR *, struct git__dirent *, struct git__dirent **, int *); extern void git__rewinddir(git__DIR *); extern int git__closedir(git__DIR *); # ifndef GIT__WIN32_NO_WRAP_DIR # define dirent git__dirent # define DIR git__DIR # define opendir git__opendir # define readdir git__readdir # define readdir_r(d,e,r) git__readdir_ext((d),(e),(r),NULL) # define rewinddir git__rewinddir # define closedir git__closedir # endif #endif
0
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2/src
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2/src/win32/w32_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_win32_w32_common_h__ #define INCLUDE_win32_w32_common_h__ #include <git2/common.h> /* * 4096 is the max allowed Git path. `MAX_PATH` (260) is the typical max allowed * Windows path length, however win32 Unicode APIs generally allow up to 32,767 * if prefixed with "\\?\" (i.e. converted to an NT-style name). */ #define GIT_WIN_PATH_MAX GIT_PATH_MAX /* * Provides a large enough buffer to support Windows Git paths: * GIT_WIN_PATH_MAX is 4096, corresponding to a maximum path length of 4095 * characters plus a NULL terminator. Prefixing with "\\?\" adds 4 characters, * but if the original was a UNC path, then we turn "\\server\share" into * "\\?\UNC\server\share". So we replace the first two characters with * 8 characters, a net gain of 6, so the maximum length is GIT_WIN_PATH_MAX+6. */ #define GIT_WIN_PATH_UTF16 GIT_WIN_PATH_MAX+6 /* Maximum size of a UTF-8 Win32 Git path. We remove the "\\?\" or "\\?\UNC\" * prefixes for presentation, bringing us back to 4095 (non-NULL) * characters. UTF-8 does have 4-byte sequences, but they are encoded in * UTF-16 using surrogate pairs, which takes up the space of two characters. * Two characters in the range U+0800 -> U+FFFF take up more space in UTF-8 * (6 bytes) than one surrogate pair (4 bytes). */ #define GIT_WIN_PATH_UTF8 ((GIT_WIN_PATH_MAX - 1) * 3 + 1) /* * The length of a Windows "shortname", for 8.3 compatibility. */ #define GIT_WIN_PATH_SHORTNAME 13 /* Win32 path types */ typedef wchar_t git_win32_path[GIT_WIN_PATH_UTF16]; typedef char git_win32_utf8_path[GIT_WIN_PATH_UTF8]; #endif
0
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2/src
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2/src/win32/w32_buffer.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 "w32_buffer.h" #include "../buffer.h" #include "utf-conv.h" GIT_INLINE(int) handle_wc_error(void) { if (GetLastError() == ERROR_INSUFFICIENT_BUFFER) errno = ENAMETOOLONG; else errno = EINVAL; return -1; } int git_buf_put_w(git_buf *buf, const wchar_t *string_w, size_t len_w) { int utf8_len, utf8_write_len; size_t new_size; if (!len_w) { return 0; } else if (len_w > INT_MAX) { git_error_set_oom(); return -1; } GIT_ASSERT(string_w); /* Measure the string necessary for conversion */ if ((utf8_len = WideCharToMultiByte(CP_UTF8, WC_ERR_INVALID_CHARS, string_w, (int)len_w, NULL, 0, NULL, NULL)) == 0) return 0; GIT_ASSERT(utf8_len > 0); GIT_ERROR_CHECK_ALLOC_ADD(&new_size, buf->size, (size_t)utf8_len); GIT_ERROR_CHECK_ALLOC_ADD(&new_size, new_size, 1); if (git_buf_grow(buf, new_size) < 0) return -1; if ((utf8_write_len = WideCharToMultiByte( CP_UTF8, WC_ERR_INVALID_CHARS, string_w, (int)len_w, &buf->ptr[buf->size], utf8_len, NULL, NULL)) == 0) return handle_wc_error(); GIT_ASSERT(utf8_write_len == utf8_len); buf->size += utf8_write_len; buf->ptr[buf->size] = '\0'; return 0; }
0
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2/src
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2/src/win32/w32_leakcheck.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_win32_leakcheck_h__ #define INCLUDE_win32_leakcheck_h__ #include "common.h" /* Initialize the win32 leak checking system. */ int git_win32_leakcheck_global_init(void); #if defined(GIT_WIN32_LEAKCHECK) #include <stdlib.h> #include <crtdbg.h> #include "git2/errors.h" #include "strnlen.h" bool git_win32_leakcheck_has_leaks(void); /* Stack frames (for stack tracing, below) */ /** * This type defines a callback to be used to augment a C stacktrace * with "aux" data. This can be used, for example, to allow LibGit2Sharp * (or other interpreted consumer libraries) to give us C# stacktrace * data for the PInvoke. * * This callback will be called during crtdbg-instrumented allocs. * * @param aux_id [out] A returned "aux_id" representing a unique * (de-duped at the C# layer) stacktrace. "aux_id" 0 is reserved * to mean no aux stacktrace data. */ typedef void (*git_win32_leakcheck_stack_aux_cb_alloc)(unsigned int *aux_id); /** * This type defines a callback to be used to augment the output of * a stacktrace. This will be used to request the C# layer format * the C# stacktrace associated with "aux_id" into the provided * buffer. * * This callback will be called during leak reporting. * * @param aux_id The "aux_id" key associated with a stacktrace. * @param aux_msg A buffer where a formatted message should be written. * @param aux_msg_len The size of the buffer. */ typedef void (*git_win32_leakcheck_stack_aux_cb_lookup)(unsigned int aux_id, char *aux_msg, size_t aux_msg_len); /** * Register an "aux" data provider to augment our C stacktrace data. * * This can be used, for example, to allow LibGit2Sharp (or other * interpreted consumer libraries) to give us the C# stacktrace of * the PInvoke. * * If you choose to use this feature, it should be registered during * initialization and not changed for the duration of the process. */ int git_win32_leakcheck_stack_set_aux_cb( git_win32_leakcheck_stack_aux_cb_alloc cb_alloc, git_win32_leakcheck_stack_aux_cb_lookup cb_lookup); /** * Maximum number of stackframes to record for a * single stacktrace. */ #define GIT_WIN32_LEAKCHECK_STACK_MAX_FRAMES 30 /** * Wrapper containing the raw unprocessed stackframe * data for a single stacktrace and any "aux_id". * * I put the aux_id first so leaks will be sorted by it. * So, for example, if a specific callstack in C# leaks * a repo handle, all of the pointers within the associated * repo pointer will be grouped together. */ typedef struct { unsigned int aux_id; unsigned int nr_frames; void *frames[GIT_WIN32_LEAKCHECK_STACK_MAX_FRAMES]; } git_win32_leakcheck_stack_raw_data; /** * Capture raw stack trace data for the current process/thread. * * @param skip Number of initial frames to skip. Pass 0 to * begin with the caller of this routine. Pass 1 to begin * with its caller. And so on. */ int git_win32_leakcheck_stack_capture(git_win32_leakcheck_stack_raw_data *pdata, int skip); /** * Compare 2 raw stacktraces with the usual -1,0,+1 result. * This includes any "aux_id" values in the comparison, so that * our de-dup is also "aux" context relative. */ int git_win32_leakcheck_stack_compare( git_win32_leakcheck_stack_raw_data *d1, git_win32_leakcheck_stack_raw_data *d2); /** * Format raw stacktrace data into buffer WITHOUT using any mallocs. * * @param prefix String written before each frame; defaults to "\t". * @param suffix String written after each frame; defaults to "\n". */ int git_win32_leakcheck_stack_format( char *pbuf, size_t buf_len, const git_win32_leakcheck_stack_raw_data *pdata, const char *prefix, const char *suffix); /** * Convenience routine to capture and format stacktrace into * a buffer WITHOUT using any mallocs. This is primarily a * wrapper for testing. * * @param skip Number of initial frames to skip. Pass 0 to * begin with the caller of this routine. Pass 1 to begin * with its caller. And so on. * @param prefix String written before each frame; defaults to "\t". * @param suffix String written after each frame; defaults to "\n". */ int git_win32_leakcheck_stack( char * pbuf, size_t buf_len, int skip, const char *prefix, const char *suffix); /* Stack tracing */ /* MSVC CRTDBG memory leak reporting. * * We DO NOT use the "_CRTDBG_MAP_ALLOC" macro described in the MSVC * documentation because all allocs/frees in libgit2 already go through * the "git__" routines defined in this file. Simply using the normal * reporting mechanism causes all leaks to be attributed to a routine * here in util.h (ie, the actual call to calloc()) rather than the * caller of git__calloc(). * * Therefore, we declare a set of "git__crtdbg__" routines to replace * the corresponding "git__" routines and re-define the "git__" symbols * as macros. This allows us to get and report the file:line info of * the real caller. * * We DO NOT replace the "git__free" routine because it needs to remain * a function pointer because it is used as a function argument when * setting up various structure "destructors". * * We also DO NOT use the "_CRTDBG_MAP_ALLOC" macro because it causes * "free" to be remapped to "_free_dbg" and this causes problems for * structures which define a field named "free". * * Finally, CRTDBG must be explicitly enabled and configured at program * startup. See tests/main.c for an example. */ /** * Checkpoint options. */ typedef enum git_win32_leakcheck_stacktrace_options { /** * Set checkpoint marker. */ GIT_WIN32_LEAKCHECK_STACKTRACE_SET_MARK = (1 << 0), /** * Dump leaks since last checkpoint marker. * May not be combined with _LEAKS_TOTAL. * * Note that this may generate false positives for global TLS * error state and other global caches that aren't cleaned up * until the thread/process terminates. So when using this * around a region of interest, also check the final (at exit) * dump before digging into leaks reported here. */ GIT_WIN32_LEAKCHECK_STACKTRACE_LEAKS_SINCE_MARK = (1 << 1), /** * Dump leaks since init. May not be combined * with _LEAKS_SINCE_MARK. */ GIT_WIN32_LEAKCHECK_STACKTRACE_LEAKS_TOTAL = (1 << 2), /** * Suppress printing during dumps. * Just return leak count. */ GIT_WIN32_LEAKCHECK_STACKTRACE_QUIET = (1 << 3), } git_win32_leakcheck_stacktrace_options; /** * Checkpoint memory state and/or dump unique stack traces of * current memory leaks. * * @return number of unique leaks (relative to requested starting * point) or error. */ int git_win32_leakcheck_stacktrace_dump( git_win32_leakcheck_stacktrace_options opt, const char *label); /** * Construct stacktrace and append it to the global buffer. * Return pointer to start of this string. On any error or * lack of buffer space, just return the given file buffer * so it will behave as usual. * * This should ONLY be called by our internal memory allocations * routines. */ const char *git_win32_leakcheck_stacktrace(int skip, const char *file); #endif #endif
0
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2/src
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2/src/allocators/failalloc.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 "failalloc.h" void *git_failalloc_malloc(size_t len, const char *file, int line) { GIT_UNUSED(len); GIT_UNUSED(file); GIT_UNUSED(line); return NULL; } void *git_failalloc_calloc(size_t nelem, size_t elsize, const char *file, int line) { GIT_UNUSED(nelem); GIT_UNUSED(elsize); GIT_UNUSED(file); GIT_UNUSED(line); return NULL; } char *git_failalloc_strdup(const char *str, const char *file, int line) { GIT_UNUSED(str); GIT_UNUSED(file); GIT_UNUSED(line); return NULL; } char *git_failalloc_strndup(const char *str, size_t n, const char *file, int line) { GIT_UNUSED(str); GIT_UNUSED(n); GIT_UNUSED(file); GIT_UNUSED(line); return NULL; } char *git_failalloc_substrdup(const char *start, size_t n, const char *file, int line) { GIT_UNUSED(start); GIT_UNUSED(n); GIT_UNUSED(file); GIT_UNUSED(line); return NULL; } void *git_failalloc_realloc(void *ptr, size_t size, const char *file, int line) { GIT_UNUSED(ptr); GIT_UNUSED(size); GIT_UNUSED(file); GIT_UNUSED(line); return NULL; } void *git_failalloc_reallocarray(void *ptr, size_t nelem, size_t elsize, const char *file, int line) { GIT_UNUSED(ptr); GIT_UNUSED(nelem); GIT_UNUSED(elsize); GIT_UNUSED(file); GIT_UNUSED(line); return NULL; } void *git_failalloc_mallocarray(size_t nelem, size_t elsize, const char *file, int line) { GIT_UNUSED(nelem); GIT_UNUSED(elsize); GIT_UNUSED(file); GIT_UNUSED(line); return NULL; } void git_failalloc_free(void *ptr) { GIT_UNUSED(ptr); }
0
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2/src
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2/src/allocators/win32_leakcheck.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 "win32_leakcheck.h" #if defined(GIT_WIN32_LEAKCHECK) #include "win32/w32_leakcheck.h" static void *leakcheck_malloc(size_t len, const char *file, int line) { void *ptr = _malloc_dbg(len, _NORMAL_BLOCK, git_win32_leakcheck_stacktrace(1,file), line); if (!ptr) git_error_set_oom(); return ptr; } static void *leakcheck_calloc(size_t nelem, size_t elsize, const char *file, int line) { void *ptr = _calloc_dbg(nelem, elsize, _NORMAL_BLOCK, git_win32_leakcheck_stacktrace(1,file), line); if (!ptr) git_error_set_oom(); return ptr; } static char *leakcheck_strdup(const char *str, const char *file, int line) { char *ptr = _strdup_dbg(str, _NORMAL_BLOCK, git_win32_leakcheck_stacktrace(1,file), line); if (!ptr) git_error_set_oom(); return ptr; } static char *leakcheck_strndup(const char *str, size_t n, const char *file, int line) { size_t length = 0, alloclength; char *ptr; length = p_strnlen(str, n); if (GIT_ADD_SIZET_OVERFLOW(&alloclength, length, 1) || !(ptr = leakcheck_malloc(alloclength, file, line))) return NULL; if (length) memcpy(ptr, str, length); ptr[length] = '\0'; return ptr; } static char *leakcheck_substrdup(const char *start, size_t n, const char *file, int line) { char *ptr; size_t alloclen; if (GIT_ADD_SIZET_OVERFLOW(&alloclen, n, 1) || !(ptr = leakcheck_malloc(alloclen, file, line))) return NULL; memcpy(ptr, start, n); ptr[n] = '\0'; return ptr; } static void *leakcheck_realloc(void *ptr, size_t size, const char *file, int line) { void *new_ptr = _realloc_dbg(ptr, size, _NORMAL_BLOCK, git_win32_leakcheck_stacktrace(1,file), line); if (!new_ptr) git_error_set_oom(); return new_ptr; } static void *leakcheck_reallocarray(void *ptr, size_t nelem, size_t elsize, const char *file, int line) { size_t newsize; if (GIT_MULTIPLY_SIZET_OVERFLOW(&newsize, nelem, elsize)) return NULL; return leakcheck_realloc(ptr, newsize, file, line); } static void *leakcheck_mallocarray(size_t nelem, size_t elsize, const char *file, int line) { return leakcheck_reallocarray(NULL, nelem, elsize, file, line); } static void leakcheck_free(void *ptr) { free(ptr); } int git_win32_leakcheck_init_allocator(git_allocator *allocator) { allocator->gmalloc = leakcheck_malloc; allocator->gcalloc = leakcheck_calloc; allocator->gstrdup = leakcheck_strdup; allocator->gstrndup = leakcheck_strndup; allocator->gsubstrdup = leakcheck_substrdup; allocator->grealloc = leakcheck_realloc; allocator->greallocarray = leakcheck_reallocarray; allocator->gmallocarray = leakcheck_mallocarray; allocator->gfree = leakcheck_free; return 0; } #else int git_win32_leakcheck_init_allocator(git_allocator *allocator) { GIT_UNUSED(allocator); git_error_set(GIT_EINVALID, "leakcheck memory allocator not available"); return -1; } #endif
0
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2/src
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2/src/allocators/stdalloc.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 "stdalloc.h" static void *stdalloc__malloc(size_t len, const char *file, int line) { void *ptr; GIT_UNUSED(file); GIT_UNUSED(line); #ifdef GIT_DEBUG_STRICT_ALLOC if (!len) return NULL; #endif ptr = malloc(len); if (!ptr) git_error_set_oom(); return ptr; } static void *stdalloc__calloc(size_t nelem, size_t elsize, const char *file, int line) { void *ptr; GIT_UNUSED(file); GIT_UNUSED(line); #ifdef GIT_DEBUG_STRICT_ALLOC if (!elsize || !nelem) return NULL; #endif ptr = calloc(nelem, elsize); if (!ptr) git_error_set_oom(); return ptr; } static char *stdalloc__strdup(const char *str, const char *file, int line) { char *ptr; GIT_UNUSED(file); GIT_UNUSED(line); ptr = strdup(str); if (!ptr) git_error_set_oom(); return ptr; } static char *stdalloc__strndup(const char *str, size_t n, const char *file, int line) { size_t length = 0, alloclength; char *ptr; length = p_strnlen(str, n); if (GIT_ADD_SIZET_OVERFLOW(&alloclength, length, 1) || !(ptr = stdalloc__malloc(alloclength, file, line))) return NULL; if (length) memcpy(ptr, str, length); ptr[length] = '\0'; return ptr; } static char *stdalloc__substrdup(const char *start, size_t n, const char *file, int line) { char *ptr; size_t alloclen; if (GIT_ADD_SIZET_OVERFLOW(&alloclen, n, 1) || !(ptr = stdalloc__malloc(alloclen, file, line))) return NULL; memcpy(ptr, start, n); ptr[n] = '\0'; return ptr; } static void *stdalloc__realloc(void *ptr, size_t size, const char *file, int line) { void *new_ptr; GIT_UNUSED(file); GIT_UNUSED(line); #ifdef GIT_DEBUG_STRICT_ALLOC if (!size) return NULL; #endif new_ptr = realloc(ptr, size); if (!new_ptr) git_error_set_oom(); return new_ptr; } static void *stdalloc__reallocarray(void *ptr, size_t nelem, size_t elsize, const char *file, int line) { size_t newsize; if (GIT_MULTIPLY_SIZET_OVERFLOW(&newsize, nelem, elsize)) return NULL; return stdalloc__realloc(ptr, newsize, file, line); } static void *stdalloc__mallocarray(size_t nelem, size_t elsize, const char *file, int line) { return stdalloc__reallocarray(NULL, nelem, elsize, file, line); } static void stdalloc__free(void *ptr) { free(ptr); } int git_stdalloc_init_allocator(git_allocator *allocator) { allocator->gmalloc = stdalloc__malloc; allocator->gcalloc = stdalloc__calloc; allocator->gstrdup = stdalloc__strdup; allocator->gstrndup = stdalloc__strndup; allocator->gsubstrdup = stdalloc__substrdup; allocator->grealloc = stdalloc__realloc; allocator->greallocarray = stdalloc__reallocarray; allocator->gmallocarray = stdalloc__mallocarray; allocator->gfree = stdalloc__free; return 0; }
0
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2/src
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2/src/allocators/win32_leakcheck.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_allocators_win32_leakcheck_h #define INCLUDE_allocators_win32_leakcheck_h #include "common.h" #include "alloc.h" int git_win32_leakcheck_init_allocator(git_allocator *allocator); #endif
0
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2/src
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2/src/allocators/stdalloc.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_allocators_stdalloc_h__ #define INCLUDE_allocators_stdalloc_h__ #include "common.h" #include "alloc.h" int git_stdalloc_init_allocator(git_allocator *allocator); #endif
0
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2/src
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2/src/allocators/failalloc.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_allocators_failalloc_h__ #define INCLUDE_allocators_failalloc_h__ #include "common.h" extern void *git_failalloc_malloc(size_t len, const char *file, int line); extern void *git_failalloc_calloc(size_t nelem, size_t elsize, const char *file, int line); extern char *git_failalloc_strdup(const char *str, const char *file, int line); extern char *git_failalloc_strndup(const char *str, size_t n, const char *file, int line); extern char *git_failalloc_substrdup(const char *start, size_t n, const char *file, int line); extern void *git_failalloc_realloc(void *ptr, size_t size, const char *file, int line); extern void *git_failalloc_reallocarray(void *ptr, size_t nelem, size_t elsize, const char *file, int line); extern void *git_failalloc_mallocarray(size_t nelem, size_t elsize, const char *file, int line); extern void git_failalloc_free(void *ptr); #endif
0
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2/fuzzers/commit_graph_fuzzer.c
/* * libgit2 commit-graph fuzzer target. * * 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 <stdio.h> #include "git2.h" #include "buffer.h" #include "common.h" #include "futils.h" #include "hash.h" #include "commit_graph.h" int LLVMFuzzerInitialize(int *argc, char ***argv) { GIT_UNUSED(argc); GIT_UNUSED(argv); if (git_libgit2_init() < 0) { fprintf(stderr, "Failed to initialize libgit2\n"); abort(); } return 0; } int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) { git_commit_graph_file file = {{0}}; git_commit_graph_entry e; git_buf commit_graph_buf = GIT_BUF_INIT; git_oid oid = {{0}}; bool append_hash = false; if (size < 4) return 0; /* * If the first byte in the stream has the high bit set, append the * SHA1 hash so that the file is somewhat valid. */ append_hash = *data & 0x80; /* Keep a 4-byte alignment to avoid unaligned accesses. */ data += 4; size -= 4; if (append_hash) { if (git_buf_init(&commit_graph_buf, size + sizeof(oid)) < 0) goto cleanup; if (git_hash_buf(&oid, data, size) < 0) { fprintf(stderr, "Failed to compute the SHA1 hash\n"); abort(); } memcpy(commit_graph_buf.ptr, data, size); memcpy(commit_graph_buf.ptr + size, &oid, sizeof(oid)); } else { git_buf_attach_notowned(&commit_graph_buf, (char *)data, size); } if (git_commit_graph_file_parse( &file, (const unsigned char *)git_buf_cstr(&commit_graph_buf), git_buf_len(&commit_graph_buf)) < 0) goto cleanup; /* Search for any oid, just to exercise that codepath. */ if (git_commit_graph_entry_find(&e, &file, &oid, GIT_OID_HEXSZ) < 0) goto cleanup; cleanup: git_commit_graph_file_close(&file); git_buf_dispose(&commit_graph_buf); 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/fuzzers/midx_fuzzer.c
/* * libgit2 multi-pack-index fuzzer target. * * 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 <stdio.h> #include "git2.h" #include "buffer.h" #include "common.h" #include "futils.h" #include "hash.h" #include "midx.h" int LLVMFuzzerInitialize(int *argc, char ***argv) { GIT_UNUSED(argc); GIT_UNUSED(argv); if (git_libgit2_init() < 0) { fprintf(stderr, "Failed to initialize libgit2\n"); abort(); } return 0; } int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) { git_midx_file idx = {{0}}; git_midx_entry e; git_buf midx_buf = GIT_BUF_INIT; git_oid oid = {{0}}; bool append_hash = false; if (size < 4) return 0; /* * If the first byte in the stream has the high bit set, append the * SHA1 hash so that the packfile is somewhat valid. */ append_hash = *data & 0x80; /* Keep a 4-byte alignment to avoid unaligned accesses. */ data += 4; size -= 4; if (append_hash) { if (git_buf_init(&midx_buf, size + sizeof(oid)) < 0) goto cleanup; if (git_hash_buf(&oid, data, size) < 0) { fprintf(stderr, "Failed to compute the SHA1 hash\n"); abort(); } memcpy(midx_buf.ptr, data, size); memcpy(midx_buf.ptr + size, &oid, sizeof(oid)); } else { git_buf_attach_notowned(&midx_buf, (char *)data, size); } if (git_midx_parse(&idx, (const unsigned char *)git_buf_cstr(&midx_buf), git_buf_len(&midx_buf)) < 0) goto cleanup; /* Search for any oid, just to exercise that codepath. */ if (git_midx_entry_find(&e, &idx, &oid, GIT_OID_HEXSZ) < 0) goto cleanup; cleanup: git_midx_close(&idx); git_buf_dispose(&midx_buf); 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/fuzzers/standalone_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 <stdio.h> #include "git2.h" #include "futils.h" #include "path.h" extern int LLVMFuzzerTestOneInput(const unsigned char *data, size_t size); extern int LLVMFuzzerInitialize(int *argc, char ***argv); static int run_one_file(const char *filename) { git_buf buf = GIT_BUF_INIT; int error = 0; if (git_futils_readbuffer(&buf, filename) < 0) { fprintf(stderr, "Failed to read %s: %s\n", filename, git_error_last()->message); error = -1; goto exit; } LLVMFuzzerTestOneInput((const unsigned char *)buf.ptr, buf.size); exit: git_buf_dispose(&buf); return error; } int main(int argc, char **argv) { git_vector corpus_files = GIT_VECTOR_INIT; char *filename = NULL; unsigned i = 0; int error = 0; if (git_libgit2_init() < 0) { fprintf(stderr, "Failed to initialize libgit2\n"); abort(); } if (argc != 2) { fprintf(stderr, "Usage: %s <corpus directory>\n", argv[0]); error = -1; goto exit; } fprintf(stderr, "Running %s against %s\n", argv[0], argv[1]); LLVMFuzzerInitialize(&argc, &argv); if (git_path_dirload(&corpus_files, argv[1], 0, 0x0) < 0) { fprintf(stderr, "Failed to scan corpus directory '%s': %s\n", argv[1], git_error_last()->message); error = -1; goto exit; } git_vector_foreach(&corpus_files, i, filename) { fprintf(stderr, "\tRunning %s...\n", filename); if (run_one_file(filename) < 0) { error = -1; goto exit; } } fprintf(stderr, "Done %d runs\n", i); exit: git_vector_free_deep(&corpus_files); git_libgit2_shutdown(); 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/fuzzers/download_refs_fuzzer.c
/* * libgit2 raw packfile fuzz target. * * 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 <stdio.h> #include <stdlib.h> #include <string.h> #include "git2.h" #include "git2/sys/transport.h" #include "futils.h" #define UNUSED(x) (void)(x) struct fuzzer_buffer { const unsigned char *data; size_t size; }; struct fuzzer_stream { git_smart_subtransport_stream base; const unsigned char *readp; const unsigned char *endp; }; struct fuzzer_subtransport { git_smart_subtransport base; git_transport *owner; struct fuzzer_buffer data; }; static git_repository *repo; static int fuzzer_stream_read(git_smart_subtransport_stream *stream, char *buffer, size_t buf_size, size_t *bytes_read) { struct fuzzer_stream *fs = (struct fuzzer_stream *) stream; size_t avail = fs->endp - fs->readp; *bytes_read = (buf_size > avail) ? avail : buf_size; memcpy(buffer, fs->readp, *bytes_read); fs->readp += *bytes_read; return 0; } static int fuzzer_stream_write(git_smart_subtransport_stream *stream, const char *buffer, size_t len) { UNUSED(stream); UNUSED(buffer); UNUSED(len); return 0; } static void fuzzer_stream_free(git_smart_subtransport_stream *stream) { free(stream); } static int fuzzer_stream_new( struct fuzzer_stream **out, const struct fuzzer_buffer *data) { struct fuzzer_stream *stream = malloc(sizeof(*stream)); if (!stream) return -1; stream->readp = data->data; stream->endp = data->data + data->size; stream->base.read = fuzzer_stream_read; stream->base.write = fuzzer_stream_write; stream->base.free = fuzzer_stream_free; *out = stream; return 0; } static int fuzzer_subtransport_action( git_smart_subtransport_stream **out, git_smart_subtransport *transport, const char *url, git_smart_service_t action) { struct fuzzer_subtransport *ft = (struct fuzzer_subtransport *) transport; UNUSED(url); UNUSED(action); return fuzzer_stream_new((struct fuzzer_stream **) out, &ft->data); } static int fuzzer_subtransport_close(git_smart_subtransport *transport) { UNUSED(transport); return 0; } static void fuzzer_subtransport_free(git_smart_subtransport *transport) { free(transport); } static int fuzzer_subtransport_new( struct fuzzer_subtransport **out, git_transport *owner, const struct fuzzer_buffer *data) { struct fuzzer_subtransport *sub = malloc(sizeof(*sub)); if (!sub) return -1; sub->owner = owner; sub->data.data = data->data; sub->data.size = data->size; sub->base.action = fuzzer_subtransport_action; sub->base.close = fuzzer_subtransport_close; sub->base.free = fuzzer_subtransport_free; *out = sub; return 0; } int fuzzer_subtransport_cb( git_smart_subtransport **out, git_transport *owner, void *payload) { struct fuzzer_buffer *buf = (struct fuzzer_buffer *) payload; struct fuzzer_subtransport *sub; if (fuzzer_subtransport_new(&sub, owner, buf) < 0) return -1; *out = &sub->base; return 0; } int fuzzer_transport_cb(git_transport **out, git_remote *owner, void *param) { git_smart_subtransport_definition def = { fuzzer_subtransport_cb, 1, param }; return git_transport_smart(out, owner, &def); } void fuzzer_git_abort(const char *op) { const git_error *err = git_error_last(); fprintf(stderr, "unexpected libgit error: %s: %s\n", op, err ? err->message : "<none>"); abort(); } int LLVMFuzzerInitialize(int *argc, char ***argv) { #if defined(_WIN32) char tmpdir[MAX_PATH], path[MAX_PATH]; if (GetTempPath((DWORD)sizeof(tmpdir), tmpdir) == 0) abort(); if (GetTempFileName(tmpdir, "lg2", 1, path) == 0) abort(); if (git_futils_mkdir(path, 0700, 0) < 0) abort(); #else char path[] = "/tmp/git2.XXXXXX"; if (mkdtemp(path) != path) abort(); #endif if (git_libgit2_init() < 0) abort(); if (git_libgit2_opts(GIT_OPT_SET_PACK_MAX_OBJECTS, 10000000) < 0) abort(); UNUSED(argc); UNUSED(argv); if (git_repository_init(&repo, path, 1) < 0) fuzzer_git_abort("git_repository_init"); return 0; } int LLVMFuzzerTestOneInput(const unsigned char *data, size_t size) { struct fuzzer_buffer buffer = { data, size }; git_remote_callbacks callbacks = GIT_REMOTE_CALLBACKS_INIT; git_remote *remote; if (git_remote_create_anonymous(&remote, repo, "fuzzer://remote-url") < 0) fuzzer_git_abort("git_remote_create"); callbacks.transport = fuzzer_transport_cb; callbacks.payload = &buffer; if (git_remote_connect(remote, GIT_DIRECTION_FETCH, &callbacks, NULL, NULL) < 0) goto out; git_remote_download(remote, NULL, NULL); out: git_remote_free(remote); 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/fuzzers/objects_fuzzer.c
/* * libgit2 packfile fuzzer target. * * Copyright (C) the libgit2 contributors. All rights reserved. * * This file is part of libgit2, distributed under the GNU GPL v2 with * a Linking Exception. For full terms see the included COPYING file. */ #include "git2.h" #include "object.h" #define UNUSED(x) (void)(x) int LLVMFuzzerInitialize(int *argc, char ***argv) { UNUSED(argc); UNUSED(argv); if (git_libgit2_init() < 0) abort(); return 0; } int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) { const git_object_t types[] = { GIT_OBJECT_BLOB, GIT_OBJECT_TREE, GIT_OBJECT_COMMIT, GIT_OBJECT_TAG }; git_object *object = NULL; size_t i; /* * Brute-force parse this as every object type. We want * to stress the parsing logic anyway, so this is fine * to do. */ for (i = 0; i < ARRAY_SIZE(types); i++) { if (git_object__from_raw(&object, (const char *) data, size, types[i]) < 0) continue; git_object_free(object); object = NULL; } 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/fuzzers/CMakeLists.txt
LINK_DIRECTORIES(${LIBGIT2_LIBDIRS}) INCLUDE_DIRECTORIES(${LIBGIT2_INCLUDES}) INCLUDE_DIRECTORIES(SYSTEM ${LIBGIT2_SYSTEM_INCLUDES}) IF(BUILD_FUZZERS AND NOT USE_STANDALONE_FUZZERS) ADD_C_FLAG(-fsanitize=fuzzer) ENDIF () FILE(GLOB SRC_FUZZ RELATIVE ${CMAKE_CURRENT_SOURCE_DIR} *_fuzzer.c) FOREACH(fuzz_target_src ${SRC_FUZZ}) STRING(REPLACE ".c" "" fuzz_target_name ${fuzz_target_src}) STRING(REPLACE "_fuzzer" "" fuzz_name ${fuzz_target_name}) SET(${fuzz_target_name}_SOURCES ${fuzz_target_src} ${LIBGIT2_OBJECTS}) IF(USE_STANDALONE_FUZZERS) LIST(APPEND ${fuzz_target_name}_SOURCES "standalone_driver.c") ENDIF() ADD_EXECUTABLE(${fuzz_target_name} ${${fuzz_target_name}_SOURCES}) SET_TARGET_PROPERTIES(${fuzz_target_name} PROPERTIES C_STANDARD 90) TARGET_LINK_LIBRARIES(${fuzz_target_name} ${LIBGIT2_LIBS}) ADD_TEST(${fuzz_target_name} "${CMAKE_CURRENT_BINARY_DIR}/${fuzz_target_name}" "${CMAKE_CURRENT_SOURCE_DIR}/corpora/${fuzz_name}") ENDFOREACH()
0
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2/fuzzers/config_file_fuzzer.c
/* * libgit2 config file parser fuzz target. * * Copyright (C) the libgit2 contributors. All rights reserved. * * This file is part of libgit2, distributed under the GNU GPL v2 with * a Linking Exception. For full terms see the included COPYING file. */ #include "git2.h" #include "config_backend.h" #define UNUSED(x) (void)(x) int foreach_cb(const git_config_entry *entry, void *payload) { UNUSED(entry); UNUSED(payload); return 0; } int LLVMFuzzerInitialize(int *argc, char ***argv) { UNUSED(argc); UNUSED(argv); if (git_libgit2_init() < 0) abort(); return 0; } int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) { git_config *cfg = NULL; git_config_backend *backend = NULL; int err = 0; if ((err = git_config_new(&cfg)) != 0) { goto out; } if ((err = git_config_backend_from_string(&backend, (const char*)data, size)) != 0) { goto out; } if ((err = git_config_add_backend(cfg, backend, 0, NULL, 0)) != 0) { goto out; } /* Now owned by the config */ backend = NULL; git_config_foreach(cfg, foreach_cb, NULL); out: git_config_backend_free(backend); git_config_free(cfg); 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/fuzzers/packfile_fuzzer.c
/* * libgit2 packfile fuzzer target. * * 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 <stdio.h> #include "git2.h" #include "git2/sys/mempack.h" #include "common.h" #include "buffer.h" static git_odb *odb = NULL; static git_odb_backend *mempack = NULL; /* Arbitrary object to seed the ODB. */ static const unsigned char base_obj[] = { 07, 076 }; static const unsigned int base_obj_len = 2; int LLVMFuzzerInitialize(int *argc, char ***argv) { GIT_UNUSED(argc); GIT_UNUSED(argv); if (git_libgit2_init() < 0) { fprintf(stderr, "Failed to initialize libgit2\n"); abort(); } if (git_libgit2_opts(GIT_OPT_SET_PACK_MAX_OBJECTS, 10000000) < 0) { fprintf(stderr, "Failed to limit maximum pack object count\n"); abort(); } if (git_odb_new(&odb) < 0) { fprintf(stderr, "Failed to create the odb\n"); abort(); } if (git_mempack_new(&mempack) < 0) { fprintf(stderr, "Failed to create the mempack\n"); abort(); } if (git_odb_add_backend(odb, mempack, 999) < 0) { fprintf(stderr, "Failed to add the mempack\n"); abort(); } return 0; } int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) { git_indexer_progress stats = {0, 0}; git_indexer *indexer = NULL; git_buf path = GIT_BUF_INIT; git_oid oid; bool append_hash = false; if (size == 0) return 0; if (!odb || !mempack) { fprintf(stderr, "Global state not initialized\n"); abort(); } git_mempack_reset(mempack); if (git_odb_write(&oid, odb, base_obj, base_obj_len, GIT_OBJECT_BLOB) < 0) { fprintf(stderr, "Failed to add an object to the odb\n"); abort(); } if (git_indexer_new(&indexer, ".", 0, odb, NULL) < 0) { fprintf(stderr, "Failed to create the indexer: %s\n", git_error_last()->message); abort(); } /* * If the first byte in the stream has the high bit set, append the * SHA1 hash so that the packfile is somewhat valid. */ append_hash = *data & 0x80; ++data; --size; if (git_indexer_append(indexer, data, size, &stats) < 0) goto cleanup; if (append_hash) { if (git_odb_hash(&oid, data, size, GIT_OBJECT_BLOB) < 0) { fprintf(stderr, "Failed to compute the SHA1 hash\n"); abort(); } if (git_indexer_append(indexer, &oid, sizeof(oid), &stats) < 0) { goto cleanup; } } if (git_indexer_commit(indexer, &stats) < 0) goto cleanup; if (git_buf_printf(&path, "pack-%s.idx", git_oid_tostr_s(git_indexer_hash(indexer))) < 0) goto cleanup; p_unlink(git_buf_cstr(&path)); git_buf_clear(&path); if (git_buf_printf(&path, "pack-%s.pack", git_oid_tostr_s(git_indexer_hash(indexer))) < 0) goto cleanup; p_unlink(git_buf_cstr(&path)); cleanup: git_mempack_reset(mempack); git_indexer_free(indexer); git_buf_dispose(&path); 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/fuzzers/patch_parse_fuzzer.c
/* * libgit2 patch parser fuzzer target. * * Copyright (C) the libgit2 contributors. All rights reserved. * * This file is part of libgit2, distributed under the GNU GPL v2 with * a Linking Exception. For full terms see the included COPYING file. */ #include "git2.h" #include "patch.h" #include "patch_parse.h" #define UNUSED(x) (void)(x) int LLVMFuzzerInitialize(int *argc, char ***argv) { UNUSED(argc); UNUSED(argv); if (git_libgit2_init() < 0) abort(); return 0; } int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) { if (size) { git_patch *patch = NULL; git_patch_options opts = GIT_PATCH_OPTIONS_INIT; opts.prefix_len = (uint32_t)data[0]; git_patch_from_buffer(&patch, (const char *)data + 1, size - 1, &opts); git_patch_free(patch); } 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/examples/rev-parse.c
/* * libgit2 "rev-parse" example - shows how to parse revspecs * * Written by the libgit2 contributors * * To the extent possible under law, the author(s) have dedicated all copyright * and related and neighboring rights to this software to the public domain * worldwide. This software is distributed without any warranty. * * You should have received a copy of the CC0 Public Domain Dedication along * with this software. If not, see * <http://creativecommons.org/publicdomain/zero/1.0/>. */ #include "common.h" /** Forward declarations for helpers. */ struct parse_state { const char *repodir; const char *spec; int not; }; static void parse_opts(struct parse_state *ps, int argc, char *argv[]); static int parse_revision(git_repository *repo, struct parse_state *ps); int lg2_rev_parse(git_repository *repo, int argc, char *argv[]) { struct parse_state ps = {0}; parse_opts(&ps, argc, argv); check_lg2(parse_revision(repo, &ps), "Parsing", NULL); return 0; } static void usage(const char *message, const char *arg) { if (message && arg) fprintf(stderr, "%s: %s\n", message, arg); else if (message) fprintf(stderr, "%s\n", message); fprintf(stderr, "usage: rev-parse [ --option ] <args>...\n"); exit(1); } static void parse_opts(struct parse_state *ps, int argc, char *argv[]) { struct args_info args = ARGS_INFO_INIT; for (args.pos=1; args.pos < argc; ++args.pos) { const char *a = argv[args.pos]; if (a[0] != '-') { if (ps->spec) usage("Too many specs", a); ps->spec = a; } else if (!strcmp(a, "--not")) ps->not = !ps->not; else if (!match_str_arg(&ps->repodir, &args, "--git-dir")) usage("Cannot handle argument", a); } } static int parse_revision(git_repository *repo, struct parse_state *ps) { git_revspec rs; char str[GIT_OID_HEXSZ + 1]; check_lg2(git_revparse(&rs, repo, ps->spec), "Could not parse", ps->spec); if ((rs.flags & GIT_REVSPEC_SINGLE) != 0) { git_oid_tostr(str, sizeof(str), git_object_id(rs.from)); printf("%s\n", str); git_object_free(rs.from); } else if ((rs.flags & GIT_REVSPEC_RANGE) != 0) { git_oid_tostr(str, sizeof(str), git_object_id(rs.to)); printf("%s\n", str); git_object_free(rs.to); if ((rs.flags & GIT_REVSPEC_MERGE_BASE) != 0) { git_oid base; check_lg2(git_merge_base(&base, repo, git_object_id(rs.from), git_object_id(rs.to)), "Could not find merge base", ps->spec); git_oid_tostr(str, sizeof(str), &base); printf("%s\n", str); } git_oid_tostr(str, sizeof(str), git_object_id(rs.from)); printf("^%s\n", str); git_object_free(rs.from); } else { fatal("Invalid results from git_revparse", ps->spec); } 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/examples/ls-files.c
/* * libgit2 "ls-files" example - shows how to view all files currently in the index * * Written by the libgit2 contributors * * To the extent possible under law, the author(s) have dedicated all copyright * and related and neighboring rights to this software to the public domain * worldwide. This software is distributed without any warranty. * * You should have received a copy of the CC0 Public Domain Dedication along * with this software. If not, see * <http://creativecommons.org/publicdomain/zero/1.0/>. */ #include "common.h" /** * This example demonstrates the libgit2 index APIs to roughly * simulate the output of `git ls-files`. * `git ls-files` has many options and this currently does not show them. * * `git ls-files` base command shows all paths in the index at that time. * This includes staged and committed files, but unstaged files will not display. * * This currently supports the default behavior and the `--error-unmatch` option. */ struct ls_options { int error_unmatch; char *files[1024]; size_t file_count; }; static void usage(const char *message, const char *arg) { if (message && arg) fprintf(stderr, "%s: %s\n", message, arg); else if (message) fprintf(stderr, "%s\n", message); fprintf(stderr, "usage: ls-files [--error-unmatch] [--] [<file>...]\n"); exit(1); } static int parse_options(struct ls_options *opts, int argc, char *argv[]) { int parsing_files = 0; int i; memset(opts, 0, sizeof(struct ls_options)); if (argc < 2) return 0; for (i = 1; i < argc; ++i) { char *a = argv[i]; /* if it doesn't start with a '-' or is after the '--' then it is a file */ if (a[0] != '-' || parsing_files) { parsing_files = 1; /* watch for overflows (just in case) */ if (opts->file_count == 1024) { fprintf(stderr, "ls-files can only support 1024 files at this time.\n"); return -1; } opts->files[opts->file_count++] = a; } else if (!strcmp(a, "--")) { parsing_files = 1; } else if (!strcmp(a, "--error-unmatch")) { opts->error_unmatch = 1; } else { usage("Unsupported argument", a); return -1; } } return 0; } static int print_paths(struct ls_options *opts, git_index *index) { size_t i; const git_index_entry *entry; /* if there are no files explicitly listed by the user print all entries in the index */ if (opts->file_count == 0) { size_t entry_count = git_index_entrycount(index); for (i = 0; i < entry_count; i++) { entry = git_index_get_byindex(index, i); puts(entry->path); } return 0; } /* loop through the files found in the args and print them if they exist */ for (i = 0; i < opts->file_count; ++i) { const char *path = opts->files[i]; if ((entry = git_index_get_bypath(index, path, GIT_INDEX_STAGE_NORMAL)) != NULL) { puts(path); } else if (opts->error_unmatch) { fprintf(stderr, "error: pathspec '%s' did not match any file(s) known to git.\n", path); fprintf(stderr, "Did you forget to 'git add'?\n"); return -1; } } return 0; } int lg2_ls_files(git_repository *repo, int argc, char *argv[]) { git_index *index = NULL; struct ls_options opts; int error; if ((error = parse_options(&opts, argc, argv)) < 0) return error; if ((error = git_repository_index(&index, repo)) < 0) goto cleanup; error = print_paths(&opts, index); cleanup: git_index_free(index); 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/examples/blame.c
/* * libgit2 "blame" example - shows how to use the blame API * * Written by the libgit2 contributors * * To the extent possible under law, the author(s) have dedicated all copyright * and related and neighboring rights to this software to the public domain * worldwide. This software is distributed without any warranty. * * You should have received a copy of the CC0 Public Domain Dedication along * with this software. If not, see * <http://creativecommons.org/publicdomain/zero/1.0/>. */ #include "common.h" /** * This example demonstrates how to invoke the libgit2 blame API to roughly * simulate the output of `git blame` and a few of its command line arguments. */ struct blame_opts { char *path; char *commitspec; int C; int M; int start_line; int end_line; int F; }; static void parse_opts(struct blame_opts *o, int argc, char *argv[]); int lg2_blame(git_repository *repo, int argc, char *argv[]) { int line, break_on_null_hunk; git_object_size_t i, rawsize; char spec[1024] = {0}; struct blame_opts o = {0}; const char *rawdata; git_revspec revspec = {0}; git_blame_options blameopts = GIT_BLAME_OPTIONS_INIT; git_blame *blame = NULL; git_blob *blob; git_object *obj; parse_opts(&o, argc, argv); if (o.M) blameopts.flags |= GIT_BLAME_TRACK_COPIES_SAME_COMMIT_MOVES; if (o.C) blameopts.flags |= GIT_BLAME_TRACK_COPIES_SAME_COMMIT_COPIES; if (o.F) blameopts.flags |= GIT_BLAME_FIRST_PARENT; /** * The commit range comes in "commitish" form. Use the rev-parse API to * nail down the end points. */ if (o.commitspec) { check_lg2(git_revparse(&revspec, repo, o.commitspec), "Couldn't parse commit spec", NULL); if (revspec.flags & GIT_REVSPEC_SINGLE) { git_oid_cpy(&blameopts.newest_commit, git_object_id(revspec.from)); git_object_free(revspec.from); } else { git_oid_cpy(&blameopts.oldest_commit, git_object_id(revspec.from)); git_oid_cpy(&blameopts.newest_commit, git_object_id(revspec.to)); git_object_free(revspec.from); git_object_free(revspec.to); } } /** Run the blame. */ check_lg2(git_blame_file(&blame, repo, o.path, &blameopts), "Blame error", NULL); /** * Get the raw data inside the blob for output. We use the * `commitish:path/to/file.txt` format to find it. */ if (git_oid_is_zero(&blameopts.newest_commit)) strcpy(spec, "HEAD"); else git_oid_tostr(spec, sizeof(spec), &blameopts.newest_commit); strcat(spec, ":"); strcat(spec, o.path); check_lg2(git_revparse_single(&obj, repo, spec), "Object lookup error", NULL); check_lg2(git_blob_lookup(&blob, repo, git_object_id(obj)), "Blob lookup error", NULL); git_object_free(obj); rawdata = git_blob_rawcontent(blob); rawsize = git_blob_rawsize(blob); /** Produce the output. */ line = 1; i = 0; break_on_null_hunk = 0; while (i < rawsize) { const char *eol = memchr(rawdata + i, '\n', (size_t)(rawsize - i)); char oid[10] = {0}; const git_blame_hunk *hunk = git_blame_get_hunk_byline(blame, line); if (break_on_null_hunk && !hunk) break; if (hunk) { char sig[128] = {0}; break_on_null_hunk = 1; git_oid_tostr(oid, 10, &hunk->final_commit_id); snprintf(sig, 30, "%s <%s>", hunk->final_signature->name, hunk->final_signature->email); printf("%s ( %-30s %3d) %.*s\n", oid, sig, line, (int)(eol - rawdata - i), rawdata + i); } i = (int)(eol - rawdata + 1); line++; } /** Cleanup. */ git_blob_free(blob); git_blame_free(blame); return 0; } /** Tell the user how to make this thing work. */ static void usage(const char *msg, const char *arg) { if (msg && arg) fprintf(stderr, "%s: %s\n", msg, arg); else if (msg) fprintf(stderr, "%s\n", msg); fprintf(stderr, "usage: blame [options] [<commit range>] <path>\n"); fprintf(stderr, "\n"); fprintf(stderr, " <commit range> example: `HEAD~10..HEAD`, or `1234abcd`\n"); fprintf(stderr, " -L <n,m> process only line range n-m, counting from 1\n"); fprintf(stderr, " -M find line moves within and across files\n"); fprintf(stderr, " -C find line copies within and across files\n"); fprintf(stderr, " -F follow only the first parent commits\n"); fprintf(stderr, "\n"); exit(1); } /** Parse the arguments. */ static void parse_opts(struct blame_opts *o, int argc, char *argv[]) { int i; char *bare_args[3] = {0}; if (argc < 2) usage(NULL, NULL); for (i=1; i<argc; i++) { char *a = argv[i]; if (a[0] != '-') { int i=0; while (bare_args[i] && i < 3) ++i; if (i >= 3) usage("Invalid argument set", NULL); bare_args[i] = a; } else if (!strcmp(a, "--")) continue; else if (!strcasecmp(a, "-M")) o->M = 1; else if (!strcasecmp(a, "-C")) o->C = 1; else if (!strcasecmp(a, "-F")) o->F = 1; else if (!strcasecmp(a, "-L")) { i++; a = argv[i]; if (i >= argc) fatal("Not enough arguments to -L", NULL); check_lg2(sscanf(a, "%d,%d", &o->start_line, &o->end_line)-2, "-L format error", NULL); } else { /* commit range */ if (o->commitspec) fatal("Only one commit spec allowed", NULL); o->commitspec = a; } } /* Handle the bare arguments */ if (!bare_args[0]) usage("Please specify a path", NULL); o->path = bare_args[0]; if (bare_args[1]) { /* <commitspec> <path> */ o->path = bare_args[1]; o->commitspec = bare_args[0]; } if (bare_args[2]) { /* <oldcommit> <newcommit> <path> */ char spec[128] = {0}; o->path = bare_args[2]; sprintf(spec, "%s..%s", bare_args[0], bare_args[1]); o->commitspec = spec; } }
0
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2/examples/merge.c
/* * libgit2 "merge" example - shows how to perform merges * * Written by the libgit2 contributors * * To the extent possible under law, the author(s) have dedicated all copyright * and related and neighboring rights to this software to the public domain * worldwide. This software is distributed without any warranty. * * You should have received a copy of the CC0 Public Domain Dedication along * with this software. If not, see * <http://creativecommons.org/publicdomain/zero/1.0/>. */ #include "common.h" /** The following example demonstrates how to do merges with libgit2. * * It will merge whatever commit-ish you pass in into the current branch. * * Recognized options are : * --no-commit: don't actually commit the merge. * */ struct merge_options { const char **heads; size_t heads_count; git_annotated_commit **annotated; size_t annotated_count; int no_commit : 1; }; static void print_usage(void) { fprintf(stderr, "usage: merge [--no-commit] <commit...>\n"); exit(1); } static void merge_options_init(struct merge_options *opts) { memset(opts, 0, sizeof(*opts)); opts->heads = NULL; opts->heads_count = 0; opts->annotated = NULL; opts->annotated_count = 0; } static void opts_add_refish(struct merge_options *opts, const char *refish) { size_t sz; assert(opts != NULL); sz = ++opts->heads_count * sizeof(opts->heads[0]); opts->heads = xrealloc((void *) opts->heads, sz); opts->heads[opts->heads_count - 1] = refish; } static void parse_options(const char **repo_path, struct merge_options *opts, int argc, char **argv) { struct args_info args = ARGS_INFO_INIT; if (argc <= 1) print_usage(); for (args.pos = 1; args.pos < argc; ++args.pos) { const char *curr = argv[args.pos]; if (curr[0] != '-') { opts_add_refish(opts, curr); } else if (!strcmp(curr, "--no-commit")) { opts->no_commit = 1; } else if (match_str_arg(repo_path, &args, "--git-dir")) { continue; } else { print_usage(); } } } static int resolve_heads(git_repository *repo, struct merge_options *opts) { git_annotated_commit **annotated = calloc(opts->heads_count, sizeof(git_annotated_commit *)); size_t annotated_count = 0, i; int err = 0; for (i = 0; i < opts->heads_count; i++) { err = resolve_refish(&annotated[annotated_count++], repo, opts->heads[i]); if (err != 0) { fprintf(stderr, "failed to resolve refish %s: %s\n", opts->heads[i], git_error_last()->message); annotated_count--; continue; } } if (annotated_count != opts->heads_count) { fprintf(stderr, "unable to parse some refish\n"); free(annotated); return -1; } opts->annotated = annotated; opts->annotated_count = annotated_count; return 0; } static int perform_fastforward(git_repository *repo, const git_oid *target_oid, int is_unborn) { git_checkout_options ff_checkout_options = GIT_CHECKOUT_OPTIONS_INIT; git_reference *target_ref; git_reference *new_target_ref; git_object *target = NULL; int err = 0; if (is_unborn) { const char *symbolic_ref; git_reference *head_ref; /* HEAD reference is unborn, lookup manually so we don't try to resolve it */ err = git_reference_lookup(&head_ref, repo, "HEAD"); if (err != 0) { fprintf(stderr, "failed to lookup HEAD ref\n"); return -1; } /* Grab the reference HEAD should be pointing to */ symbolic_ref = git_reference_symbolic_target(head_ref); /* Create our master reference on the target OID */ err = git_reference_create(&target_ref, repo, symbolic_ref, target_oid, 0, NULL); if (err != 0) { fprintf(stderr, "failed to create master reference\n"); return -1; } git_reference_free(head_ref); } else { /* HEAD exists, just lookup and resolve */ err = git_repository_head(&target_ref, repo); if (err != 0) { fprintf(stderr, "failed to get HEAD reference\n"); return -1; } } /* Lookup the target object */ err = git_object_lookup(&target, repo, target_oid, GIT_OBJECT_COMMIT); if (err != 0) { fprintf(stderr, "failed to lookup OID %s\n", git_oid_tostr_s(target_oid)); return -1; } /* Checkout the result so the workdir is in the expected state */ ff_checkout_options.checkout_strategy = GIT_CHECKOUT_SAFE; err = git_checkout_tree(repo, target, &ff_checkout_options); if (err != 0) { fprintf(stderr, "failed to checkout HEAD reference\n"); return -1; } /* Move the target reference to the target OID */ err = git_reference_set_target(&new_target_ref, target_ref, target_oid, NULL); if (err != 0) { fprintf(stderr, "failed to move HEAD reference\n"); return -1; } git_reference_free(target_ref); git_reference_free(new_target_ref); git_object_free(target); return 0; } static void output_conflicts(git_index *index) { git_index_conflict_iterator *conflicts; const git_index_entry *ancestor; const git_index_entry *our; const git_index_entry *their; int err = 0; check_lg2(git_index_conflict_iterator_new(&conflicts, index), "failed to create conflict iterator", NULL); while ((err = git_index_conflict_next(&ancestor, &our, &their, conflicts)) == 0) { fprintf(stderr, "conflict: a:%s o:%s t:%s\n", ancestor ? ancestor->path : "NULL", our->path ? our->path : "NULL", their->path ? their->path : "NULL"); } if (err != GIT_ITEROVER) { fprintf(stderr, "error iterating conflicts\n"); } git_index_conflict_iterator_free(conflicts); } static int create_merge_commit(git_repository *repo, git_index *index, struct merge_options *opts) { git_oid tree_oid, commit_oid; git_tree *tree; git_signature *sign; git_reference *merge_ref = NULL; git_annotated_commit *merge_commit; git_reference *head_ref; git_commit **parents = calloc(opts->annotated_count + 1, sizeof(git_commit *)); const char *msg_target = NULL; size_t msglen = 0; char *msg; size_t i; int err; /* Grab our needed references */ check_lg2(git_repository_head(&head_ref, repo), "failed to get repo HEAD", NULL); if (resolve_refish(&merge_commit, repo, opts->heads[0])) { fprintf(stderr, "failed to resolve refish %s", opts->heads[0]); free(parents); return -1; } /* Maybe that's a ref, so DWIM it */ err = git_reference_dwim(&merge_ref, repo, opts->heads[0]); check_lg2(err, "failed to DWIM reference", git_error_last()->message); /* Grab a signature */ check_lg2(git_signature_now(&sign, "Me", "[email protected]"), "failed to create signature", NULL); #define MERGE_COMMIT_MSG "Merge %s '%s'" /* Prepare a standard merge commit message */ if (merge_ref != NULL) { check_lg2(git_branch_name(&msg_target, merge_ref), "failed to get branch name of merged ref", NULL); } else { msg_target = git_oid_tostr_s(git_annotated_commit_id(merge_commit)); } msglen = snprintf(NULL, 0, MERGE_COMMIT_MSG, (merge_ref ? "branch" : "commit"), msg_target); if (msglen > 0) msglen++; msg = malloc(msglen); err = snprintf(msg, msglen, MERGE_COMMIT_MSG, (merge_ref ? "branch" : "commit"), msg_target); /* This is only to silence the compiler */ if (err < 0) goto cleanup; /* Setup our parent commits */ err = git_reference_peel((git_object **)&parents[0], head_ref, GIT_OBJECT_COMMIT); check_lg2(err, "failed to peel head reference", NULL); for (i = 0; i < opts->annotated_count; i++) { git_commit_lookup(&parents[i + 1], repo, git_annotated_commit_id(opts->annotated[i])); } /* Prepare our commit tree */ check_lg2(git_index_write_tree(&tree_oid, index), "failed to write merged tree", NULL); check_lg2(git_tree_lookup(&tree, repo, &tree_oid), "failed to lookup tree", NULL); /* Commit time ! */ err = git_commit_create(&commit_oid, repo, git_reference_name(head_ref), sign, sign, NULL, msg, tree, opts->annotated_count + 1, (const git_commit **)parents); check_lg2(err, "failed to create commit", NULL); /* We're done merging, cleanup the repository state */ git_repository_state_cleanup(repo); cleanup: free(parents); return err; } int lg2_merge(git_repository *repo, int argc, char **argv) { struct merge_options opts; git_index *index; git_repository_state_t state; git_merge_analysis_t analysis; git_merge_preference_t preference; const char *path = "."; int err = 0; merge_options_init(&opts); parse_options(&path, &opts, argc, argv); state = git_repository_state(repo); if (state != GIT_REPOSITORY_STATE_NONE) { fprintf(stderr, "repository is in unexpected state %d\n", state); goto cleanup; } err = resolve_heads(repo, &opts); if (err != 0) goto cleanup; err = git_merge_analysis(&analysis, &preference, repo, (const git_annotated_commit **)opts.annotated, opts.annotated_count); check_lg2(err, "merge analysis failed", NULL); if (analysis & GIT_MERGE_ANALYSIS_UP_TO_DATE) { printf("Already up-to-date\n"); return 0; } else if (analysis & GIT_MERGE_ANALYSIS_UNBORN || (analysis & GIT_MERGE_ANALYSIS_FASTFORWARD && !(preference & GIT_MERGE_PREFERENCE_NO_FASTFORWARD))) { const git_oid *target_oid; if (analysis & GIT_MERGE_ANALYSIS_UNBORN) { printf("Unborn\n"); } else { printf("Fast-forward\n"); } /* Since this is a fast-forward, there can be only one merge head */ target_oid = git_annotated_commit_id(opts.annotated[0]); assert(opts.annotated_count == 1); return perform_fastforward(repo, target_oid, (analysis & GIT_MERGE_ANALYSIS_UNBORN)); } else if (analysis & GIT_MERGE_ANALYSIS_NORMAL) { git_merge_options merge_opts = GIT_MERGE_OPTIONS_INIT; git_checkout_options checkout_opts = GIT_CHECKOUT_OPTIONS_INIT; merge_opts.flags = 0; merge_opts.file_flags = GIT_MERGE_FILE_STYLE_DIFF3; checkout_opts.checkout_strategy = GIT_CHECKOUT_FORCE|GIT_CHECKOUT_ALLOW_CONFLICTS; if (preference & GIT_MERGE_PREFERENCE_FASTFORWARD_ONLY) { printf("Fast-forward is preferred, but only a merge is possible\n"); return -1; } err = git_merge(repo, (const git_annotated_commit **)opts.annotated, opts.annotated_count, &merge_opts, &checkout_opts); check_lg2(err, "merge failed", NULL); } /* If we get here, we actually performed the merge above */ check_lg2(git_repository_index(&index, repo), "failed to get repository index", NULL); if (git_index_has_conflicts(index)) { /* Handle conflicts */ output_conflicts(index); } else if (!opts.no_commit) { create_merge_commit(repo, index, &opts); printf("Merge made\n"); } cleanup: free((char **)opts.heads); free(opts.annotated); 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/examples/rev-list.c
/* * libgit2 "rev-list" example - shows how to transform a rev-spec into a list * of commit ids * * Written by the libgit2 contributors * * To the extent possible under law, the author(s) have dedicated all copyright * and related and neighboring rights to this software to the public domain * worldwide. This software is distributed without any warranty. * * You should have received a copy of the CC0 Public Domain Dedication along * with this software. If not, see * <http://creativecommons.org/publicdomain/zero/1.0/>. */ #include "common.h" #include <assert.h> static int revwalk_parse_options(git_sort_t *sort, struct args_info *args); static int revwalk_parse_revs(git_repository *repo, git_revwalk *walk, struct args_info *args); int lg2_rev_list(git_repository *repo, int argc, char **argv) { struct args_info args = ARGS_INFO_INIT; git_revwalk *walk; git_oid oid; git_sort_t sort; char buf[GIT_OID_HEXSZ+1]; check_lg2(revwalk_parse_options(&sort, &args), "parsing options", NULL); check_lg2(git_revwalk_new(&walk, repo), "allocating revwalk", NULL); git_revwalk_sorting(walk, sort); check_lg2(revwalk_parse_revs(repo, walk, &args), "parsing revs", NULL); while (!git_revwalk_next(&oid, walk)) { git_oid_fmt(buf, &oid); buf[GIT_OID_HEXSZ] = '\0'; printf("%s\n", buf); } git_revwalk_free(walk); return 0; } static int push_commit(git_revwalk *walk, const git_oid *oid, int hide) { if (hide) return git_revwalk_hide(walk, oid); else return git_revwalk_push(walk, oid); } static int push_spec(git_repository *repo, git_revwalk *walk, const char *spec, int hide) { int error; git_object *obj; if ((error = git_revparse_single(&obj, repo, spec)) < 0) return error; error = push_commit(walk, git_object_id(obj), hide); git_object_free(obj); return error; } static int push_range(git_repository *repo, git_revwalk *walk, const char *range, int hide) { git_revspec revspec; int error = 0; if ((error = git_revparse(&revspec, repo, range))) return error; if (revspec.flags & GIT_REVSPEC_MERGE_BASE) { /* TODO: support "<commit>...<commit>" */ return GIT_EINVALIDSPEC; } if ((error = push_commit(walk, git_object_id(revspec.from), !hide))) goto out; error = push_commit(walk, git_object_id(revspec.to), hide); out: git_object_free(revspec.from); git_object_free(revspec.to); return error; } static void print_usage(void) { fprintf(stderr, "rev-list [--git-dir=dir] [--topo-order|--date-order] [--reverse] <revspec>\n"); exit(-1); } static int revwalk_parse_options(git_sort_t *sort, struct args_info *args) { assert(sort && args); *sort = GIT_SORT_NONE; if (args->argc < 1) print_usage(); for (args->pos = 1; args->pos < args->argc; ++args->pos) { const char *curr = args->argv[args->pos]; if (!strcmp(curr, "--topo-order")) { *sort |= GIT_SORT_TOPOLOGICAL; } else if (!strcmp(curr, "--date-order")) { *sort |= GIT_SORT_TIME; } else if (!strcmp(curr, "--reverse")) { *sort |= (*sort & ~GIT_SORT_REVERSE) ^ GIT_SORT_REVERSE; } else { break; } } return 0; } static int revwalk_parse_revs(git_repository *repo, git_revwalk *walk, struct args_info *args) { int hide, error; git_oid oid; hide = 0; for (; args->pos < args->argc; ++args->pos) { const char *curr = args->argv[args->pos]; if (!strcmp(curr, "--not")) { hide = !hide; } else if (curr[0] == '^') { if ((error = push_spec(repo, walk, curr + 1, !hide))) return error; } else if (strstr(curr, "..")) { if ((error = push_range(repo, walk, curr, hide))) return error; } else { if (push_spec(repo, walk, curr, hide) == 0) continue; if ((error = git_oid_fromstr(&oid, curr))) return error; if ((error = push_commit(walk, &oid, hide))) return error; } } return 0; }
0
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2/examples/clone.c
#include "common.h" typedef struct progress_data { git_indexer_progress fetch_progress; size_t completed_steps; size_t total_steps; const char *path; } progress_data; static void print_progress(const progress_data *pd) { int network_percent = pd->fetch_progress.total_objects > 0 ? (100*pd->fetch_progress.received_objects) / pd->fetch_progress.total_objects : 0; int index_percent = pd->fetch_progress.total_objects > 0 ? (100*pd->fetch_progress.indexed_objects) / pd->fetch_progress.total_objects : 0; int checkout_percent = pd->total_steps > 0 ? (int)((100 * pd->completed_steps) / pd->total_steps) : 0; size_t kbytes = pd->fetch_progress.received_bytes / 1024; if (pd->fetch_progress.total_objects && pd->fetch_progress.received_objects == pd->fetch_progress.total_objects) { printf("Resolving deltas %u/%u\r", pd->fetch_progress.indexed_deltas, pd->fetch_progress.total_deltas); } else { printf("net %3d%% (%4" PRIuZ " kb, %5u/%5u) / idx %3d%% (%5u/%5u) / chk %3d%% (%4" PRIuZ "/%4" PRIuZ")%s\n", network_percent, kbytes, pd->fetch_progress.received_objects, pd->fetch_progress.total_objects, index_percent, pd->fetch_progress.indexed_objects, pd->fetch_progress.total_objects, checkout_percent, pd->completed_steps, pd->total_steps, pd->path); } } static int sideband_progress(const char *str, int len, void *payload) { (void)payload; /* unused */ printf("remote: %.*s", len, str); fflush(stdout); return 0; } static int fetch_progress(const git_indexer_progress *stats, void *payload) { progress_data *pd = (progress_data*)payload; pd->fetch_progress = *stats; print_progress(pd); return 0; } static void checkout_progress(const char *path, size_t cur, size_t tot, void *payload) { progress_data *pd = (progress_data*)payload; pd->completed_steps = cur; pd->total_steps = tot; pd->path = path; print_progress(pd); } int lg2_clone(git_repository *repo, int argc, char **argv) { progress_data pd = {{0}}; git_repository *cloned_repo = NULL; git_clone_options clone_opts = GIT_CLONE_OPTIONS_INIT; git_checkout_options checkout_opts = GIT_CHECKOUT_OPTIONS_INIT; const char *url = argv[1]; const char *path = argv[2]; int error; (void)repo; /* unused */ /* Validate args */ if (argc < 3) { printf ("USAGE: %s <url> <path>\n", argv[0]); return -1; } /* Set up options */ checkout_opts.checkout_strategy = GIT_CHECKOUT_SAFE; checkout_opts.progress_cb = checkout_progress; checkout_opts.progress_payload = &pd; clone_opts.checkout_opts = checkout_opts; clone_opts.fetch_opts.callbacks.sideband_progress = sideband_progress; clone_opts.fetch_opts.callbacks.transfer_progress = &fetch_progress; clone_opts.fetch_opts.callbacks.credentials = cred_acquire_cb; clone_opts.fetch_opts.callbacks.payload = &pd; /* Do the clone */ error = git_clone(&cloned_repo, url, path, &clone_opts); printf("\n"); if (error != 0) { const git_error *err = git_error_last(); if (err) printf("ERROR %d: %s\n", err->klass, err->message); else printf("ERROR %d: no detailed info\n", error); } else if (cloned_repo) git_repository_free(cloned_repo); 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/examples/remote.c
/* * libgit2 "remote" example - shows how to modify remotes for a repo * * Written by the libgit2 contributors * * To the extent possible under law, the author(s) have dedicated all copyright * and related and neighboring rights to this software to the public domain * worldwide. This software is distributed without any warranty. * * You should have received a copy of the CC0 Public Domain Dedication along * with this software. If not, see * <http://creativecommons.org/publicdomain/zero/1.0/>. */ #include "common.h" /** * This is a sample program that is similar to "git remote". See the * documentation for that (try "git help remote") to understand what this * program is emulating. * * This demonstrates using the libgit2 APIs to modify remotes of a repository. */ enum subcmd { subcmd_add, subcmd_remove, subcmd_rename, subcmd_seturl, subcmd_show, }; struct remote_opts { enum subcmd cmd; /* for command-specific args */ int argc; char **argv; }; static int cmd_add(git_repository *repo, struct remote_opts *o); static int cmd_remove(git_repository *repo, struct remote_opts *o); static int cmd_rename(git_repository *repo, struct remote_opts *o); static int cmd_seturl(git_repository *repo, struct remote_opts *o); static int cmd_show(git_repository *repo, struct remote_opts *o); static void parse_subcmd( struct remote_opts *opt, int argc, char **argv); static void usage(const char *msg, const char *arg); int lg2_remote(git_repository *repo, int argc, char *argv[]) { int retval = 0; struct remote_opts opt = {0}; parse_subcmd(&opt, argc, argv); switch (opt.cmd) { case subcmd_add: retval = cmd_add(repo, &opt); break; case subcmd_remove: retval = cmd_remove(repo, &opt); break; case subcmd_rename: retval = cmd_rename(repo, &opt); break; case subcmd_seturl: retval = cmd_seturl(repo, &opt); break; case subcmd_show: retval = cmd_show(repo, &opt); break; } return retval; } static int cmd_add(git_repository *repo, struct remote_opts *o) { char *name, *url; git_remote *remote = {0}; if (o->argc != 2) usage("you need to specify a name and URL", NULL); name = o->argv[0]; url = o->argv[1]; check_lg2(git_remote_create(&remote, repo, name, url), "could not create remote", NULL); return 0; } static int cmd_remove(git_repository *repo, struct remote_opts *o) { char *name; if (o->argc != 1) usage("you need to specify a name", NULL); name = o->argv[0]; check_lg2(git_remote_delete(repo, name), "could not delete remote", name); return 0; } static int cmd_rename(git_repository *repo, struct remote_opts *o) { int i, retval; char *old, *new; git_strarray problems = {0}; if (o->argc != 2) usage("you need to specify old and new remote name", NULL); old = o->argv[0]; new = o->argv[1]; retval = git_remote_rename(&problems, repo, old, new); if (!retval) return 0; for (i = 0; i < (int) problems.count; i++) { puts(problems.strings[0]); } git_strarray_dispose(&problems); return retval; } static int cmd_seturl(git_repository *repo, struct remote_opts *o) { int i, retval, push = 0; char *name = NULL, *url = NULL; for (i = 0; i < o->argc; i++) { char *arg = o->argv[i]; if (!strcmp(arg, "--push")) { push = 1; } else if (arg[0] != '-' && name == NULL) { name = arg; } else if (arg[0] != '-' && url == NULL) { url = arg; } else { usage("invalid argument to set-url", arg); } } if (name == NULL || url == NULL) usage("you need to specify remote and the new URL", NULL); if (push) retval = git_remote_set_pushurl(repo, name, url); else retval = git_remote_set_url(repo, name, url); check_lg2(retval, "could not set URL", url); return 0; } static int cmd_show(git_repository *repo, struct remote_opts *o) { int i; const char *arg, *name, *fetch, *push; int verbose = 0; git_strarray remotes = {0}; git_remote *remote = {0}; for (i = 0; i < o->argc; i++) { arg = o->argv[i]; if (!strcmp(arg, "-v") || !strcmp(arg, "--verbose")) { verbose = 1; } } check_lg2(git_remote_list(&remotes, repo), "could not retrieve remotes", NULL); for (i = 0; i < (int) remotes.count; i++) { name = remotes.strings[i]; if (!verbose) { puts(name); continue; } check_lg2(git_remote_lookup(&remote, repo, name), "could not look up remote", name); fetch = git_remote_url(remote); if (fetch) printf("%s\t%s (fetch)\n", name, fetch); push = git_remote_pushurl(remote); /* use fetch URL if no distinct push URL has been set */ push = push ? push : fetch; if (push) printf("%s\t%s (push)\n", name, push); git_remote_free(remote); } git_strarray_dispose(&remotes); return 0; } static void parse_subcmd( struct remote_opts *opt, int argc, char **argv) { char *arg = argv[1]; enum subcmd cmd = 0; if (argc < 2) usage("no command specified", NULL); if (!strcmp(arg, "add")) { cmd = subcmd_add; } else if (!strcmp(arg, "remove")) { cmd = subcmd_remove; } else if (!strcmp(arg, "rename")) { cmd = subcmd_rename; } else if (!strcmp(arg, "set-url")) { cmd = subcmd_seturl; } else if (!strcmp(arg, "show")) { cmd = subcmd_show; } else { usage("command is not valid", arg); } opt->cmd = cmd; opt->argc = argc - 2; /* executable and subcommand are removed */ opt->argv = argv + 2; } static void usage(const char *msg, const char *arg) { fputs("usage: remote add <name> <url>\n", stderr); fputs(" remote remove <name>\n", stderr); fputs(" remote rename <old> <new>\n", stderr); fputs(" remote set-url [--push] <name> <newurl>\n", stderr); fputs(" remote show [-v|--verbose]\n", stderr); if (msg && !arg) fprintf(stderr, "\n%s\n", msg); else if (msg && arg) fprintf(stderr, "\n%s: %s\n", msg, arg); exit(1); }
0
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2/examples/tag.c
/* * libgit2 "tag" example - shows how to list, create and delete tags * * Written by the libgit2 contributors * * To the extent possible under law, the author(s) have dedicated all copyright * and related and neighboring rights to this software to the public domain * worldwide. This software is distributed without any warranty. * * You should have received a copy of the CC0 Public Domain Dedication along * with this software. If not, see * <http://creativecommons.org/publicdomain/zero/1.0/>. */ #include "common.h" /** * The following example partially reimplements the `git tag` command * and some of its options. * * These commands should work: * - Tag name listing (`tag`) * - Filtered tag listing with messages (`tag -n3 -l "v0.1*"`) * - Lightweight tag creation (`tag test v0.18.0`) * - Tag creation (`tag -a -m "Test message" test v0.18.0`) * - Tag deletion (`tag -d test`) * * The command line parsing logic is simplified and doesn't handle * all of the use cases. */ /** tag_options represents the parsed command line options */ struct tag_options { const char *message; const char *pattern; const char *tag_name; const char *target; int num_lines; int force; }; /** tag_state represents the current program state for dragging around */ typedef struct { git_repository *repo; struct tag_options *opts; } tag_state; /** An action to execute based on the command line arguments */ typedef void (*tag_action)(tag_state *state); typedef struct args_info args_info; static void check(int result, const char *message) { if (result) fatal(message, NULL); } /** Tag listing: Print individual message lines */ static void print_list_lines(const char *message, const tag_state *state) { const char *msg = message; int num = state->opts->num_lines - 1; if (!msg) return; /** first line - headline */ while(*msg && *msg != '\n') printf("%c", *msg++); /** skip over new lines */ while(*msg && *msg == '\n') msg++; printf("\n"); /** print just headline? */ if (num == 0) return; if (*msg && msg[1]) printf("\n"); /** print individual commit/tag lines */ while (*msg && num-- >= 2) { printf(" "); while (*msg && *msg != '\n') printf("%c", *msg++); /** handle consecutive new lines */ if (*msg && *msg == '\n' && msg[1] == '\n') { num--; printf("\n"); } while(*msg && *msg == '\n') msg++; printf("\n"); } } /** Tag listing: Print an actual tag object */ static void print_tag(git_tag *tag, const tag_state *state) { printf("%-16s", git_tag_name(tag)); if (state->opts->num_lines) { const char *msg = git_tag_message(tag); print_list_lines(msg, state); } else { printf("\n"); } } /** Tag listing: Print a commit (target of a lightweight tag) */ static void print_commit(git_commit *commit, const char *name, const tag_state *state) { printf("%-16s", name); if (state->opts->num_lines) { const char *msg = git_commit_message(commit); print_list_lines(msg, state); } else { printf("\n"); } } /** Tag listing: Fallback, should not happen */ static void print_name(const char *name) { printf("%s\n", name); } /** Tag listing: Lookup tags based on ref name and dispatch to print */ static int each_tag(const char *name, tag_state *state) { git_repository *repo = state->repo; git_object *obj; check_lg2(git_revparse_single(&obj, repo, name), "Failed to lookup rev", name); switch (git_object_type(obj)) { case GIT_OBJECT_TAG: print_tag((git_tag *) obj, state); break; case GIT_OBJECT_COMMIT: print_commit((git_commit *) obj, name, state); break; default: print_name(name); } git_object_free(obj); return 0; } static void action_list_tags(tag_state *state) { const char *pattern = state->opts->pattern; git_strarray tag_names = {0}; size_t i; check_lg2(git_tag_list_match(&tag_names, pattern ? pattern : "*", state->repo), "Unable to get list of tags", NULL); for(i = 0; i < tag_names.count; i++) { each_tag(tag_names.strings[i], state); } git_strarray_dispose(&tag_names); } static void action_delete_tag(tag_state *state) { struct tag_options *opts = state->opts; git_object *obj; git_buf abbrev_oid = {0}; check(!opts->tag_name, "Name required"); check_lg2(git_revparse_single(&obj, state->repo, opts->tag_name), "Failed to lookup rev", opts->tag_name); check_lg2(git_object_short_id(&abbrev_oid, obj), "Unable to get abbreviated OID", opts->tag_name); check_lg2(git_tag_delete(state->repo, opts->tag_name), "Unable to delete tag", opts->tag_name); printf("Deleted tag '%s' (was %s)\n", opts->tag_name, abbrev_oid.ptr); git_buf_dispose(&abbrev_oid); git_object_free(obj); } static void action_create_lightweight_tag(tag_state *state) { git_repository *repo = state->repo; struct tag_options *opts = state->opts; git_oid oid; git_object *target; check(!opts->tag_name, "Name required"); if (!opts->target) opts->target = "HEAD"; check(!opts->target, "Target required"); check_lg2(git_revparse_single(&target, repo, opts->target), "Unable to resolve spec", opts->target); check_lg2(git_tag_create_lightweight(&oid, repo, opts->tag_name, target, opts->force), "Unable to create tag", NULL); git_object_free(target); } static void action_create_tag(tag_state *state) { git_repository *repo = state->repo; struct tag_options *opts = state->opts; git_signature *tagger; git_oid oid; git_object *target; check(!opts->tag_name, "Name required"); check(!opts->message, "Message required"); if (!opts->target) opts->target = "HEAD"; check_lg2(git_revparse_single(&target, repo, opts->target), "Unable to resolve spec", opts->target); check_lg2(git_signature_default(&tagger, repo), "Unable to create signature", NULL); check_lg2(git_tag_create(&oid, repo, opts->tag_name, target, tagger, opts->message, opts->force), "Unable to create tag", NULL); git_object_free(target); git_signature_free(tagger); } static void print_usage(void) { fprintf(stderr, "usage: see `git help tag`\n"); exit(1); } /** Parse command line arguments and choose action to run when done */ static void parse_options(tag_action *action, struct tag_options *opts, int argc, char **argv) { args_info args = ARGS_INFO_INIT; *action = &action_list_tags; for (args.pos = 1; args.pos < argc; ++args.pos) { const char *curr = argv[args.pos]; if (curr[0] != '-') { if (!opts->tag_name) opts->tag_name = curr; else if (!opts->target) opts->target = curr; else print_usage(); if (*action != &action_create_tag) *action = &action_create_lightweight_tag; } else if (!strcmp(curr, "-n")) { opts->num_lines = 1; *action = &action_list_tags; } else if (!strcmp(curr, "-a")) { *action = &action_create_tag; } else if (!strcmp(curr, "-f")) { opts->force = 1; } else if (match_int_arg(&opts->num_lines, &args, "-n", 0)) { *action = &action_list_tags; } else if (match_str_arg(&opts->pattern, &args, "-l")) { *action = &action_list_tags; } else if (match_str_arg(&opts->tag_name, &args, "-d")) { *action = &action_delete_tag; } else if (match_str_arg(&opts->message, &args, "-m")) { *action = &action_create_tag; } } } /** Initialize tag_options struct */ static void tag_options_init(struct tag_options *opts) { memset(opts, 0, sizeof(*opts)); opts->message = NULL; opts->pattern = NULL; opts->tag_name = NULL; opts->target = NULL; opts->num_lines = 0; opts->force = 0; } int lg2_tag(git_repository *repo, int argc, char **argv) { struct tag_options opts; tag_action action; tag_state state; tag_options_init(&opts); parse_options(&action, &opts, argc, argv); state.repo = repo; state.opts = &opts; action(&state); 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/examples/log.c
/* * libgit2 "log" example - shows how to walk history and get commit info * * Written by the libgit2 contributors * * To the extent possible under law, the author(s) have dedicated all copyright * and related and neighboring rights to this software to the public domain * worldwide. This software is distributed without any warranty. * * You should have received a copy of the CC0 Public Domain Dedication along * with this software. If not, see * <http://creativecommons.org/publicdomain/zero/1.0/>. */ #include "common.h" /** * This example demonstrates the libgit2 rev walker APIs to roughly * simulate the output of `git log` and a few of command line arguments. * `git log` has many many options and this only shows a few of them. * * This does not have: * * - Robust error handling * - Colorized or paginated output formatting * - Most of the `git log` options * * This does have: * * - Examples of translating command line arguments to equivalent libgit2 * revwalker configuration calls * - Simplified options to apply pathspec limits and to show basic diffs */ /** log_state represents walker being configured while handling options */ struct log_state { git_repository *repo; const char *repodir; git_revwalk *walker; int hide; int sorting; int revisions; }; /** utility functions that are called to configure the walker */ static void set_sorting(struct log_state *s, unsigned int sort_mode); static void push_rev(struct log_state *s, git_object *obj, int hide); static int add_revision(struct log_state *s, const char *revstr); /** log_options holds other command line options that affect log output */ struct log_options { int show_diff; int show_log_size; int skip, limit; int min_parents, max_parents; git_time_t before; git_time_t after; const char *author; const char *committer; const char *grep; }; /** utility functions that parse options and help with log output */ static int parse_options( struct log_state *s, struct log_options *opt, int argc, char **argv); static void print_time(const git_time *intime, const char *prefix); static void print_commit(git_commit *commit, struct log_options *opts); static int match_with_parent(git_commit *commit, int i, git_diff_options *); /** utility functions for filtering */ static int signature_matches(const git_signature *sig, const char *filter); static int log_message_matches(const git_commit *commit, const char *filter); int lg2_log(git_repository *repo, int argc, char *argv[]) { int i, count = 0, printed = 0, parents, last_arg; struct log_state s; struct log_options opt; git_diff_options diffopts = GIT_DIFF_OPTIONS_INIT; git_oid oid; git_commit *commit = NULL; git_pathspec *ps = NULL; /** Parse arguments and set up revwalker. */ last_arg = parse_options(&s, &opt, argc, argv); s.repo = repo; diffopts.pathspec.strings = &argv[last_arg]; diffopts.pathspec.count = argc - last_arg; if (diffopts.pathspec.count > 0) check_lg2(git_pathspec_new(&ps, &diffopts.pathspec), "Building pathspec", NULL); if (!s.revisions) add_revision(&s, NULL); /** Use the revwalker to traverse the history. */ printed = count = 0; for (; !git_revwalk_next(&oid, s.walker); git_commit_free(commit)) { check_lg2(git_commit_lookup(&commit, s.repo, &oid), "Failed to look up commit", NULL); parents = (int)git_commit_parentcount(commit); if (parents < opt.min_parents) continue; if (opt.max_parents > 0 && parents > opt.max_parents) continue; if (diffopts.pathspec.count > 0) { int unmatched = parents; if (parents == 0) { git_tree *tree; check_lg2(git_commit_tree(&tree, commit), "Get tree", NULL); if (git_pathspec_match_tree( NULL, tree, GIT_PATHSPEC_NO_MATCH_ERROR, ps) != 0) unmatched = 1; git_tree_free(tree); } else if (parents == 1) { unmatched = match_with_parent(commit, 0, &diffopts) ? 0 : 1; } else { for (i = 0; i < parents; ++i) { if (match_with_parent(commit, i, &diffopts)) unmatched--; } } if (unmatched > 0) continue; } if (!signature_matches(git_commit_author(commit), opt.author)) continue; if (!signature_matches(git_commit_committer(commit), opt.committer)) continue; if (!log_message_matches(commit, opt.grep)) continue; if (count++ < opt.skip) continue; if (opt.limit != -1 && printed++ >= opt.limit) { git_commit_free(commit); break; } print_commit(commit, &opt); if (opt.show_diff) { git_tree *a = NULL, *b = NULL; git_diff *diff = NULL; if (parents > 1) continue; check_lg2(git_commit_tree(&b, commit), "Get tree", NULL); if (parents == 1) { git_commit *parent; check_lg2(git_commit_parent(&parent, commit, 0), "Get parent", NULL); check_lg2(git_commit_tree(&a, parent), "Tree for parent", NULL); git_commit_free(parent); } check_lg2(git_diff_tree_to_tree( &diff, git_commit_owner(commit), a, b, &diffopts), "Diff commit with parent", NULL); check_lg2( git_diff_print(diff, GIT_DIFF_FORMAT_PATCH, diff_output, NULL), "Displaying diff", NULL); git_diff_free(diff); git_tree_free(a); git_tree_free(b); } } git_pathspec_free(ps); git_revwalk_free(s.walker); return 0; } /** Determine if the given git_signature does not contain the filter text. */ static int signature_matches(const git_signature *sig, const char *filter) { if (filter == NULL) return 1; if (sig != NULL && (strstr(sig->name, filter) != NULL || strstr(sig->email, filter) != NULL)) return 1; return 0; } static int log_message_matches(const git_commit *commit, const char *filter) { const char *message = NULL; if (filter == NULL) return 1; if ((message = git_commit_message(commit)) != NULL && strstr(message, filter) != NULL) return 1; return 0; } /** Push object (for hide or show) onto revwalker. */ static void push_rev(struct log_state *s, git_object *obj, int hide) { hide = s->hide ^ hide; /** Create revwalker on demand if it doesn't already exist. */ if (!s->walker) { check_lg2(git_revwalk_new(&s->walker, s->repo), "Could not create revision walker", NULL); git_revwalk_sorting(s->walker, s->sorting); } if (!obj) check_lg2(git_revwalk_push_head(s->walker), "Could not find repository HEAD", NULL); else if (hide) check_lg2(git_revwalk_hide(s->walker, git_object_id(obj)), "Reference does not refer to a commit", NULL); else check_lg2(git_revwalk_push(s->walker, git_object_id(obj)), "Reference does not refer to a commit", NULL); git_object_free(obj); } /** Parse revision string and add revs to walker. */ static int add_revision(struct log_state *s, const char *revstr) { git_revspec revs; int hide = 0; if (!revstr) { push_rev(s, NULL, hide); return 0; } if (*revstr == '^') { revs.flags = GIT_REVSPEC_SINGLE; hide = !hide; if (git_revparse_single(&revs.from, s->repo, revstr + 1) < 0) return -1; } else if (git_revparse(&revs, s->repo, revstr) < 0) return -1; if ((revs.flags & GIT_REVSPEC_SINGLE) != 0) push_rev(s, revs.from, hide); else { push_rev(s, revs.to, hide); if ((revs.flags & GIT_REVSPEC_MERGE_BASE) != 0) { git_oid base; check_lg2(git_merge_base(&base, s->repo, git_object_id(revs.from), git_object_id(revs.to)), "Could not find merge base", revstr); check_lg2( git_object_lookup(&revs.to, s->repo, &base, GIT_OBJECT_COMMIT), "Could not find merge base commit", NULL); push_rev(s, revs.to, hide); } push_rev(s, revs.from, !hide); } return 0; } /** Update revwalker with sorting mode. */ static void set_sorting(struct log_state *s, unsigned int sort_mode) { /** Open repo on demand if it isn't already open. */ if (!s->repo) { if (!s->repodir) s->repodir = "."; check_lg2(git_repository_open_ext(&s->repo, s->repodir, 0, NULL), "Could not open repository", s->repodir); } /** Create revwalker on demand if it doesn't already exist. */ if (!s->walker) check_lg2(git_revwalk_new(&s->walker, s->repo), "Could not create revision walker", NULL); if (sort_mode == GIT_SORT_REVERSE) s->sorting = s->sorting ^ GIT_SORT_REVERSE; else s->sorting = sort_mode | (s->sorting & GIT_SORT_REVERSE); git_revwalk_sorting(s->walker, s->sorting); } /** Helper to format a git_time value like Git. */ static void print_time(const git_time *intime, const char *prefix) { char sign, out[32]; struct tm *intm; int offset, hours, minutes; time_t t; offset = intime->offset; if (offset < 0) { sign = '-'; offset = -offset; } else { sign = '+'; } hours = offset / 60; minutes = offset % 60; t = (time_t)intime->time + (intime->offset * 60); intm = gmtime(&t); strftime(out, sizeof(out), "%a %b %e %T %Y", intm); printf("%s%s %c%02d%02d\n", prefix, out, sign, hours, minutes); } /** Helper to print a commit object. */ static void print_commit(git_commit *commit, struct log_options *opts) { char buf[GIT_OID_HEXSZ + 1]; int i, count; const git_signature *sig; const char *scan, *eol; git_oid_tostr(buf, sizeof(buf), git_commit_id(commit)); printf("commit %s\n", buf); if (opts->show_log_size) { printf("log size %d\n", (int)strlen(git_commit_message(commit))); } if ((count = (int)git_commit_parentcount(commit)) > 1) { printf("Merge:"); for (i = 0; i < count; ++i) { git_oid_tostr(buf, 8, git_commit_parent_id(commit, i)); printf(" %s", buf); } printf("\n"); } if ((sig = git_commit_author(commit)) != NULL) { printf("Author: %s <%s>\n", sig->name, sig->email); print_time(&sig->when, "Date: "); } printf("\n"); for (scan = git_commit_message(commit); scan && *scan; ) { for (eol = scan; *eol && *eol != '\n'; ++eol) /* find eol */; printf(" %.*s\n", (int)(eol - scan), scan); scan = *eol ? eol + 1 : NULL; } printf("\n"); } /** Helper to find how many files in a commit changed from its nth parent. */ static int match_with_parent(git_commit *commit, int i, git_diff_options *opts) { git_commit *parent; git_tree *a, *b; git_diff *diff; int ndeltas; check_lg2( git_commit_parent(&parent, commit, (size_t)i), "Get parent", NULL); check_lg2(git_commit_tree(&a, parent), "Tree for parent", NULL); check_lg2(git_commit_tree(&b, commit), "Tree for commit", NULL); check_lg2( git_diff_tree_to_tree(&diff, git_commit_owner(commit), a, b, opts), "Checking diff between parent and commit", NULL); ndeltas = (int)git_diff_num_deltas(diff); git_diff_free(diff); git_tree_free(a); git_tree_free(b); git_commit_free(parent); return ndeltas > 0; } /** Print a usage message for the program. */ static void usage(const char *message, const char *arg) { if (message && arg) fprintf(stderr, "%s: %s\n", message, arg); else if (message) fprintf(stderr, "%s\n", message); fprintf(stderr, "usage: log [<options>]\n"); exit(1); } /** Parse some log command line options. */ static int parse_options( struct log_state *s, struct log_options *opt, int argc, char **argv) { struct args_info args = ARGS_INFO_INIT; memset(s, 0, sizeof(*s)); s->sorting = GIT_SORT_TIME; memset(opt, 0, sizeof(*opt)); opt->max_parents = -1; opt->limit = -1; for (args.pos = 1; args.pos < argc; ++args.pos) { const char *a = argv[args.pos]; if (a[0] != '-') { if (!add_revision(s, a)) s->revisions++; else /** Try failed revision parse as filename. */ break; } else if (!match_arg_separator(&args)) { break; } else if (!strcmp(a, "--date-order")) set_sorting(s, GIT_SORT_TIME); else if (!strcmp(a, "--topo-order")) set_sorting(s, GIT_SORT_TOPOLOGICAL); else if (!strcmp(a, "--reverse")) set_sorting(s, GIT_SORT_REVERSE); else if (match_str_arg(&opt->author, &args, "--author")) /** Found valid --author */ ; else if (match_str_arg(&opt->committer, &args, "--committer")) /** Found valid --committer */ ; else if (match_str_arg(&opt->grep, &args, "--grep")) /** Found valid --grep */ ; else if (match_str_arg(&s->repodir, &args, "--git-dir")) /** Found git-dir. */ ; else if (match_int_arg(&opt->skip, &args, "--skip", 0)) /** Found valid --skip. */ ; else if (match_int_arg(&opt->limit, &args, "--max-count", 0)) /** Found valid --max-count. */ ; else if (a[1] >= '0' && a[1] <= '9') is_integer(&opt->limit, a + 1, 0); else if (match_int_arg(&opt->limit, &args, "-n", 0)) /** Found valid -n. */ ; else if (!strcmp(a, "--merges")) opt->min_parents = 2; else if (!strcmp(a, "--no-merges")) opt->max_parents = 1; else if (!strcmp(a, "--no-min-parents")) opt->min_parents = 0; else if (!strcmp(a, "--no-max-parents")) opt->max_parents = -1; else if (match_int_arg(&opt->max_parents, &args, "--max-parents=", 1)) /** Found valid --max-parents. */ ; else if (match_int_arg(&opt->min_parents, &args, "--min-parents=", 0)) /** Found valid --min_parents. */ ; else if (!strcmp(a, "-p") || !strcmp(a, "-u") || !strcmp(a, "--patch")) opt->show_diff = 1; else if (!strcmp(a, "--log-size")) opt->show_log_size = 1; else usage("Unsupported argument", a); } return args.pos; }
0
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2/examples/describe.c
/* * libgit2 "describe" example - shows how to describe commits * * Written by the libgit2 contributors * * To the extent possible under law, the author(s) have dedicated all copyright * and related and neighboring rights to this software to the public domain * worldwide. This software is distributed without any warranty. * * You should have received a copy of the CC0 Public Domain Dedication along * with this software. If not, see * <http://creativecommons.org/publicdomain/zero/1.0/>. */ #include "common.h" /** * The following example partially reimplements the `git describe` command * and some of its options. * * These commands should work: * - Describe HEAD with default options (`describe`) * - Describe specified revision (`describe master~2`) * - Describe specified revisions (`describe master~2 HEAD~3`) * - Describe HEAD with dirty state suffix (`describe --dirty=*`) * - Describe consider all refs (`describe --all master`) * - Describe consider lightweight tags (`describe --tags temp-tag`) * - Describe show non-default abbreviated size (`describe --abbrev=10`) * - Describe always output the long format if matches a tag (`describe --long v1.0`) * - Describe consider only tags of specified pattern (`describe --match v*-release`) * - Describe show the fallback result (`describe --always`) * - Describe follow only the first parent commit (`describe --first-parent`) * * The command line parsing logic is simplified and doesn't handle * all of the use cases. */ /** describe_options represents the parsed command line options */ struct describe_options { const char **commits; size_t commit_count; git_describe_options describe_options; git_describe_format_options format_options; }; static void opts_add_commit(struct describe_options *opts, const char *commit) { size_t sz; assert(opts != NULL); sz = ++opts->commit_count * sizeof(opts->commits[0]); opts->commits = xrealloc((void *) opts->commits, sz); opts->commits[opts->commit_count - 1] = commit; } static void do_describe_single(git_repository *repo, struct describe_options *opts, const char *rev) { git_object *commit; git_describe_result *describe_result; git_buf buf = { 0 }; if (rev) { check_lg2(git_revparse_single(&commit, repo, rev), "Failed to lookup rev", rev); check_lg2(git_describe_commit(&describe_result, commit, &opts->describe_options), "Failed to describe rev", rev); } else check_lg2(git_describe_workdir(&describe_result, repo, &opts->describe_options), "Failed to describe workdir", NULL); check_lg2(git_describe_format(&buf, describe_result, &opts->format_options), "Failed to format describe rev", rev); printf("%s\n", buf.ptr); } static void do_describe(git_repository *repo, struct describe_options *opts) { if (opts->commit_count == 0) do_describe_single(repo, opts, NULL); else { size_t i; for (i = 0; i < opts->commit_count; i++) do_describe_single(repo, opts, opts->commits[i]); } } static void print_usage(void) { fprintf(stderr, "usage: see `git help describe`\n"); exit(1); } /** Parse command line arguments */ static void parse_options(struct describe_options *opts, int argc, char **argv) { struct args_info args = ARGS_INFO_INIT; for (args.pos = 1; args.pos < argc; ++args.pos) { const char *curr = argv[args.pos]; if (curr[0] != '-') { opts_add_commit(opts, curr); } else if (!strcmp(curr, "--all")) { opts->describe_options.describe_strategy = GIT_DESCRIBE_ALL; } else if (!strcmp(curr, "--tags")) { opts->describe_options.describe_strategy = GIT_DESCRIBE_TAGS; } else if (!strcmp(curr, "--exact-match")) { opts->describe_options.max_candidates_tags = 0; } else if (!strcmp(curr, "--long")) { opts->format_options.always_use_long_format = 1; } else if (!strcmp(curr, "--always")) { opts->describe_options.show_commit_oid_as_fallback = 1; } else if (!strcmp(curr, "--first-parent")) { opts->describe_options.only_follow_first_parent = 1; } else if (optional_str_arg(&opts->format_options.dirty_suffix, &args, "--dirty", "-dirty")) { } else if (match_int_arg((int *)&opts->format_options.abbreviated_size, &args, "--abbrev", 0)) { } else if (match_int_arg((int *)&opts->describe_options.max_candidates_tags, &args, "--candidates", 0)) { } else if (match_str_arg(&opts->describe_options.pattern, &args, "--match")) { } else { print_usage(); } } if (opts->commit_count > 0) { if (opts->format_options.dirty_suffix) fatal("--dirty is incompatible with commit-ishes", NULL); } else { if (!opts->format_options.dirty_suffix || !opts->format_options.dirty_suffix[0]) { opts_add_commit(opts, "HEAD"); } } } /** Initialize describe_options struct */ static void describe_options_init(struct describe_options *opts) { memset(opts, 0, sizeof(*opts)); opts->commits = NULL; opts->commit_count = 0; git_describe_options_init(&opts->describe_options, GIT_DESCRIBE_OPTIONS_VERSION); git_describe_format_options_init(&opts->format_options, GIT_DESCRIBE_FORMAT_OPTIONS_VERSION); } int lg2_describe(git_repository *repo, int argc, char **argv) { struct describe_options opts; describe_options_init(&opts); parse_options(&opts, argc, argv); do_describe(repo, &opts); 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/examples/ls-remote.c
#include "common.h" static int use_remote(git_repository *repo, char *name) { git_remote *remote = NULL; int error; const git_remote_head **refs; size_t refs_len, i; git_remote_callbacks callbacks = GIT_REMOTE_CALLBACKS_INIT; /* Find the remote by name */ error = git_remote_lookup(&remote, repo, name); if (error < 0) { error = git_remote_create_anonymous(&remote, repo, name); if (error < 0) goto cleanup; } /** * Connect to the remote and call the printing function for * each of the remote references. */ callbacks.credentials = cred_acquire_cb; error = git_remote_connect(remote, GIT_DIRECTION_FETCH, &callbacks, NULL, NULL); if (error < 0) goto cleanup; /** * Get the list of references on the remote and print out * their name next to what they point to. */ if (git_remote_ls(&refs, &refs_len, remote) < 0) goto cleanup; for (i = 0; i < refs_len; i++) { char oid[GIT_OID_HEXSZ + 1] = {0}; git_oid_fmt(oid, &refs[i]->oid); printf("%s\t%s\n", oid, refs[i]->name); } cleanup: git_remote_free(remote); return error; } /** Entry point for this command */ int lg2_ls_remote(git_repository *repo, int argc, char **argv) { int error; if (argc < 2) { fprintf(stderr, "usage: %s ls-remote <remote>\n", argv[-1]); return EXIT_FAILURE; } error = use_remote(repo, argv[1]); 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/examples/args.c
#include "common.h" #include "args.h" size_t is_prefixed(const char *str, const char *pfx) { size_t len = strlen(pfx); return strncmp(str, pfx, len) ? 0 : len; } int optional_str_arg( const char **out, struct args_info *args, const char *opt, const char *def) { const char *found = args->argv[args->pos]; size_t len = is_prefixed(found, opt); if (!len) return 0; if (!found[len]) { if (args->pos + 1 == args->argc) { *out = def; return 1; } args->pos += 1; *out = args->argv[args->pos]; return 1; } if (found[len] == '=') { *out = found + len + 1; return 1; } return 0; } int match_str_arg( const char **out, struct args_info *args, const char *opt) { const char *found = args->argv[args->pos]; size_t len = is_prefixed(found, opt); if (!len) return 0; if (!found[len]) { if (args->pos + 1 == args->argc) fatal("expected value following argument", opt); args->pos += 1; *out = args->argv[args->pos]; return 1; } if (found[len] == '=') { *out = found + len + 1; return 1; } return 0; } static const char *match_numeric_arg(struct args_info *args, const char *opt) { const char *found = args->argv[args->pos]; size_t len = is_prefixed(found, opt); if (!len) return NULL; if (!found[len]) { if (args->pos + 1 == args->argc) fatal("expected numeric value following argument", opt); args->pos += 1; found = args->argv[args->pos]; } else { found = found + len; if (*found == '=') found++; } return found; } int match_uint16_arg( uint16_t *out, struct args_info *args, const char *opt) { const char *found = match_numeric_arg(args, opt); uint16_t val; char *endptr = NULL; if (!found) return 0; val = (uint16_t)strtoul(found, &endptr, 0); if (!endptr || *endptr != '\0') fatal("expected number after argument", opt); if (out) *out = val; return 1; } int match_uint32_arg( uint32_t *out, struct args_info *args, const char *opt) { const char *found = match_numeric_arg(args, opt); uint16_t val; char *endptr = NULL; if (!found) return 0; val = (uint32_t)strtoul(found, &endptr, 0); if (!endptr || *endptr != '\0') fatal("expected number after argument", opt); if (out) *out = val; return 1; } static int match_int_internal( int *out, const char *str, int allow_negative, const char *opt) { char *endptr = NULL; int val = (int)strtol(str, &endptr, 10); if (!endptr || *endptr != '\0') fatal("expected number", opt); else if (val < 0 && !allow_negative) fatal("negative values are not allowed", opt); if (out) *out = val; return 1; } int match_bool_arg(int *out, struct args_info *args, const char *opt) { const char *found = args->argv[args->pos]; if (!strcmp(found, opt)) { *out = 1; return 1; } if (!strncmp(found, "--no-", strlen("--no-")) && !strcmp(found + strlen("--no-"), opt + 2)) { *out = 0; return 1; } *out = -1; return 0; } int is_integer(int *out, const char *str, int allow_negative) { return match_int_internal(out, str, allow_negative, NULL); } int match_int_arg( int *out, struct args_info *args, const char *opt, int allow_negative) { const char *found = match_numeric_arg(args, opt); if (!found) return 0; return match_int_internal(out, found, allow_negative, opt); } int match_arg_separator(struct args_info *args) { if (args->opts_done) return 1; if (strcmp(args->argv[args->pos], "--") != 0) return 0; args->opts_done = 1; args->pos++; return 1; } void strarray_from_args(git_strarray *array, struct args_info *args) { size_t i; array->count = args->argc - args->pos; array->strings = calloc(array->count, sizeof(char *)); assert(array->strings != NULL); for (i = 0; args->pos < args->argc; ++args->pos) { array->strings[i++] = args->argv[args->pos]; } args->pos = args->argc; }
0
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2/examples/init.c
/* * libgit2 "init" example - shows how to initialize a new repo * * Written by the libgit2 contributors * * To the extent possible under law, the author(s) have dedicated all copyright * and related and neighboring rights to this software to the public domain * worldwide. This software is distributed without any warranty. * * You should have received a copy of the CC0 Public Domain Dedication along * with this software. If not, see * <http://creativecommons.org/publicdomain/zero/1.0/>. */ #include "common.h" /** * This is a sample program that is similar to "git init". See the * documentation for that (try "git help init") to understand what this * program is emulating. * * This demonstrates using the libgit2 APIs to initialize a new repository. * * This also contains a special additional option that regular "git init" * does not support which is "--initial-commit" to make a first empty commit. * That is demonstrated in the "create_initial_commit" helper function. */ /** Forward declarations of helpers */ struct init_opts { int no_options; int quiet; int bare; int initial_commit; uint32_t shared; const char *template; const char *gitdir; const char *dir; }; static void create_initial_commit(git_repository *repo); static void parse_opts(struct init_opts *o, int argc, char *argv[]); int lg2_init(git_repository *repo, int argc, char *argv[]) { struct init_opts o = { 1, 0, 0, 0, GIT_REPOSITORY_INIT_SHARED_UMASK, 0, 0, 0 }; parse_opts(&o, argc, argv); /* Initialize repository. */ if (o.no_options) { /** * No options were specified, so let's demonstrate the default * simple case of git_repository_init() API usage... */ check_lg2(git_repository_init(&repo, o.dir, 0), "Could not initialize repository", NULL); } else { /** * Some command line options were specified, so we'll use the * extended init API to handle them */ git_repository_init_options initopts = GIT_REPOSITORY_INIT_OPTIONS_INIT; initopts.flags = GIT_REPOSITORY_INIT_MKPATH; if (o.bare) initopts.flags |= GIT_REPOSITORY_INIT_BARE; if (o.template) { initopts.flags |= GIT_REPOSITORY_INIT_EXTERNAL_TEMPLATE; initopts.template_path = o.template; } if (o.gitdir) { /** * If you specified a separate git directory, then initialize * the repository at that path and use the second path as the * working directory of the repository (with a git-link file) */ initopts.workdir_path = o.dir; o.dir = o.gitdir; } if (o.shared != 0) initopts.mode = o.shared; check_lg2(git_repository_init_ext(&repo, o.dir, &initopts), "Could not initialize repository", NULL); } /** Print a message to stdout like "git init" does. */ if (!o.quiet) { if (o.bare || o.gitdir) o.dir = git_repository_path(repo); else o.dir = git_repository_workdir(repo); printf("Initialized empty Git repository in %s\n", o.dir); } /** * As an extension to the basic "git init" command, this example * gives the option to create an empty initial commit. This is * mostly to demonstrate what it takes to do that, but also some * people like to have that empty base commit in their repo. */ if (o.initial_commit) { create_initial_commit(repo); printf("Created empty initial commit\n"); } git_repository_free(repo); return 0; } /** * Unlike regular "git init", this example shows how to create an initial * empty commit in the repository. This is the helper function that does * that. */ static void create_initial_commit(git_repository *repo) { git_signature *sig; git_index *index; git_oid tree_id, commit_id; git_tree *tree; /** First use the config to initialize a commit signature for the user. */ if (git_signature_default(&sig, repo) < 0) fatal("Unable to create a commit signature.", "Perhaps 'user.name' and 'user.email' are not set"); /* Now let's create an empty tree for this commit */ if (git_repository_index(&index, repo) < 0) fatal("Could not open repository index", NULL); /** * Outside of this example, you could call git_index_add_bypath() * here to put actual files into the index. For our purposes, we'll * leave it empty for now. */ if (git_index_write_tree(&tree_id, index) < 0) fatal("Unable to write initial tree from index", NULL); git_index_free(index); if (git_tree_lookup(&tree, repo, &tree_id) < 0) fatal("Could not look up initial tree", NULL); /** * Ready to create the initial commit. * * Normally creating a commit would involve looking up the current * HEAD commit and making that be the parent of the initial commit, * but here this is the first commit so there will be no parent. */ if (git_commit_create_v( &commit_id, repo, "HEAD", sig, sig, NULL, "Initial commit", tree, 0) < 0) fatal("Could not create the initial commit", NULL); /** Clean up so we don't leak memory. */ git_tree_free(tree); git_signature_free(sig); } static void usage(const char *error, const char *arg) { fprintf(stderr, "error: %s '%s'\n", error, arg); fprintf(stderr, "usage: init [-q | --quiet] [--bare] [--template=<dir>]\n" " [--shared[=perms]] [--initial-commit]\n" " [--separate-git-dir] <directory>\n"); exit(1); } /** Parse the tail of the --shared= argument. */ static uint32_t parse_shared(const char *shared) { if (!strcmp(shared, "false") || !strcmp(shared, "umask")) return GIT_REPOSITORY_INIT_SHARED_UMASK; else if (!strcmp(shared, "true") || !strcmp(shared, "group")) return GIT_REPOSITORY_INIT_SHARED_GROUP; else if (!strcmp(shared, "all") || !strcmp(shared, "world") || !strcmp(shared, "everybody")) return GIT_REPOSITORY_INIT_SHARED_ALL; else if (shared[0] == '0') { long val; char *end = NULL; val = strtol(shared + 1, &end, 8); if (end == shared + 1 || *end != 0) usage("invalid octal value for --shared", shared); return (uint32_t)val; } else usage("unknown value for --shared", shared); return 0; } static void parse_opts(struct init_opts *o, int argc, char *argv[]) { struct args_info args = ARGS_INFO_INIT; const char *sharedarg; /** Process arguments. */ for (args.pos = 1; args.pos < argc; ++args.pos) { char *a = argv[args.pos]; if (a[0] == '-') o->no_options = 0; if (a[0] != '-') { if (o->dir != NULL) usage("extra argument", a); o->dir = a; } else if (!strcmp(a, "-q") || !strcmp(a, "--quiet")) o->quiet = 1; else if (!strcmp(a, "--bare")) o->bare = 1; else if (!strcmp(a, "--shared")) o->shared = GIT_REPOSITORY_INIT_SHARED_GROUP; else if (!strcmp(a, "--initial-commit")) o->initial_commit = 1; else if (match_str_arg(&sharedarg, &args, "--shared")) o->shared = parse_shared(sharedarg); else if (!match_str_arg(&o->template, &args, "--template") || !match_str_arg(&o->gitdir, &args, "--separate-git-dir")) usage("unknown option", a); } if (!o->dir) usage("must specify directory to init", ""); }
0
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2/examples/index-pack.c
#include "common.h" /* * This could be run in the main loop whilst the application waits for * the indexing to finish in a worker thread */ static int index_cb(const git_indexer_progress *stats, void *data) { (void)data; printf("\rProcessing %u of %u", stats->indexed_objects, stats->total_objects); return 0; } int lg2_index_pack(git_repository *repo, int argc, char **argv) { git_indexer *idx; git_indexer_progress stats = {0, 0}; int error; char hash[GIT_OID_HEXSZ + 1] = {0}; int fd; ssize_t read_bytes; char buf[512]; (void)repo; if (argc < 2) { fprintf(stderr, "usage: %s index-pack <packfile>\n", argv[-1]); return EXIT_FAILURE; } if (git_indexer_new(&idx, ".", 0, NULL, NULL) < 0) { puts("bad idx"); return -1; } if ((fd = open(argv[1], 0)) < 0) { perror("open"); return -1; } do { read_bytes = read(fd, buf, sizeof(buf)); if (read_bytes < 0) break; if ((error = git_indexer_append(idx, buf, read_bytes, &stats)) < 0) goto cleanup; index_cb(&stats, NULL); } while (read_bytes > 0); if (read_bytes < 0) { error = -1; perror("failed reading"); goto cleanup; } if ((error = git_indexer_commit(idx, &stats)) < 0) goto cleanup; printf("\rIndexing %u of %u\n", stats.indexed_objects, stats.total_objects); git_oid_fmt(hash, git_indexer_hash(idx)); puts(hash); cleanup: close(fd); git_indexer_free(idx); 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/examples/common.c
/* * Utilities library for libgit2 examples * * Written by the libgit2 contributors * * To the extent possible under law, the author(s) have dedicated all copyright * and related and neighboring rights to this software to the public domain * worldwide. This software is distributed without any warranty. * * You should have received a copy of the CC0 Public Domain Dedication along * with this software. If not, see * <http://creativecommons.org/publicdomain/zero/1.0/>. */ #include "common.h" #ifndef _WIN32 # include <unistd.h> #endif #include <errno.h> void check_lg2(int error, const char *message, const char *extra) { const git_error *lg2err; const char *lg2msg = "", *lg2spacer = ""; if (!error) return; if ((lg2err = git_error_last()) != NULL && lg2err->message != NULL) { lg2msg = lg2err->message; lg2spacer = " - "; } if (extra) fprintf(stderr, "%s '%s' [%d]%s%s\n", message, extra, error, lg2spacer, lg2msg); else fprintf(stderr, "%s [%d]%s%s\n", message, error, lg2spacer, lg2msg); exit(1); } void fatal(const char *message, const char *extra) { if (extra) fprintf(stderr, "%s %s\n", message, extra); else fprintf(stderr, "%s\n", message); exit(1); } int diff_output( const git_diff_delta *d, const git_diff_hunk *h, const git_diff_line *l, void *p) { FILE *fp = (FILE*)p; (void)d; (void)h; if (!fp) fp = stdout; if (l->origin == GIT_DIFF_LINE_CONTEXT || l->origin == GIT_DIFF_LINE_ADDITION || l->origin == GIT_DIFF_LINE_DELETION) fputc(l->origin, fp); fwrite(l->content, 1, l->content_len, fp); return 0; } void treeish_to_tree( git_tree **out, git_repository *repo, const char *treeish) { git_object *obj = NULL; check_lg2( git_revparse_single(&obj, repo, treeish), "looking up object", treeish); check_lg2( git_object_peel((git_object **)out, obj, GIT_OBJECT_TREE), "resolving object to tree", treeish); git_object_free(obj); } void *xrealloc(void *oldp, size_t newsz) { void *p = realloc(oldp, newsz); if (p == NULL) { fprintf(stderr, "Cannot allocate memory, exiting.\n"); exit(1); } return p; } int resolve_refish(git_annotated_commit **commit, git_repository *repo, const char *refish) { git_reference *ref; git_object *obj; int err = 0; assert(commit != NULL); err = git_reference_dwim(&ref, repo, refish); if (err == GIT_OK) { git_annotated_commit_from_ref(commit, repo, ref); git_reference_free(ref); return 0; } err = git_revparse_single(&obj, repo, refish); if (err == GIT_OK) { err = git_annotated_commit_lookup(commit, repo, git_object_id(obj)); git_object_free(obj); } return err; } static int readline(char **out) { int c, error = 0, length = 0, allocated = 0; char *line = NULL; errno = 0; while ((c = getchar()) != EOF) { if (length == allocated) { allocated += 16; if ((line = realloc(line, allocated)) == NULL) { error = -1; goto error; } } if (c == '\n') break; line[length++] = c; } if (errno != 0) { error = -1; goto error; } line[length] = '\0'; *out = line; line = NULL; error = length; error: free(line); return error; } static int ask(char **out, const char *prompt, char optional) { printf("%s ", prompt); fflush(stdout); if (!readline(out) && !optional) { fprintf(stderr, "Could not read response: %s", strerror(errno)); return -1; } return 0; } int cred_acquire_cb(git_credential **out, const char *url, const char *username_from_url, unsigned int allowed_types, void *payload) { char *username = NULL, *password = NULL, *privkey = NULL, *pubkey = NULL; int error = 1; UNUSED(url); UNUSED(payload); if (username_from_url) { if ((username = strdup(username_from_url)) == NULL) goto out; } else if ((error = ask(&username, "Username:", 0)) < 0) { goto out; } if (allowed_types & GIT_CREDENTIAL_SSH_KEY) { int n; if ((error = ask(&privkey, "SSH Key:", 0)) < 0 || (error = ask(&password, "Password:", 1)) < 0) goto out; if ((n = snprintf(NULL, 0, "%s.pub", privkey)) < 0 || (pubkey = malloc(n + 1)) == NULL || (n = snprintf(pubkey, n + 1, "%s.pub", privkey)) < 0) goto out; error = git_credential_ssh_key_new(out, username, pubkey, privkey, password); } else if (allowed_types & GIT_CREDENTIAL_USERPASS_PLAINTEXT) { if ((error = ask(&password, "Password:", 1)) < 0) goto out; error = git_credential_userpass_plaintext_new(out, username, password); } else if (allowed_types & GIT_CREDENTIAL_USERNAME) { error = git_credential_username_new(out, username); } out: free(username); free(password); free(privkey); free(pubkey); return error; } char *read_file(const char *path) { ssize_t total = 0; char *buf = NULL; struct stat st; int fd = -1; if ((fd = open(path, O_RDONLY)) < 0 || fstat(fd, &st) < 0) goto out; if ((buf = malloc(st.st_size + 1)) == NULL) goto out; while (total < st.st_size) { ssize_t bytes = read(fd, buf + total, st.st_size - total); if (bytes <= 0) { if (errno == EAGAIN || errno == EINTR) continue; free(buf); buf = NULL; goto out; } total += bytes; } buf[total] = '\0'; out: if (fd >= 0) close(fd); return buf; }
0
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2/examples/general.c
/* * libgit2 "general" example - shows basic libgit2 concepts * * Written by the libgit2 contributors * * To the extent possible under law, the author(s) have dedicated all copyright * and related and neighboring rights to this software to the public domain * worldwide. This software is distributed without any warranty. * * You should have received a copy of the CC0 Public Domain Dedication along * with this software. If not, see * <http://creativecommons.org/publicdomain/zero/1.0/>. */ /** * [**libgit2**][lg] is a portable, pure C implementation of the Git core * methods provided as a re-entrant linkable library with a solid API, * allowing you to write native speed custom Git applications in any * language which supports C bindings. * * This file is an example of using that API in a real, compilable C file. * As the API is updated, this file will be updated to demonstrate the new * functionality. * * If you're trying to write something in C using [libgit2][lg], you should * also check out the generated [API documentation][ap]. We try to link to * the relevant sections of the API docs in each section in this file. * * **libgit2** (for the most part) only implements the core plumbing * functions, not really the higher level porcelain stuff. For a primer on * Git Internals that you will need to know to work with Git at this level, * check out [Chapter 10][pg] of the Pro Git book. * * [lg]: http://libgit2.github.com * [ap]: http://libgit2.github.com/libgit2 * [pg]: https://git-scm.com/book/en/v2/Git-Internals-Plumbing-and-Porcelain */ #include "common.h" /** * ### Includes * * Including the `git2.h` header will include all the other libgit2 headers * that you need. It should be the only thing you need to include in order * to compile properly and get all the libgit2 API. */ #include "git2.h" static void oid_parsing(git_oid *out); static void object_database(git_repository *repo, git_oid *oid); static void commit_writing(git_repository *repo); static void commit_parsing(git_repository *repo); static void tag_parsing(git_repository *repo); static void tree_parsing(git_repository *repo); static void blob_parsing(git_repository *repo); static void revwalking(git_repository *repo); static void index_walking(git_repository *repo); static void reference_listing(git_repository *repo); static void config_files(const char *repo_path, git_repository *repo); /** * Almost all libgit2 functions return 0 on success or negative on error. * This is not production quality error checking, but should be sufficient * as an example. */ static void check_error(int error_code, const char *action) { const git_error *error = git_error_last(); if (!error_code) return; printf("Error %d %s - %s\n", error_code, action, (error && error->message) ? error->message : "???"); exit(1); } int lg2_general(git_repository *repo, int argc, char** argv) { int error; git_oid oid; char *repo_path; /** * Initialize the library, this will set up any global state which libgit2 needs * including threading and crypto */ git_libgit2_init(); /** * ### Opening the Repository * * There are a couple of methods for opening a repository, this being the * simplest. There are also [methods][me] for specifying the index file * and work tree locations, here we assume they are in the normal places. * * (Try running this program against tests/resources/testrepo.git.) * * [me]: http://libgit2.github.com/libgit2/#HEAD/group/repository */ repo_path = (argc > 1) ? argv[1] : "/opt/libgit2-test/.git"; error = git_repository_open(&repo, repo_path); check_error(error, "opening repository"); oid_parsing(&oid); object_database(repo, &oid); commit_writing(repo); commit_parsing(repo); tag_parsing(repo); tree_parsing(repo); blob_parsing(repo); revwalking(repo); index_walking(repo); reference_listing(repo); config_files(repo_path, repo); /** * Finally, when you're done with the repository, you can free it as well. */ git_repository_free(repo); return 0; } /** * ### SHA-1 Value Conversions */ static void oid_parsing(git_oid *oid) { char out[GIT_OID_HEXSZ+1]; char hex[] = "4a202b346bb0fb0db7eff3cffeb3c70babbd2045"; printf("*Hex to Raw*\n"); /** * For our first example, we will convert a 40 character hex value to the * 20 byte raw SHA1 value. * * The `git_oid` is the structure that keeps the SHA value. We will use * this throughout the example for storing the value of the current SHA * key we're working with. */ git_oid_fromstr(oid, hex); /* * Once we've converted the string into the oid value, we can get the raw * value of the SHA by accessing `oid.id` * * Next we will convert the 20 byte raw SHA1 value to a human readable 40 * char hex value. */ printf("\n*Raw to Hex*\n"); out[GIT_OID_HEXSZ] = '\0'; /** * If you have a oid, you can easily get the hex value of the SHA as well. */ git_oid_fmt(out, oid); printf("SHA hex string: %s\n", out); } /** * ### Working with the Object Database * * **libgit2** provides [direct access][odb] to the object database. The * object database is where the actual objects are stored in Git. For * working with raw objects, we'll need to get this structure from the * repository. * * [odb]: http://libgit2.github.com/libgit2/#HEAD/group/odb */ static void object_database(git_repository *repo, git_oid *oid) { char oid_hex[GIT_OID_HEXSZ+1] = { 0 }; const unsigned char *data; const char *str_type; int error; git_odb_object *obj; git_odb *odb; git_object_t otype; git_repository_odb(&odb, repo); /** * #### Raw Object Reading */ printf("\n*Raw Object Read*\n"); /** * We can read raw objects directly from the object database if we have * the oid (SHA) of the object. This allows us to access objects without * knowing their type and inspect the raw bytes unparsed. */ error = git_odb_read(&obj, odb, oid); check_error(error, "finding object in repository"); /** * A raw object only has three properties - the type (commit, blob, tree * or tag), the size of the raw data and the raw, unparsed data itself. * For a commit or tag, that raw data is human readable plain ASCII * text. For a blob it is just file contents, so it could be text or * binary data. For a tree it is a special binary format, so it's unlikely * to be hugely helpful as a raw object. */ data = (const unsigned char *)git_odb_object_data(obj); otype = git_odb_object_type(obj); /** * We provide methods to convert from the object type which is an enum, to * a string representation of that value (and vice-versa). */ str_type = git_object_type2string(otype); printf("object length and type: %d, %s\nobject data: %s\n", (int)git_odb_object_size(obj), str_type, data); /** * For proper memory management, close the object when you are done with * it or it will leak memory. */ git_odb_object_free(obj); /** * #### Raw Object Writing */ printf("\n*Raw Object Write*\n"); /** * You can also write raw object data to Git. This is pretty cool because * it gives you direct access to the key/value properties of Git. Here * we'll write a new blob object that just contains a simple string. * Notice that we have to specify the object type as the `git_otype` enum. */ git_odb_write(oid, odb, "test data", sizeof("test data") - 1, GIT_OBJECT_BLOB); /** * Now that we've written the object, we can check out what SHA1 was * generated when the object was written to our database. */ git_oid_fmt(oid_hex, oid); printf("Written Object: %s\n", oid_hex); /** * Free the object database after usage. */ git_odb_free(odb); } /** * #### Writing Commits * * libgit2 provides a couple of methods to create commit objects easily as * well. There are four different create signatures, we'll just show one * of them here. You can read about the other ones in the [commit API * docs][cd]. * * [cd]: http://libgit2.github.com/libgit2/#HEAD/group/commit */ static void commit_writing(git_repository *repo) { git_oid tree_id, parent_id, commit_id; git_tree *tree; git_commit *parent; git_signature *author, *committer; char oid_hex[GIT_OID_HEXSZ+1] = { 0 }; printf("\n*Commit Writing*\n"); /** * Creating signatures for an authoring identity and time is simple. You * will need to do this to specify who created a commit and when. Default * values for the name and email should be found in the `user.name` and * `user.email` configuration options. See the `config` section of this * example file to see how to access config values. */ git_signature_new(&author, "Scott Chacon", "[email protected]", 123456789, 60); git_signature_new(&committer, "Scott A Chacon", "[email protected]", 987654321, 90); /** * Commit objects need a tree to point to and optionally one or more * parents. Here we're creating oid objects to create the commit with, * but you can also use */ git_oid_fromstr(&tree_id, "f60079018b664e4e79329a7ef9559c8d9e0378d1"); git_tree_lookup(&tree, repo, &tree_id); git_oid_fromstr(&parent_id, "5b5b025afb0b4c913b4c338a42934a3863bf3644"); git_commit_lookup(&parent, repo, &parent_id); /** * Here we actually create the commit object with a single call with all * the values we need to create the commit. The SHA key is written to the * `commit_id` variable here. */ git_commit_create_v( &commit_id, /* out id */ repo, NULL, /* do not update the HEAD */ author, committer, NULL, /* use default message encoding */ "example commit", tree, 1, parent); /** * Now we can take a look at the commit SHA we've generated. */ git_oid_fmt(oid_hex, &commit_id); printf("New Commit: %s\n", oid_hex); /** * Free all objects used in the meanwhile. */ git_tree_free(tree); git_commit_free(parent); git_signature_free(author); git_signature_free(committer); } /** * ### Object Parsing * * libgit2 has methods to parse every object type in Git so you don't have * to work directly with the raw data. This is much faster and simpler * than trying to deal with the raw data yourself. */ /** * #### Commit Parsing * * [Parsing commit objects][pco] is simple and gives you access to all the * data in the commit - the author (name, email, datetime), committer * (same), tree, message, encoding and parent(s). * * [pco]: http://libgit2.github.com/libgit2/#HEAD/group/commit */ static void commit_parsing(git_repository *repo) { const git_signature *author, *cmtter; git_commit *commit, *parent; git_oid oid; char oid_hex[GIT_OID_HEXSZ+1]; const char *message; unsigned int parents, p; int error; time_t time; printf("\n*Commit Parsing*\n"); git_oid_fromstr(&oid, "8496071c1b46c854b31185ea97743be6a8774479"); error = git_commit_lookup(&commit, repo, &oid); check_error(error, "looking up commit"); /** * Each of the properties of the commit object are accessible via methods, * including commonly needed variations, such as `git_commit_time` which * returns the author time and `git_commit_message` which gives you the * commit message (as a NUL-terminated string). */ message = git_commit_message(commit); author = git_commit_author(commit); cmtter = git_commit_committer(commit); time = git_commit_time(commit); /** * The author and committer methods return [git_signature] structures, * which give you name, email and `when`, which is a `git_time` structure, * giving you a timestamp and timezone offset. */ printf("Author: %s (%s)\nCommitter: %s (%s)\nDate: %s\nMessage: %s\n", author->name, author->email, cmtter->name, cmtter->email, ctime(&time), message); /** * Commits can have zero or more parents. The first (root) commit will * have no parents, most commits will have one (i.e. the commit it was * based on) and merge commits will have two or more. Commits can * technically have any number, though it's rare to have more than two. */ parents = git_commit_parentcount(commit); for (p = 0;p < parents;p++) { memset(oid_hex, 0, sizeof(oid_hex)); git_commit_parent(&parent, commit, p); git_oid_fmt(oid_hex, git_commit_id(parent)); printf("Parent: %s\n", oid_hex); git_commit_free(parent); } git_commit_free(commit); } /** * #### Tag Parsing * * You can parse and create tags with the [tag management API][tm], which * functions very similarly to the commit lookup, parsing and creation * methods, since the objects themselves are very similar. * * [tm]: http://libgit2.github.com/libgit2/#HEAD/group/tag */ static void tag_parsing(git_repository *repo) { git_commit *commit; git_object_t type; git_tag *tag; git_oid oid; const char *name, *message; int error; printf("\n*Tag Parsing*\n"); /** * We create an oid for the tag object if we know the SHA and look it up * the same way that we would a commit (or any other object). */ git_oid_fromstr(&oid, "b25fa35b38051e4ae45d4222e795f9df2e43f1d1"); error = git_tag_lookup(&tag, repo, &oid); check_error(error, "looking up tag"); /** * Now that we have the tag object, we can extract the information it * generally contains: the target (usually a commit object), the type of * the target object (usually 'commit'), the name ('v1.0'), the tagger (a * git_signature - name, email, timestamp), and the tag message. */ git_tag_target((git_object **)&commit, tag); name = git_tag_name(tag); /* "test" */ type = git_tag_target_type(tag); /* GIT_OBJECT_COMMIT (object_t enum) */ message = git_tag_message(tag); /* "tag message\n" */ printf("Tag Name: %s\nTag Type: %s\nTag Message: %s\n", name, git_object_type2string(type), message); /** * Free both the commit and tag after usage. */ git_commit_free(commit); git_tag_free(tag); } /** * #### Tree Parsing * * [Tree parsing][tp] is a bit different than the other objects, in that * we have a subtype which is the tree entry. This is not an actual * object type in Git, but a useful structure for parsing and traversing * tree entries. * * [tp]: http://libgit2.github.com/libgit2/#HEAD/group/tree */ static void tree_parsing(git_repository *repo) { const git_tree_entry *entry; size_t cnt; git_object *obj; git_tree *tree; git_oid oid; printf("\n*Tree Parsing*\n"); /** * Create the oid and lookup the tree object just like the other objects. */ git_oid_fromstr(&oid, "f60079018b664e4e79329a7ef9559c8d9e0378d1"); git_tree_lookup(&tree, repo, &oid); /** * Getting the count of entries in the tree so you can iterate over them * if you want to. */ cnt = git_tree_entrycount(tree); /* 2 */ printf("tree entries: %d\n", (int) cnt); entry = git_tree_entry_byindex(tree, 0); printf("Entry name: %s\n", git_tree_entry_name(entry)); /* "README" */ /** * You can also access tree entries by name if you know the name of the * entry you're looking for. */ entry = git_tree_entry_byname(tree, "README"); git_tree_entry_name(entry); /* "README" */ /** * Once you have the entry object, you can access the content or subtree * (or commit, in the case of submodules) that it points to. You can also * get the mode if you want. */ git_tree_entry_to_object(&obj, repo, entry); /* blob */ /** * Remember to close the looked-up object and tree once you are done using it */ git_object_free(obj); git_tree_free(tree); } /** * #### Blob Parsing * * The last object type is the simplest and requires the least parsing * help. Blobs are just file contents and can contain anything, there is * no structure to it. The main advantage to using the [simple blob * api][ba] is that when you're creating blobs you don't have to calculate * the size of the content. There is also a helper for reading a file * from disk and writing it to the db and getting the oid back so you * don't have to do all those steps yourself. * * [ba]: http://libgit2.github.com/libgit2/#HEAD/group/blob */ static void blob_parsing(git_repository *repo) { git_blob *blob; git_oid oid; printf("\n*Blob Parsing*\n"); git_oid_fromstr(&oid, "1385f264afb75a56a5bec74243be9b367ba4ca08"); git_blob_lookup(&blob, repo, &oid); /** * You can access a buffer with the raw contents of the blob directly. * Note that this buffer may not be contain ASCII data for certain blobs * (e.g. binary files): do not consider the buffer a NULL-terminated * string, and use the `git_blob_rawsize` attribute to find out its exact * size in bytes * */ printf("Blob Size: %ld\n", (long)git_blob_rawsize(blob)); /* 8 */ git_blob_rawcontent(blob); /* "content" */ /** * Free the blob after usage. */ git_blob_free(blob); } /** * ### Revwalking * * The libgit2 [revision walking api][rw] provides methods to traverse the * directed graph created by the parent pointers of the commit objects. * Since all commits point back to the commit that came directly before * them, you can walk this parentage as a graph and find all the commits * that were ancestors of (reachable from) a given starting point. This * can allow you to create `git log` type functionality. * * [rw]: http://libgit2.github.com/libgit2/#HEAD/group/revwalk */ static void revwalking(git_repository *repo) { const git_signature *cauth; const char *cmsg; int error; git_revwalk *walk; git_commit *wcommit; git_oid oid; printf("\n*Revwalking*\n"); git_oid_fromstr(&oid, "5b5b025afb0b4c913b4c338a42934a3863bf3644"); /** * To use the revwalker, create a new walker, tell it how you want to sort * the output and then push one or more starting points onto the walker. * If you want to emulate the output of `git log` you would push the SHA * of the commit that HEAD points to into the walker and then start * traversing them. You can also 'hide' commits that you want to stop at * or not see any of their ancestors. So if you want to emulate `git log * branch1..branch2`, you would push the oid of `branch2` and hide the oid * of `branch1`. */ git_revwalk_new(&walk, repo); git_revwalk_sorting(walk, GIT_SORT_TOPOLOGICAL | GIT_SORT_REVERSE); git_revwalk_push(walk, &oid); /** * Now that we have the starting point pushed onto the walker, we start * asking for ancestors. It will return them in the sorting order we asked * for as commit oids. We can then lookup and parse the committed pointed * at by the returned OID; note that this operation is specially fast * since the raw contents of the commit object will be cached in memory */ while ((git_revwalk_next(&oid, walk)) == 0) { error = git_commit_lookup(&wcommit, repo, &oid); check_error(error, "looking up commit during revwalk"); cmsg = git_commit_message(wcommit); cauth = git_commit_author(wcommit); printf("%s (%s)\n", cmsg, cauth->email); git_commit_free(wcommit); } /** * Like the other objects, be sure to free the revwalker when you're done * to prevent memory leaks. Also, make sure that the repository being * walked it not deallocated while the walk is in progress, or it will * result in undefined behavior */ git_revwalk_free(walk); } /** * ### Index File Manipulation * * The [index file API][gi] allows you to read, traverse, update and write * the Git index file (sometimes thought of as the staging area). * * [gi]: http://libgit2.github.com/libgit2/#HEAD/group/index */ static void index_walking(git_repository *repo) { git_index *index; size_t i, ecount; printf("\n*Index Walking*\n"); /** * You can either open the index from the standard location in an open * repository, as we're doing here, or you can open and manipulate any * index file with `git_index_open_bare()`. The index for the repository * will be located and loaded from disk. */ git_repository_index(&index, repo); /** * For each entry in the index, you can get a bunch of information * including the SHA (oid), path and mode which map to the tree objects * that are written out. It also has filesystem properties to help * determine what to inspect for changes (ctime, mtime, dev, ino, uid, * gid, file_size and flags) All these properties are exported publicly in * the `git_index_entry` struct */ ecount = git_index_entrycount(index); for (i = 0; i < ecount; ++i) { const git_index_entry *e = git_index_get_byindex(index, i); printf("path: %s\n", e->path); printf("mtime: %d\n", (int)e->mtime.seconds); printf("fs: %d\n", (int)e->file_size); } git_index_free(index); } /** * ### References * * The [reference API][ref] allows you to list, resolve, create and update * references such as branches, tags and remote references (everything in * the .git/refs directory). * * [ref]: http://libgit2.github.com/libgit2/#HEAD/group/reference */ static void reference_listing(git_repository *repo) { git_strarray ref_list; unsigned i; printf("\n*Reference Listing*\n"); /** * Here we will implement something like `git for-each-ref` simply listing * out all available references and the object SHA they resolve to. * * Now that we have the list of reference names, we can lookup each ref * one at a time and resolve them to the SHA, then print both values out. */ git_reference_list(&ref_list, repo); for (i = 0; i < ref_list.count; ++i) { git_reference *ref; char oid_hex[GIT_OID_HEXSZ+1] = GIT_OID_HEX_ZERO; const char *refname; refname = ref_list.strings[i]; git_reference_lookup(&ref, repo, refname); switch (git_reference_type(ref)) { case GIT_REFERENCE_DIRECT: git_oid_fmt(oid_hex, git_reference_target(ref)); printf("%s [%s]\n", refname, oid_hex); break; case GIT_REFERENCE_SYMBOLIC: printf("%s => %s\n", refname, git_reference_symbolic_target(ref)); break; default: fprintf(stderr, "Unexpected reference type\n"); exit(1); } git_reference_free(ref); } git_strarray_dispose(&ref_list); } /** * ### Config Files * * The [config API][config] allows you to list and update config values * in any of the accessible config file locations (system, global, local). * * [config]: http://libgit2.github.com/libgit2/#HEAD/group/config */ static void config_files(const char *repo_path, git_repository* repo) { const char *email; char config_path[256]; int32_t autocorrect; git_config *cfg; git_config *snap_cfg; int error_code; printf("\n*Config Listing*\n"); /** * Open a config object so we can read global values from it. */ sprintf(config_path, "%s/config", repo_path); check_error(git_config_open_ondisk(&cfg, config_path), "opening config"); if (git_config_get_int32(&autocorrect, cfg, "help.autocorrect") == 0) printf("Autocorrect: %d\n", autocorrect); check_error(git_repository_config_snapshot(&snap_cfg, repo), "config snapshot"); git_config_get_string(&email, snap_cfg, "user.email"); printf("Email: %s\n", email); error_code = git_config_get_int32(&autocorrect, cfg, "help.autocorrect"); switch (error_code) { case 0: printf("Autocorrect: %d\n", autocorrect); break; case GIT_ENOTFOUND: printf("Autocorrect: Undefined\n"); break; default: check_error(error_code, "get_int32 failed"); } git_config_free(cfg); check_error(git_repository_config_snapshot(&snap_cfg, repo), "config snapshot"); error_code = git_config_get_string(&email, snap_cfg, "user.email"); switch (error_code) { case 0: printf("Email: %s\n", email); break; case GIT_ENOTFOUND: printf("Email: Undefined\n"); break; default: check_error(error_code, "get_string failed"); } git_config_free(snap_cfg); }
0
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2/examples/diff.c
/* * libgit2 "diff" example - shows how to use the diff API * * Written by the libgit2 contributors * * To the extent possible under law, the author(s) have dedicated all copyright * and related and neighboring rights to this software to the public domain * worldwide. This software is distributed without any warranty. * * You should have received a copy of the CC0 Public Domain Dedication along * with this software. If not, see * <http://creativecommons.org/publicdomain/zero/1.0/>. */ #include "common.h" /** * This example demonstrates the use of the libgit2 diff APIs to * create `git_diff` objects and display them, emulating a number of * core Git `diff` command line options. * * This covers on a portion of the core Git diff options and doesn't * have particularly good error handling, but it should show most of * the core libgit2 diff APIs, including various types of diffs and * how to do renaming detection and patch formatting. */ static const char *colors[] = { "\033[m", /* reset */ "\033[1m", /* bold */ "\033[31m", /* red */ "\033[32m", /* green */ "\033[36m" /* cyan */ }; enum { OUTPUT_DIFF = (1 << 0), OUTPUT_STAT = (1 << 1), OUTPUT_SHORTSTAT = (1 << 2), OUTPUT_NUMSTAT = (1 << 3), OUTPUT_SUMMARY = (1 << 4) }; enum { CACHE_NORMAL = 0, CACHE_ONLY = 1, CACHE_NONE = 2 }; /** The 'diff_options' struct captures all the various parsed command line options. */ struct diff_options { git_diff_options diffopts; git_diff_find_options findopts; int color; int no_index; int cache; int output; git_diff_format_t format; const char *treeish1; const char *treeish2; const char *dir; }; /** These functions are implemented at the end */ static void usage(const char *message, const char *arg); static void parse_opts(struct diff_options *o, int argc, char *argv[]); static int color_printer( const git_diff_delta*, const git_diff_hunk*, const git_diff_line*, void*); static void diff_print_stats(git_diff *diff, struct diff_options *o); static void compute_diff_no_index(git_diff **diff, struct diff_options *o); int lg2_diff(git_repository *repo, int argc, char *argv[]) { git_tree *t1 = NULL, *t2 = NULL; git_diff *diff; struct diff_options o = { GIT_DIFF_OPTIONS_INIT, GIT_DIFF_FIND_OPTIONS_INIT, -1, -1, 0, 0, GIT_DIFF_FORMAT_PATCH, NULL, NULL, "." }; parse_opts(&o, argc, argv); /** * Possible argument patterns: * * * &lt;sha1&gt; &lt;sha2&gt; * * &lt;sha1&gt; --cached * * &lt;sha1&gt; * * --cached * * --nocache (don't use index data in diff at all) * * --no-index &lt;file1&gt; &lt;file2&gt; * * nothing * * Currently ranged arguments like &lt;sha1&gt;..&lt;sha2&gt; and &lt;sha1&gt;...&lt;sha2&gt; * are not supported in this example */ if (o.no_index >= 0) { compute_diff_no_index(&diff, &o); } else { if (o.treeish1) treeish_to_tree(&t1, repo, o.treeish1); if (o.treeish2) treeish_to_tree(&t2, repo, o.treeish2); if (t1 && t2) check_lg2( git_diff_tree_to_tree(&diff, repo, t1, t2, &o.diffopts), "diff trees", NULL); else if (o.cache != CACHE_NORMAL) { if (!t1) treeish_to_tree(&t1, repo, "HEAD"); if (o.cache == CACHE_NONE) check_lg2( git_diff_tree_to_workdir(&diff, repo, t1, &o.diffopts), "diff tree to working directory", NULL); else check_lg2( git_diff_tree_to_index(&diff, repo, t1, NULL, &o.diffopts), "diff tree to index", NULL); } else if (t1) check_lg2( git_diff_tree_to_workdir_with_index(&diff, repo, t1, &o.diffopts), "diff tree to working directory", NULL); else check_lg2( git_diff_index_to_workdir(&diff, repo, NULL, &o.diffopts), "diff index to working directory", NULL); /** Apply rename and copy detection if requested. */ if ((o.findopts.flags & GIT_DIFF_FIND_ALL) != 0) check_lg2( git_diff_find_similar(diff, &o.findopts), "finding renames and copies", NULL); } /** Generate simple output using libgit2 display helper. */ if (!o.output) o.output = OUTPUT_DIFF; if (o.output != OUTPUT_DIFF) diff_print_stats(diff, &o); if ((o.output & OUTPUT_DIFF) != 0) { if (o.color >= 0) fputs(colors[0], stdout); check_lg2( git_diff_print(diff, o.format, color_printer, &o.color), "displaying diff", NULL); if (o.color >= 0) fputs(colors[0], stdout); } /** Cleanup before exiting. */ git_diff_free(diff); git_tree_free(t1); git_tree_free(t2); return 0; } static void compute_diff_no_index(git_diff **diff, struct diff_options *o) { git_patch *patch = NULL; char *file1_str = NULL; char *file2_str = NULL; git_buf buf = {0}; if (!o->treeish1 || !o->treeish2) { usage("two files should be provided as arguments", NULL); } file1_str = read_file(o->treeish1); if (file1_str == NULL) { usage("file cannot be read", o->treeish1); } file2_str = read_file(o->treeish2); if (file2_str == NULL) { usage("file cannot be read", o->treeish2); } check_lg2( git_patch_from_buffers(&patch, file1_str, strlen(file1_str), o->treeish1, file2_str, strlen(file2_str), o->treeish2, &o->diffopts), "patch buffers", NULL); check_lg2( git_patch_to_buf(&buf, patch), "patch to buf", NULL); check_lg2( git_diff_from_buffer(diff, buf.ptr, buf.size), "diff from patch", NULL); git_patch_free(patch); git_buf_dispose(&buf); free(file1_str); free(file2_str); } static void usage(const char *message, const char *arg) { if (message && arg) fprintf(stderr, "%s: %s\n", message, arg); else if (message) fprintf(stderr, "%s\n", message); fprintf(stderr, "usage: diff [<tree-oid> [<tree-oid>]]\n"); exit(1); } /** This implements very rudimentary colorized output. */ static int color_printer( const git_diff_delta *delta, const git_diff_hunk *hunk, const git_diff_line *line, void *data) { int *last_color = data, color = 0; (void)delta; (void)hunk; if (*last_color >= 0) { switch (line->origin) { case GIT_DIFF_LINE_ADDITION: color = 3; break; case GIT_DIFF_LINE_DELETION: color = 2; break; case GIT_DIFF_LINE_ADD_EOFNL: color = 3; break; case GIT_DIFF_LINE_DEL_EOFNL: color = 2; break; case GIT_DIFF_LINE_FILE_HDR: color = 1; break; case GIT_DIFF_LINE_HUNK_HDR: color = 4; break; default: break; } if (color != *last_color) { if (*last_color == 1 || color == 1) fputs(colors[0], stdout); fputs(colors[color], stdout); *last_color = color; } } return diff_output(delta, hunk, line, stdout); } /** Parse arguments as copied from git-diff. */ static void parse_opts(struct diff_options *o, int argc, char *argv[]) { struct args_info args = ARGS_INFO_INIT; for (args.pos = 1; args.pos < argc; ++args.pos) { const char *a = argv[args.pos]; if (a[0] != '-') { if (o->treeish1 == NULL) o->treeish1 = a; else if (o->treeish2 == NULL) o->treeish2 = a; else usage("Only one or two tree identifiers can be provided", NULL); } else if (!strcmp(a, "-p") || !strcmp(a, "-u") || !strcmp(a, "--patch")) { o->output |= OUTPUT_DIFF; o->format = GIT_DIFF_FORMAT_PATCH; } else if (!strcmp(a, "--cached")) { o->cache = CACHE_ONLY; if (o->no_index >= 0) usage("--cached and --no-index are incompatible", NULL); } else if (!strcmp(a, "--nocache")) o->cache = CACHE_NONE; else if (!strcmp(a, "--name-only") || !strcmp(a, "--format=name")) o->format = GIT_DIFF_FORMAT_NAME_ONLY; else if (!strcmp(a, "--name-status") || !strcmp(a, "--format=name-status")) o->format = GIT_DIFF_FORMAT_NAME_STATUS; else if (!strcmp(a, "--raw") || !strcmp(a, "--format=raw")) o->format = GIT_DIFF_FORMAT_RAW; else if (!strcmp(a, "--format=diff-index")) { o->format = GIT_DIFF_FORMAT_RAW; o->diffopts.id_abbrev = 40; } else if (!strcmp(a, "--no-index")) { o->no_index = 0; if (o->cache == CACHE_ONLY) usage("--cached and --no-index are incompatible", NULL); } else if (!strcmp(a, "--color")) o->color = 0; else if (!strcmp(a, "--no-color")) o->color = -1; else if (!strcmp(a, "-R")) o->diffopts.flags |= GIT_DIFF_REVERSE; else if (!strcmp(a, "-a") || !strcmp(a, "--text")) o->diffopts.flags |= GIT_DIFF_FORCE_TEXT; else if (!strcmp(a, "--ignore-space-at-eol")) o->diffopts.flags |= GIT_DIFF_IGNORE_WHITESPACE_EOL; else if (!strcmp(a, "-b") || !strcmp(a, "--ignore-space-change")) o->diffopts.flags |= GIT_DIFF_IGNORE_WHITESPACE_CHANGE; else if (!strcmp(a, "-w") || !strcmp(a, "--ignore-all-space")) o->diffopts.flags |= GIT_DIFF_IGNORE_WHITESPACE; else if (!strcmp(a, "--ignored")) o->diffopts.flags |= GIT_DIFF_INCLUDE_IGNORED; else if (!strcmp(a, "--untracked")) o->diffopts.flags |= GIT_DIFF_INCLUDE_UNTRACKED; else if (!strcmp(a, "--patience")) o->diffopts.flags |= GIT_DIFF_PATIENCE; else if (!strcmp(a, "--minimal")) o->diffopts.flags |= GIT_DIFF_MINIMAL; else if (!strcmp(a, "--stat")) o->output |= OUTPUT_STAT; else if (!strcmp(a, "--numstat")) o->output |= OUTPUT_NUMSTAT; else if (!strcmp(a, "--shortstat")) o->output |= OUTPUT_SHORTSTAT; else if (!strcmp(a, "--summary")) o->output |= OUTPUT_SUMMARY; else if (match_uint16_arg( &o->findopts.rename_threshold, &args, "-M") || match_uint16_arg( &o->findopts.rename_threshold, &args, "--find-renames")) o->findopts.flags |= GIT_DIFF_FIND_RENAMES; else if (match_uint16_arg( &o->findopts.copy_threshold, &args, "-C") || match_uint16_arg( &o->findopts.copy_threshold, &args, "--find-copies")) o->findopts.flags |= GIT_DIFF_FIND_COPIES; else if (!strcmp(a, "--find-copies-harder")) o->findopts.flags |= GIT_DIFF_FIND_COPIES_FROM_UNMODIFIED; else if (is_prefixed(a, "-B") || is_prefixed(a, "--break-rewrites")) /* TODO: parse thresholds */ o->findopts.flags |= GIT_DIFF_FIND_REWRITES; else if (!match_uint32_arg( &o->diffopts.context_lines, &args, "-U") && !match_uint32_arg( &o->diffopts.context_lines, &args, "--unified") && !match_uint32_arg( &o->diffopts.interhunk_lines, &args, "--inter-hunk-context") && !match_uint16_arg( &o->diffopts.id_abbrev, &args, "--abbrev") && !match_str_arg(&o->diffopts.old_prefix, &args, "--src-prefix") && !match_str_arg(&o->diffopts.new_prefix, &args, "--dst-prefix") && !match_str_arg(&o->dir, &args, "--git-dir")) usage("Unknown command line argument", a); } } /** Display diff output with "--stat", "--numstat", or "--shortstat" */ static void diff_print_stats(git_diff *diff, struct diff_options *o) { git_diff_stats *stats; git_buf b = GIT_BUF_INIT_CONST(NULL, 0); git_diff_stats_format_t format = 0; check_lg2( git_diff_get_stats(&stats, diff), "generating stats for diff", NULL); if (o->output & OUTPUT_STAT) format |= GIT_DIFF_STATS_FULL; if (o->output & OUTPUT_SHORTSTAT) format |= GIT_DIFF_STATS_SHORT; if (o->output & OUTPUT_NUMSTAT) format |= GIT_DIFF_STATS_NUMBER; if (o->output & OUTPUT_SUMMARY) format |= GIT_DIFF_STATS_INCLUDE_SUMMARY; check_lg2( git_diff_stats_to_buf(&b, stats, format, 80), "formatting stats", NULL); fputs(b.ptr, stdout); git_buf_dispose(&b); git_diff_stats_free(stats); }
0
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2/examples/cat-file.c
/* * libgit2 "cat-file" example - shows how to print data from the ODB * * Written by the libgit2 contributors * * To the extent possible under law, the author(s) have dedicated all copyright * and related and neighboring rights to this software to the public domain * worldwide. This software is distributed without any warranty. * * You should have received a copy of the CC0 Public Domain Dedication along * with this software. If not, see * <http://creativecommons.org/publicdomain/zero/1.0/>. */ #include "common.h" static void print_signature(const char *header, const git_signature *sig) { char sign; int offset, hours, minutes; if (!sig) return; offset = sig->when.offset; if (offset < 0) { sign = '-'; offset = -offset; } else { sign = '+'; } hours = offset / 60; minutes = offset % 60; printf("%s %s <%s> %ld %c%02d%02d\n", header, sig->name, sig->email, (long)sig->when.time, sign, hours, minutes); } /** Printing out a blob is simple, get the contents and print */ static void show_blob(const git_blob *blob) { /* ? Does this need crlf filtering? */ fwrite(git_blob_rawcontent(blob), (size_t)git_blob_rawsize(blob), 1, stdout); } /** Show each entry with its type, id and attributes */ static void show_tree(const git_tree *tree) { size_t i, max_i = (int)git_tree_entrycount(tree); char oidstr[GIT_OID_HEXSZ + 1]; const git_tree_entry *te; for (i = 0; i < max_i; ++i) { te = git_tree_entry_byindex(tree, i); git_oid_tostr(oidstr, sizeof(oidstr), git_tree_entry_id(te)); printf("%06o %s %s\t%s\n", git_tree_entry_filemode(te), git_object_type2string(git_tree_entry_type(te)), oidstr, git_tree_entry_name(te)); } } /** * Commits and tags have a few interesting fields in their header. */ static void show_commit(const git_commit *commit) { unsigned int i, max_i; char oidstr[GIT_OID_HEXSZ + 1]; git_oid_tostr(oidstr, sizeof(oidstr), git_commit_tree_id(commit)); printf("tree %s\n", oidstr); max_i = (unsigned int)git_commit_parentcount(commit); for (i = 0; i < max_i; ++i) { git_oid_tostr(oidstr, sizeof(oidstr), git_commit_parent_id(commit, i)); printf("parent %s\n", oidstr); } print_signature("author", git_commit_author(commit)); print_signature("committer", git_commit_committer(commit)); if (git_commit_message(commit)) printf("\n%s\n", git_commit_message(commit)); } static void show_tag(const git_tag *tag) { char oidstr[GIT_OID_HEXSZ + 1]; git_oid_tostr(oidstr, sizeof(oidstr), git_tag_target_id(tag));; printf("object %s\n", oidstr); printf("type %s\n", git_object_type2string(git_tag_target_type(tag))); printf("tag %s\n", git_tag_name(tag)); print_signature("tagger", git_tag_tagger(tag)); if (git_tag_message(tag)) printf("\n%s\n", git_tag_message(tag)); } typedef enum { SHOW_TYPE = 1, SHOW_SIZE = 2, SHOW_NONE = 3, SHOW_PRETTY = 4 } catfile_mode; /* Forward declarations for option-parsing helper */ struct catfile_options { const char *dir; const char *rev; catfile_mode action; int verbose; }; static void parse_opts(struct catfile_options *o, int argc, char *argv[]); /** Entry point for this command */ int lg2_cat_file(git_repository *repo, int argc, char *argv[]) { struct catfile_options o = { ".", NULL, 0, 0 }; git_object *obj = NULL; char oidstr[GIT_OID_HEXSZ + 1]; parse_opts(&o, argc, argv); check_lg2(git_revparse_single(&obj, repo, o.rev), "Could not resolve", o.rev); if (o.verbose) { char oidstr[GIT_OID_HEXSZ + 1]; git_oid_tostr(oidstr, sizeof(oidstr), git_object_id(obj)); printf("%s %s\n--\n", git_object_type2string(git_object_type(obj)), oidstr); } switch (o.action) { case SHOW_TYPE: printf("%s\n", git_object_type2string(git_object_type(obj))); break; case SHOW_SIZE: { git_odb *odb; git_odb_object *odbobj; check_lg2(git_repository_odb(&odb, repo), "Could not open ODB", NULL); check_lg2(git_odb_read(&odbobj, odb, git_object_id(obj)), "Could not find obj", NULL); printf("%ld\n", (long)git_odb_object_size(odbobj)); git_odb_object_free(odbobj); git_odb_free(odb); } break; case SHOW_NONE: /* just want return result */ break; case SHOW_PRETTY: switch (git_object_type(obj)) { case GIT_OBJECT_BLOB: show_blob((const git_blob *)obj); break; case GIT_OBJECT_COMMIT: show_commit((const git_commit *)obj); break; case GIT_OBJECT_TREE: show_tree((const git_tree *)obj); break; case GIT_OBJECT_TAG: show_tag((const git_tag *)obj); break; default: printf("unknown %s\n", oidstr); break; } break; } git_object_free(obj); return 0; } /** Print out usage information */ static void usage(const char *message, const char *arg) { if (message && arg) fprintf(stderr, "%s: %s\n", message, arg); else if (message) fprintf(stderr, "%s\n", message); fprintf(stderr, "usage: cat-file (-t | -s | -e | -p) [-v] [-q] " "[-h|--help] [--git-dir=<dir>] <object>\n"); exit(1); } /** Parse the command-line options taken from git */ static void parse_opts(struct catfile_options *o, int argc, char *argv[]) { struct args_info args = ARGS_INFO_INIT; for (args.pos = 1; args.pos < argc; ++args.pos) { char *a = argv[args.pos]; if (a[0] != '-') { if (o->rev != NULL) usage("Only one rev should be provided", NULL); else o->rev = a; } else if (!strcmp(a, "-t")) o->action = SHOW_TYPE; else if (!strcmp(a, "-s")) o->action = SHOW_SIZE; else if (!strcmp(a, "-e")) o->action = SHOW_NONE; else if (!strcmp(a, "-p")) o->action = SHOW_PRETTY; else if (!strcmp(a, "-q")) o->verbose = 0; else if (!strcmp(a, "-v")) o->verbose = 1; else if (!strcmp(a, "--help") || !strcmp(a, "-h")) usage(NULL, NULL); else if (!match_str_arg(&o->dir, &args, "--git-dir")) usage("Unknown option", a); } if (!o->action || !o->rev) usage(NULL, NULL); }
0
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2/examples/show-index.c
/* * libgit2 "showindex" example - shows how to extract data from the index * * Written by the libgit2 contributors * * To the extent possible under law, the author(s) have dedicated all copyright * and related and neighboring rights to this software to the public domain * worldwide. This software is distributed without any warranty. * * You should have received a copy of the CC0 Public Domain Dedication along * with this software. If not, see * <http://creativecommons.org/publicdomain/zero/1.0/>. */ #include "common.h" int lg2_show_index(git_repository *repo, int argc, char **argv) { git_index *index; size_t i, ecount; char *dir = "."; size_t dirlen; char out[GIT_OID_HEXSZ+1]; out[GIT_OID_HEXSZ] = '\0'; if (argc > 2) fatal("usage: showindex [<repo-dir>]", NULL); if (argc > 1) dir = argv[1]; dirlen = strlen(dir); if (dirlen > 5 && strcmp(dir + dirlen - 5, "index") == 0) { check_lg2(git_index_open(&index, dir), "could not open index", dir); } else { check_lg2(git_repository_open_ext(&repo, dir, 0, NULL), "could not open repository", dir); check_lg2(git_repository_index(&index, repo), "could not open repository index", NULL); git_repository_free(repo); } git_index_read(index, 0); ecount = git_index_entrycount(index); if (!ecount) printf("Empty index\n"); for (i = 0; i < ecount; ++i) { const git_index_entry *e = git_index_get_byindex(index, i); git_oid_fmt(out, &e->id); printf("File Path: %s\n", e->path); printf(" Stage: %d\n", git_index_entry_stage(e)); printf(" Blob SHA: %s\n", out); printf("File Mode: %07o\n", e->mode); printf("File Size: %d bytes\n", (int)e->file_size); printf("Dev/Inode: %d/%d\n", (int)e->dev, (int)e->ino); printf(" UID/GID: %d/%d\n", (int)e->uid, (int)e->gid); printf(" ctime: %d\n", (int)e->ctime.seconds); printf(" mtime: %d\n", (int)e->mtime.seconds); printf("\n"); } git_index_free(index); 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/examples/lg2.c
#include "common.h" /* This part is not strictly libgit2-dependent, but you can use this * as a starting point for a git-like tool */ typedef int (*git_command_fn)(git_repository *, int , char **); struct { char *name; git_command_fn fn; char requires_repo; } commands[] = { { "add", lg2_add, 1 }, { "blame", lg2_blame, 1 }, { "cat-file", lg2_cat_file, 1 }, { "checkout", lg2_checkout, 1 }, { "clone", lg2_clone, 0 }, { "commit", lg2_commit, 1 }, { "config", lg2_config, 1 }, { "describe", lg2_describe, 1 }, { "diff", lg2_diff, 1 }, { "fetch", lg2_fetch, 1 }, { "for-each-ref", lg2_for_each_ref, 1 }, { "general", lg2_general, 0 }, { "index-pack", lg2_index_pack, 1 }, { "init", lg2_init, 0 }, { "log", lg2_log, 1 }, { "ls-files", lg2_ls_files, 1 }, { "ls-remote", lg2_ls_remote, 1 }, { "merge", lg2_merge, 1 }, { "push", lg2_push, 1 }, { "remote", lg2_remote, 1 }, { "rev-list", lg2_rev_list, 1 }, { "rev-parse", lg2_rev_parse, 1 }, { "show-index", lg2_show_index, 0 }, { "stash", lg2_stash, 1 }, { "status", lg2_status, 1 }, { "tag", lg2_tag, 1 }, }; static int run_command(git_command_fn fn, git_repository *repo, struct args_info args) { int error; /* Run the command. If something goes wrong, print the error message to stderr */ error = fn(repo, args.argc - args.pos, &args.argv[args.pos]); if (error < 0) { if (git_error_last() == NULL) fprintf(stderr, "Error without message"); else fprintf(stderr, "Bad news:\n %s\n", git_error_last()->message); } return !!error; } static int usage(const char *prog) { size_t i; fprintf(stderr, "usage: %s <cmd>...\n\nAvailable commands:\n\n", prog); for (i = 0; i < ARRAY_SIZE(commands); i++) fprintf(stderr, "\t%s\n", commands[i].name); exit(EXIT_FAILURE); } int main(int argc, char **argv) { struct args_info args = ARGS_INFO_INIT; git_repository *repo = NULL; const char *git_dir = NULL; int return_code = 1; size_t i; if (argc < 2) usage(argv[0]); git_libgit2_init(); for (args.pos = 1; args.pos < args.argc; ++args.pos) { char *a = args.argv[args.pos]; if (a[0] != '-') { /* non-arg */ break; } else if (optional_str_arg(&git_dir, &args, "--git-dir", ".git")) { continue; } else if (match_arg_separator(&args)) { break; } } if (args.pos == args.argc) usage(argv[0]); if (!git_dir) git_dir = "."; for (i = 0; i < ARRAY_SIZE(commands); ++i) { if (strcmp(args.argv[args.pos], commands[i].name)) continue; /* * Before running the actual command, create an instance * of the local repository and pass it to the function. * */ if (commands[i].requires_repo) { check_lg2(git_repository_open_ext(&repo, git_dir, 0, NULL), "Unable to open repository '%s'", git_dir); } return_code = run_command(commands[i].fn, repo, args); goto shutdown; } fprintf(stderr, "Command not found: %s\n", argv[1]); shutdown: git_repository_free(repo); git_libgit2_shutdown(); return return_code; }
0
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2/examples/args.h
#ifndef INCLUDE_examples_args_h__ #define INCLUDE_examples_args_h__ /** * Argument-processing helper structure */ struct args_info { int argc; char **argv; int pos; int opts_done : 1; /**< Did we see a -- separator */ }; #define ARGS_INFO_INIT { argc, argv, 0, 0 } #define ARGS_CURRENT(args) args->argv[args->pos] /** * Check if a string has the given prefix. Returns 0 if not prefixed * or the length of the prefix if it is. */ extern size_t is_prefixed(const char *str, const char *pfx); /** * Match an integer string, returning 1 if matched, 0 if not. */ extern int is_integer(int *out, const char *str, int allow_negative); /** * Check current `args` entry against `opt` string. If it matches * exactly, take the next arg as a string; if it matches as a prefix with * an equal sign, take the remainder as a string; if value not supplied, * default value `def` will be given. otherwise return 0. */ extern int optional_str_arg( const char **out, struct args_info *args, const char *opt, const char *def); /** * Check current `args` entry against `opt` string. If it matches * exactly, take the next arg as a string; if it matches as a prefix with * an equal sign, take the remainder as a string; otherwise return 0. */ extern int match_str_arg( const char **out, struct args_info *args, const char *opt); /** * Check current `args` entry against `opt` string parsing as uint16. If * `opt` matches exactly, take the next arg as a uint16_t value; if `opt` * is a prefix (equal sign optional), take the remainder of the arg as a * uint16_t value; otherwise return 0. */ extern int match_uint16_arg( uint16_t *out, struct args_info *args, const char *opt); /** * Check current `args` entry against `opt` string parsing as uint32. If * `opt` matches exactly, take the next arg as a uint16_t value; if `opt` * is a prefix (equal sign optional), take the remainder of the arg as a * uint32_t value; otherwise return 0. */ extern int match_uint32_arg( uint32_t *out, struct args_info *args, const char *opt); /** * Check current `args` entry against `opt` string parsing as int. If * `opt` matches exactly, take the next arg as an int value; if it matches * as a prefix (equal sign optional), take the remainder of the arg as a * int value; otherwise return 0. */ extern int match_int_arg( int *out, struct args_info *args, const char *opt, int allow_negative); /** * Check current `args` entry against a "bool" `opt` (ie. --[no-]progress). * If `opt` matches positively, out will be set to 1, or if `opt` matches * negatively, out will be set to 0, and in both cases 1 will be returned. * If neither the positive or the negative form of opt matched, out will be -1, * and 0 will be returned. */ extern int match_bool_arg(int *out, struct args_info *args, const char *opt); /** * Check if we're processing past the single -- separator */ extern int match_arg_separator(struct args_info *args); /** * Consume all remaining arguments in a git_strarray */ extern void strarray_from_args(git_strarray *array, struct args_info *args); #endif
0
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2/examples/common.h
/* * Utilities library for libgit2 examples * * Written by the libgit2 contributors * * To the extent possible under law, the author(s) have dedicated all copyright * and related and neighboring rights to this software to the public domain * worldwide. This software is distributed without any warranty. * * You should have received a copy of the CC0 Public Domain Dedication along * with this software. If not, see * <http://creativecommons.org/publicdomain/zero/1.0/>. */ #ifndef INCLUDE_examples_common_h__ #define INCLUDE_examples_common_h__ #include <assert.h> #include <sys/types.h> #include <sys/stat.h> #include <stdio.h> #include <string.h> #include <stdlib.h> #include <git2.h> #include <fcntl.h> #ifdef _WIN32 # include <io.h> # include <Windows.h> # define open _open # define read _read # define close _close # define ssize_t int # define sleep(a) Sleep(a * 1000) #else # include <unistd.h> #endif #ifndef PRIuZ /* Define the printf format specifier to use for size_t output */ #if defined(_MSC_VER) || defined(__MINGW32__) # define PRIuZ "Iu" #else # define PRIuZ "zu" #endif #endif #ifdef _MSC_VER #define snprintf sprintf_s #define strcasecmp strcmpi #endif #define ARRAY_SIZE(x) (sizeof(x)/sizeof(*x)) #define UNUSED(x) (void)(x) #include "args.h" extern int lg2_add(git_repository *repo, int argc, char **argv); extern int lg2_blame(git_repository *repo, int argc, char **argv); extern int lg2_cat_file(git_repository *repo, int argc, char **argv); extern int lg2_checkout(git_repository *repo, int argc, char **argv); extern int lg2_clone(git_repository *repo, int argc, char **argv); extern int lg2_commit(git_repository *repo, int argc, char **argv); extern int lg2_config(git_repository *repo, int argc, char **argv); extern int lg2_describe(git_repository *repo, int argc, char **argv); extern int lg2_diff(git_repository *repo, int argc, char **argv); extern int lg2_fetch(git_repository *repo, int argc, char **argv); extern int lg2_for_each_ref(git_repository *repo, int argc, char **argv); extern int lg2_general(git_repository *repo, int argc, char **argv); extern int lg2_index_pack(git_repository *repo, int argc, char **argv); extern int lg2_init(git_repository *repo, int argc, char **argv); extern int lg2_log(git_repository *repo, int argc, char **argv); extern int lg2_ls_files(git_repository *repo, int argc, char **argv); extern int lg2_ls_remote(git_repository *repo, int argc, char **argv); extern int lg2_merge(git_repository *repo, int argc, char **argv); extern int lg2_push(git_repository *repo, int argc, char **argv); extern int lg2_remote(git_repository *repo, int argc, char **argv); extern int lg2_rev_list(git_repository *repo, int argc, char **argv); extern int lg2_rev_parse(git_repository *repo, int argc, char **argv); extern int lg2_show_index(git_repository *repo, int argc, char **argv); extern int lg2_stash(git_repository *repo, int argc, char **argv); extern int lg2_status(git_repository *repo, int argc, char **argv); extern int lg2_tag(git_repository *repo, int argc, char **argv); /** * Check libgit2 error code, printing error to stderr on failure and * exiting the program. */ extern void check_lg2(int error, const char *message, const char *extra); /** * Read a file into a buffer * * @param path The path to the file that shall be read * @return NUL-terminated buffer if the file was successfully read, NULL-pointer otherwise */ extern char *read_file(const char *path); /** * Exit the program, printing error to stderr */ extern void fatal(const char *message, const char *extra); /** * Basic output function for plain text diff output * Pass `FILE*` such as `stdout` or `stderr` as payload (or NULL == `stdout`) */ extern int diff_output( const git_diff_delta*, const git_diff_hunk*, const git_diff_line*, void*); /** * Convert a treeish argument to an actual tree; this will call check_lg2 * and exit the program if `treeish` cannot be resolved to a tree */ extern void treeish_to_tree( git_tree **out, git_repository *repo, const char *treeish); /** * A realloc that exits on failure */ extern void *xrealloc(void *oldp, size_t newsz); /** * Convert a refish to an annotated commit. */ extern int resolve_refish(git_annotated_commit **commit, git_repository *repo, const char *refish); /** * Acquire credentials via command line */ extern int cred_acquire_cb(git_credential **out, const char *url, const char *username_from_url, unsigned int allowed_types, 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/examples/CMakeLists.txt
INCLUDE_DIRECTORIES(${LIBGIT2_INCLUDES}) INCLUDE_DIRECTORIES(SYSTEM ${LIBGIT2_SYSTEM_INCLUDES}) FILE(GLOB LG2_SOURCES *.c *.h) ADD_EXECUTABLE(lg2 ${LG2_SOURCES}) SET_TARGET_PROPERTIES(lg2 PROPERTIES C_STANDARD 90) # Ensure that we do not use deprecated functions internally ADD_DEFINITIONS(-DGIT_DEPRECATE_HARD) IF(WIN32 OR ANDROID) TARGET_LINK_LIBRARIES(lg2 git2) ELSE() TARGET_LINK_LIBRARIES(lg2 git2 pthread) ENDIF()
0
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2/examples/fetch.c
#include "common.h" static int progress_cb(const char *str, int len, void *data) { (void)data; printf("remote: %.*s", len, str); fflush(stdout); /* We don't have the \n to force the flush */ return 0; } /** * This function gets called for each remote-tracking branch that gets * updated. The message we output depends on whether it's a new one or * an update. */ static int update_cb(const char *refname, const git_oid *a, const git_oid *b, void *data) { char a_str[GIT_OID_HEXSZ+1], b_str[GIT_OID_HEXSZ+1]; (void)data; git_oid_fmt(b_str, b); b_str[GIT_OID_HEXSZ] = '\0'; if (git_oid_is_zero(a)) { printf("[new] %.20s %s\n", b_str, refname); } else { git_oid_fmt(a_str, a); a_str[GIT_OID_HEXSZ] = '\0'; printf("[updated] %.10s..%.10s %s\n", a_str, b_str, refname); } return 0; } /** * This gets called during the download and indexing. Here we show * processed and total objects in the pack and the amount of received * data. Most frontends will probably want to show a percentage and * the download rate. */ static int transfer_progress_cb(const git_indexer_progress *stats, void *payload) { (void)payload; if (stats->received_objects == stats->total_objects) { printf("Resolving deltas %u/%u\r", stats->indexed_deltas, stats->total_deltas); } else if (stats->total_objects > 0) { printf("Received %u/%u objects (%u) in %" PRIuZ " bytes\r", stats->received_objects, stats->total_objects, stats->indexed_objects, stats->received_bytes); } return 0; } /** Entry point for this command */ int lg2_fetch(git_repository *repo, int argc, char **argv) { git_remote *remote = NULL; const git_indexer_progress *stats; git_fetch_options fetch_opts = GIT_FETCH_OPTIONS_INIT; if (argc < 2) { fprintf(stderr, "usage: %s fetch <repo>\n", argv[-1]); return EXIT_FAILURE; } /* Figure out whether it's a named remote or a URL */ printf("Fetching %s for repo %p\n", argv[1], repo); if (git_remote_lookup(&remote, repo, argv[1]) < 0) if (git_remote_create_anonymous(&remote, repo, argv[1]) < 0) goto on_error; /* Set up the callbacks (only update_tips for now) */ fetch_opts.callbacks.update_tips = &update_cb; fetch_opts.callbacks.sideband_progress = &progress_cb; fetch_opts.callbacks.transfer_progress = transfer_progress_cb; fetch_opts.callbacks.credentials = cred_acquire_cb; /** * Perform the fetch with the configured refspecs from the * config. Update the reflog for the updated references with * "fetch". */ if (git_remote_fetch(remote, NULL, &fetch_opts, "fetch") < 0) goto on_error; /** * If there are local objects (we got a thin pack), then tell * the user how many objects we saved from having to cross the * network. */ stats = git_remote_stats(remote); if (stats->local_objects > 0) { printf("\rReceived %u/%u objects in %" PRIuZ " bytes (used %u local objects)\n", stats->indexed_objects, stats->total_objects, stats->received_bytes, stats->local_objects); } else{ printf("\rReceived %u/%u objects in %" PRIuZ "bytes\n", stats->indexed_objects, stats->total_objects, stats->received_bytes); } git_remote_free(remote); return 0; on_error: git_remote_free(remote); 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/examples/README.md
libgit2 examples ================ These examples are a mixture of basic emulation of core Git command line functions and simple snippets demonstrating libgit2 API usage (for use with Docurium). As a whole, they are not vetted carefully for bugs, error handling, and cross-platform compatibility in the same manner as the rest of the code in libgit2, so copy with caution. That being said, you are welcome to copy code from these examples as desired when using libgit2. They have been [released to the public domain][cc0], so there are no restrictions on their use. [cc0]: COPYING For annotated HTML versions, see the "Examples" section of: http://libgit2.github.com/libgit2 such as: http://libgit2.github.com/libgit2/ex/HEAD/general.html
0
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2/examples/checkout.c
/* * libgit2 "checkout" example - shows how to perform checkouts * * Written by the libgit2 contributors * * To the extent possible under law, the author(s) have dedicated all copyright * and related and neighboring rights to this software to the public domain * worldwide. This software is distributed without any warranty. * * You should have received a copy of the CC0 Public Domain Dedication along * with this software. If not, see * <http://creativecommons.org/publicdomain/zero/1.0/>. */ #include "common.h" /* Define the printf format specifier to use for size_t output */ #if defined(_MSC_VER) || defined(__MINGW32__) # define PRIuZ "Iu" # define PRIxZ "Ix" # define PRIdZ "Id" #else # define PRIuZ "zu" # define PRIxZ "zx" # define PRIdZ "zd" #endif /** * The following example demonstrates how to do checkouts with libgit2. * * Recognized options are : * --force: force the checkout to happen. * --[no-]progress: show checkout progress, on by default. * --perf: show performance data. */ typedef struct { int force : 1; int progress : 1; int perf : 1; } checkout_options; static void print_usage(void) { fprintf(stderr, "usage: checkout [options] <branch>\n" "Options are :\n" " --git-dir: use the following git repository.\n" " --force: force the checkout.\n" " --[no-]progress: show checkout progress.\n" " --perf: show performance data.\n"); exit(1); } static void parse_options(const char **repo_path, checkout_options *opts, struct args_info *args) { if (args->argc <= 1) print_usage(); memset(opts, 0, sizeof(*opts)); /* Default values */ opts->progress = 1; for (args->pos = 1; args->pos < args->argc; ++args->pos) { const char *curr = args->argv[args->pos]; int bool_arg; if (match_arg_separator(args)) { break; } else if (!strcmp(curr, "--force")) { opts->force = 1; } else if (match_bool_arg(&bool_arg, args, "--progress")) { opts->progress = bool_arg; } else if (match_bool_arg(&bool_arg, args, "--perf")) { opts->perf = bool_arg; } else if (match_str_arg(repo_path, args, "--git-dir")) { continue; } else { break; } } } /** * This function is called to report progression, ie. it's called once with * a NULL path and the number of total steps, then for each subsequent path, * the current completed_step value. */ static void print_checkout_progress(const char *path, size_t completed_steps, size_t total_steps, void *payload) { (void)payload; if (path == NULL) { printf("checkout started: %" PRIuZ " steps\n", total_steps); } else { printf("checkout: %s %" PRIuZ "/%" PRIuZ "\n", path, completed_steps, total_steps); } } /** * This function is called when the checkout completes, and is used to report the * number of syscalls performed. */ static void print_perf_data(const git_checkout_perfdata *perfdata, void *payload) { (void)payload; printf("perf: stat: %" PRIuZ " mkdir: %" PRIuZ " chmod: %" PRIuZ "\n", perfdata->stat_calls, perfdata->mkdir_calls, perfdata->chmod_calls); } /** * This is the main "checkout <branch>" function, responsible for performing * a branch-based checkout. */ static int perform_checkout_ref(git_repository *repo, git_annotated_commit *target, const char *target_ref, checkout_options *opts) { git_checkout_options checkout_opts = GIT_CHECKOUT_OPTIONS_INIT; git_reference *ref = NULL, *branch = NULL; git_commit *target_commit = NULL; int err; /** Setup our checkout options from the parsed options */ checkout_opts.checkout_strategy = GIT_CHECKOUT_SAFE; if (opts->force) checkout_opts.checkout_strategy = GIT_CHECKOUT_FORCE; if (opts->progress) checkout_opts.progress_cb = print_checkout_progress; if (opts->perf) checkout_opts.perfdata_cb = print_perf_data; /** Grab the commit we're interested to move to */ err = git_commit_lookup(&target_commit, repo, git_annotated_commit_id(target)); if (err != 0) { fprintf(stderr, "failed to lookup commit: %s\n", git_error_last()->message); goto cleanup; } /** * Perform the checkout so the workdir corresponds to what target_commit * contains. * * Note that it's okay to pass a git_commit here, because it will be * peeled to a tree. */ err = git_checkout_tree(repo, (const git_object *)target_commit, &checkout_opts); if (err != 0) { fprintf(stderr, "failed to checkout tree: %s\n", git_error_last()->message); goto cleanup; } /** * Now that the checkout has completed, we have to update HEAD. * * Depending on the "origin" of target (ie. it's an OID or a branch name), * we might need to detach HEAD. */ if (git_annotated_commit_ref(target)) { const char *target_head; if ((err = git_reference_lookup(&ref, repo, git_annotated_commit_ref(target))) < 0) goto error; if (git_reference_is_remote(ref)) { if ((err = git_branch_create_from_annotated(&branch, repo, target_ref, target, 0)) < 0) goto error; target_head = git_reference_name(branch); } else { target_head = git_annotated_commit_ref(target); } err = git_repository_set_head(repo, target_head); } else { err = git_repository_set_head_detached_from_annotated(repo, target); } error: if (err != 0) { fprintf(stderr, "failed to update HEAD reference: %s\n", git_error_last()->message); goto cleanup; } cleanup: git_commit_free(target_commit); git_reference_free(branch); git_reference_free(ref); return err; } /** * This corresponds to `git switch --guess`: if a given ref does * not exist, git will by default try to guess the reference by * seeing whether any remote has a branch called <ref>. If there * is a single remote only that has it, then it is assumed to be * the desired reference and a local branch is created for it. * * The following is a simplified implementation. It will not try * to check whether the ref is unique across all remotes. */ static int guess_refish(git_annotated_commit **out, git_repository *repo, const char *ref) { git_strarray remotes = { NULL, 0 }; git_reference *remote_ref = NULL; int error; size_t i; if ((error = git_remote_list(&remotes, repo)) < 0) goto out; for (i = 0; i < remotes.count; i++) { char *refname = NULL; size_t reflen; reflen = snprintf(refname, 0, "refs/remotes/%s/%s", remotes.strings[i], ref); if ((refname = malloc(reflen + 1)) == NULL) { error = -1; goto next; } snprintf(refname, reflen + 1, "refs/remotes/%s/%s", remotes.strings[i], ref); if ((error = git_reference_lookup(&remote_ref, repo, refname)) < 0) goto next; break; next: free(refname); if (error < 0 && error != GIT_ENOTFOUND) break; } if (!remote_ref) { error = GIT_ENOTFOUND; goto out; } if ((error = git_annotated_commit_from_ref(out, repo, remote_ref)) < 0) goto out; out: git_reference_free(remote_ref); git_strarray_dispose(&remotes); return error; } /** That example's entry point */ int lg2_checkout(git_repository *repo, int argc, char **argv) { struct args_info args = ARGS_INFO_INIT; checkout_options opts; git_repository_state_t state; git_annotated_commit *checkout_target = NULL; int err = 0; const char *path = "."; /** Parse our command line options */ parse_options(&path, &opts, &args); /** Make sure we're not about to checkout while something else is going on */ state = git_repository_state(repo); if (state != GIT_REPOSITORY_STATE_NONE) { fprintf(stderr, "repository is in unexpected state %d\n", state); goto cleanup; } if (match_arg_separator(&args)) { /** * Try to checkout the given path */ fprintf(stderr, "unhandled path-based checkout\n"); err = 1; goto cleanup; } else { /** * Try to resolve a "refish" argument to a target libgit2 can use */ if ((err = resolve_refish(&checkout_target, repo, args.argv[args.pos])) < 0 && (err = guess_refish(&checkout_target, repo, args.argv[args.pos])) < 0) { fprintf(stderr, "failed to resolve %s: %s\n", args.argv[args.pos], git_error_last()->message); goto cleanup; } err = perform_checkout_ref(repo, checkout_target, args.argv[args.pos], &opts); } cleanup: git_annotated_commit_free(checkout_target); return err; }
0
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2/examples/commit.c
/* * libgit2 "commit" example - shows how to create a git commit * * Written by the libgit2 contributors * * To the extent possible under law, the author(s) have dedicated all copyright * and related and neighboring rights to this software to the public domain * worldwide. This software is distributed without any warranty. * * You should have received a copy of the CC0 Public Domain Dedication along * with this software. If not, see * <http://creativecommons.org/publicdomain/zero/1.0/>. */ #include "common.h" /** * This example demonstrates the libgit2 commit APIs to roughly * simulate `git commit` with the commit message argument. * * This does not have: * * - Robust error handling * - Most of the `git commit` options * * This does have: * * - Example of performing a git commit with a comment * */ int lg2_commit(git_repository *repo, int argc, char **argv) { const char *opt = argv[1]; const char *comment = argv[2]; int error; git_oid commit_oid,tree_oid; git_tree *tree; git_index *index; git_object *parent = NULL; git_reference *ref = NULL; git_signature *signature; /* Validate args */ if (argc < 3 || strcmp(opt, "-m") != 0) { printf ("USAGE: %s -m <comment>\n", argv[0]); return -1; } error = git_revparse_ext(&parent, &ref, repo, "HEAD"); if (error == GIT_ENOTFOUND) { printf("HEAD not found. Creating first commit\n"); error = 0; } else if (error != 0) { const git_error *err = git_error_last(); if (err) printf("ERROR %d: %s\n", err->klass, err->message); else printf("ERROR %d: no detailed info\n", error); } check_lg2(git_repository_index(&index, repo), "Could not open repository index", NULL); check_lg2(git_index_write_tree(&tree_oid, index), "Could not write tree", NULL);; check_lg2(git_index_write(index), "Could not write index", NULL);; check_lg2(git_tree_lookup(&tree, repo, &tree_oid), "Error looking up tree", NULL); check_lg2(git_signature_default(&signature, repo), "Error creating signature", NULL); check_lg2(git_commit_create_v( &commit_oid, repo, "HEAD", signature, signature, NULL, comment, tree, parent ? 1 : 0, parent), "Error creating commit", NULL); git_index_free(index); git_signature_free(signature); git_tree_free(tree); 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/examples/push.c
/* * libgit2 "push" example - shows how to push to remote * * Written by the libgit2 contributors * * To the extent possible under law, the author(s) have dedicated all copyright * and related and neighboring rights to this software to the public domain * worldwide. This software is distributed without any warranty. * * You should have received a copy of the CC0 Public Domain Dedication along * with this software. If not, see * <http://creativecommons.org/publicdomain/zero/1.0/>. */ #include "common.h" /** * This example demonstrates the libgit2 push API to roughly * simulate `git push`. * * This does not have: * * - Robust error handling * - Any of the `git push` options * * This does have: * * - Example of push to origin/master * */ /** Entry point for this command */ int lg2_push(git_repository *repo, int argc, char **argv) { git_push_options options; git_remote* remote = NULL; char *refspec = "refs/heads/master"; const git_strarray refspecs = { &refspec, 1 }; /* Validate args */ if (argc > 1) { printf ("USAGE: %s\n\nsorry, no arguments supported yet\n", argv[0]); return -1; } check_lg2(git_remote_lookup(&remote, repo, "origin" ), "Unable to lookup remote", NULL); check_lg2(git_push_options_init(&options, GIT_PUSH_OPTIONS_VERSION ), "Error initializing push", NULL); check_lg2(git_remote_push(remote, &refspecs, &options), "Error pushing", NULL); printf("pushed\n"); 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/examples/status.c
/* * libgit2 "status" example - shows how to use the status APIs * * Written by the libgit2 contributors * * To the extent possible under law, the author(s) have dedicated all copyright * and related and neighboring rights to this software to the public domain * worldwide. This software is distributed without any warranty. * * You should have received a copy of the CC0 Public Domain Dedication along * with this software. If not, see * <http://creativecommons.org/publicdomain/zero/1.0/>. */ #include "common.h" /** * This example demonstrates the use of the libgit2 status APIs, * particularly the `git_status_list` object, to roughly simulate the * output of running `git status`. It serves as a simple example of * using those APIs to get basic status information. * * This does not have: * * - Robust error handling * - Colorized or paginated output formatting * * This does have: * * - Examples of translating command line arguments to the status * options settings to mimic `git status` results. * - A sample status formatter that matches the default "long" format * from `git status` * - A sample status formatter that matches the "short" format */ enum { FORMAT_DEFAULT = 0, FORMAT_LONG = 1, FORMAT_SHORT = 2, FORMAT_PORCELAIN = 3, }; #define MAX_PATHSPEC 8 struct status_opts { git_status_options statusopt; char *repodir; char *pathspec[MAX_PATHSPEC]; int npaths; int format; int zterm; int showbranch; int showsubmod; int repeat; }; static void parse_opts(struct status_opts *o, int argc, char *argv[]); static void show_branch(git_repository *repo, int format); static void print_long(git_status_list *status); static void print_short(git_repository *repo, git_status_list *status); static int print_submod(git_submodule *sm, const char *name, void *payload); int lg2_status(git_repository *repo, int argc, char *argv[]) { git_status_list *status; struct status_opts o = { GIT_STATUS_OPTIONS_INIT, "." }; o.statusopt.show = GIT_STATUS_SHOW_INDEX_AND_WORKDIR; o.statusopt.flags = GIT_STATUS_OPT_INCLUDE_UNTRACKED | GIT_STATUS_OPT_RENAMES_HEAD_TO_INDEX | GIT_STATUS_OPT_SORT_CASE_SENSITIVELY; parse_opts(&o, argc, argv); if (git_repository_is_bare(repo)) fatal("Cannot report status on bare repository", git_repository_path(repo)); show_status: if (o.repeat) printf("\033[H\033[2J"); /** * Run status on the repository * * We use `git_status_list_new()` to generate a list of status * information which lets us iterate over it at our * convenience and extract the data we want to show out of * each entry. * * You can use `git_status_foreach()` or * `git_status_foreach_ext()` if you'd prefer to execute a * callback for each entry. The latter gives you more control * about what results are presented. */ check_lg2(git_status_list_new(&status, repo, &o.statusopt), "Could not get status", NULL); if (o.showbranch) show_branch(repo, o.format); if (o.showsubmod) { int submod_count = 0; check_lg2(git_submodule_foreach(repo, print_submod, &submod_count), "Cannot iterate submodules", o.repodir); } if (o.format == FORMAT_LONG) print_long(status); else print_short(repo, status); git_status_list_free(status); if (o.repeat) { sleep(o.repeat); goto show_status; } return 0; } /** * If the user asked for the branch, let's show the short name of the * branch. */ static void show_branch(git_repository *repo, int format) { int error = 0; const char *branch = NULL; git_reference *head = NULL; error = git_repository_head(&head, repo); if (error == GIT_EUNBORNBRANCH || error == GIT_ENOTFOUND) branch = NULL; else if (!error) { branch = git_reference_shorthand(head); } else check_lg2(error, "failed to get current branch", NULL); if (format == FORMAT_LONG) printf("# On branch %s\n", branch ? branch : "Not currently on any branch."); else printf("## %s\n", branch ? branch : "HEAD (no branch)"); git_reference_free(head); } /** * This function print out an output similar to git's status command * in long form, including the command-line hints. */ static void print_long(git_status_list *status) { size_t i, maxi = git_status_list_entrycount(status); const git_status_entry *s; int header = 0, changes_in_index = 0; int changed_in_workdir = 0, rm_in_workdir = 0; const char *old_path, *new_path; /** Print index changes. */ for (i = 0; i < maxi; ++i) { char *istatus = NULL; s = git_status_byindex(status, i); if (s->status == GIT_STATUS_CURRENT) continue; if (s->status & GIT_STATUS_WT_DELETED) rm_in_workdir = 1; if (s->status & GIT_STATUS_INDEX_NEW) istatus = "new file: "; if (s->status & GIT_STATUS_INDEX_MODIFIED) istatus = "modified: "; if (s->status & GIT_STATUS_INDEX_DELETED) istatus = "deleted: "; if (s->status & GIT_STATUS_INDEX_RENAMED) istatus = "renamed: "; if (s->status & GIT_STATUS_INDEX_TYPECHANGE) istatus = "typechange:"; if (istatus == NULL) continue; if (!header) { printf("# Changes to be committed:\n"); printf("# (use \"git reset HEAD <file>...\" to unstage)\n"); printf("#\n"); header = 1; } old_path = s->head_to_index->old_file.path; new_path = s->head_to_index->new_file.path; if (old_path && new_path && strcmp(old_path, new_path)) printf("#\t%s %s -> %s\n", istatus, old_path, new_path); else printf("#\t%s %s\n", istatus, old_path ? old_path : new_path); } if (header) { changes_in_index = 1; printf("#\n"); } header = 0; /** Print workdir changes to tracked files. */ for (i = 0; i < maxi; ++i) { char *wstatus = NULL; s = git_status_byindex(status, i); /** * With `GIT_STATUS_OPT_INCLUDE_UNMODIFIED` (not used in this example) * `index_to_workdir` may not be `NULL` even if there are * no differences, in which case it will be a `GIT_DELTA_UNMODIFIED`. */ if (s->status == GIT_STATUS_CURRENT || s->index_to_workdir == NULL) continue; /** Print out the output since we know the file has some changes */ if (s->status & GIT_STATUS_WT_MODIFIED) wstatus = "modified: "; if (s->status & GIT_STATUS_WT_DELETED) wstatus = "deleted: "; if (s->status & GIT_STATUS_WT_RENAMED) wstatus = "renamed: "; if (s->status & GIT_STATUS_WT_TYPECHANGE) wstatus = "typechange:"; if (wstatus == NULL) continue; if (!header) { printf("# Changes not staged for commit:\n"); printf("# (use \"git add%s <file>...\" to update what will be committed)\n", rm_in_workdir ? "/rm" : ""); printf("# (use \"git checkout -- <file>...\" to discard changes in working directory)\n"); printf("#\n"); header = 1; } old_path = s->index_to_workdir->old_file.path; new_path = s->index_to_workdir->new_file.path; if (old_path && new_path && strcmp(old_path, new_path)) printf("#\t%s %s -> %s\n", wstatus, old_path, new_path); else printf("#\t%s %s\n", wstatus, old_path ? old_path : new_path); } if (header) { changed_in_workdir = 1; printf("#\n"); } /** Print untracked files. */ header = 0; for (i = 0; i < maxi; ++i) { s = git_status_byindex(status, i); if (s->status == GIT_STATUS_WT_NEW) { if (!header) { printf("# Untracked files:\n"); printf("# (use \"git add <file>...\" to include in what will be committed)\n"); printf("#\n"); header = 1; } printf("#\t%s\n", s->index_to_workdir->old_file.path); } } header = 0; /** Print ignored files. */ for (i = 0; i < maxi; ++i) { s = git_status_byindex(status, i); if (s->status == GIT_STATUS_IGNORED) { if (!header) { printf("# Ignored files:\n"); printf("# (use \"git add -f <file>...\" to include in what will be committed)\n"); printf("#\n"); header = 1; } printf("#\t%s\n", s->index_to_workdir->old_file.path); } } if (!changes_in_index && changed_in_workdir) printf("no changes added to commit (use \"git add\" and/or \"git commit -a\")\n"); } /** * This version of the output prefixes each path with two status * columns and shows submodule status information. */ static void print_short(git_repository *repo, git_status_list *status) { size_t i, maxi = git_status_list_entrycount(status); const git_status_entry *s; char istatus, wstatus; const char *extra, *a, *b, *c; for (i = 0; i < maxi; ++i) { s = git_status_byindex(status, i); if (s->status == GIT_STATUS_CURRENT) continue; a = b = c = NULL; istatus = wstatus = ' '; extra = ""; if (s->status & GIT_STATUS_INDEX_NEW) istatus = 'A'; if (s->status & GIT_STATUS_INDEX_MODIFIED) istatus = 'M'; if (s->status & GIT_STATUS_INDEX_DELETED) istatus = 'D'; if (s->status & GIT_STATUS_INDEX_RENAMED) istatus = 'R'; if (s->status & GIT_STATUS_INDEX_TYPECHANGE) istatus = 'T'; if (s->status & GIT_STATUS_WT_NEW) { if (istatus == ' ') istatus = '?'; wstatus = '?'; } if (s->status & GIT_STATUS_WT_MODIFIED) wstatus = 'M'; if (s->status & GIT_STATUS_WT_DELETED) wstatus = 'D'; if (s->status & GIT_STATUS_WT_RENAMED) wstatus = 'R'; if (s->status & GIT_STATUS_WT_TYPECHANGE) wstatus = 'T'; if (s->status & GIT_STATUS_IGNORED) { istatus = '!'; wstatus = '!'; } if (istatus == '?' && wstatus == '?') continue; /** * A commit in a tree is how submodules are stored, so * let's go take a look at its status. */ if (s->index_to_workdir && s->index_to_workdir->new_file.mode == GIT_FILEMODE_COMMIT) { unsigned int smstatus = 0; if (!git_submodule_status(&smstatus, repo, s->index_to_workdir->new_file.path, GIT_SUBMODULE_IGNORE_UNSPECIFIED)) { if (smstatus & GIT_SUBMODULE_STATUS_WD_MODIFIED) extra = " (new commits)"; else if (smstatus & GIT_SUBMODULE_STATUS_WD_INDEX_MODIFIED) extra = " (modified content)"; else if (smstatus & GIT_SUBMODULE_STATUS_WD_WD_MODIFIED) extra = " (modified content)"; else if (smstatus & GIT_SUBMODULE_STATUS_WD_UNTRACKED) extra = " (untracked content)"; } } /** * Now that we have all the information, format the output. */ if (s->head_to_index) { a = s->head_to_index->old_file.path; b = s->head_to_index->new_file.path; } if (s->index_to_workdir) { if (!a) a = s->index_to_workdir->old_file.path; if (!b) b = s->index_to_workdir->old_file.path; c = s->index_to_workdir->new_file.path; } if (istatus == 'R') { if (wstatus == 'R') printf("%c%c %s %s %s%s\n", istatus, wstatus, a, b, c, extra); else printf("%c%c %s %s%s\n", istatus, wstatus, a, b, extra); } else { if (wstatus == 'R') printf("%c%c %s %s%s\n", istatus, wstatus, a, c, extra); else printf("%c%c %s%s\n", istatus, wstatus, a, extra); } } for (i = 0; i < maxi; ++i) { s = git_status_byindex(status, i); if (s->status == GIT_STATUS_WT_NEW) printf("?? %s\n", s->index_to_workdir->old_file.path); } } static int print_submod(git_submodule *sm, const char *name, void *payload) { int *count = payload; (void)name; if (*count == 0) printf("# Submodules\n"); (*count)++; printf("# - submodule '%s' at %s\n", git_submodule_name(sm), git_submodule_path(sm)); return 0; } /** * Parse options that git's status command supports. */ static void parse_opts(struct status_opts *o, int argc, char *argv[]) { struct args_info args = ARGS_INFO_INIT; for (args.pos = 1; args.pos < argc; ++args.pos) { char *a = argv[args.pos]; if (a[0] != '-') { if (o->npaths < MAX_PATHSPEC) o->pathspec[o->npaths++] = a; else fatal("Example only supports a limited pathspec", NULL); } else if (!strcmp(a, "-s") || !strcmp(a, "--short")) o->format = FORMAT_SHORT; else if (!strcmp(a, "--long")) o->format = FORMAT_LONG; else if (!strcmp(a, "--porcelain")) o->format = FORMAT_PORCELAIN; else if (!strcmp(a, "-b") || !strcmp(a, "--branch")) o->showbranch = 1; else if (!strcmp(a, "-z")) { o->zterm = 1; if (o->format == FORMAT_DEFAULT) o->format = FORMAT_PORCELAIN; } else if (!strcmp(a, "--ignored")) o->statusopt.flags |= GIT_STATUS_OPT_INCLUDE_IGNORED; else if (!strcmp(a, "-uno") || !strcmp(a, "--untracked-files=no")) o->statusopt.flags &= ~GIT_STATUS_OPT_INCLUDE_UNTRACKED; else if (!strcmp(a, "-unormal") || !strcmp(a, "--untracked-files=normal")) o->statusopt.flags |= GIT_STATUS_OPT_INCLUDE_UNTRACKED; else if (!strcmp(a, "-uall") || !strcmp(a, "--untracked-files=all")) o->statusopt.flags |= GIT_STATUS_OPT_INCLUDE_UNTRACKED | GIT_STATUS_OPT_RECURSE_UNTRACKED_DIRS; else if (!strcmp(a, "--ignore-submodules=all")) o->statusopt.flags |= GIT_STATUS_OPT_EXCLUDE_SUBMODULES; else if (!strncmp(a, "--git-dir=", strlen("--git-dir="))) o->repodir = a + strlen("--git-dir="); else if (!strcmp(a, "--repeat")) o->repeat = 10; else if (match_int_arg(&o->repeat, &args, "--repeat", 0)) /* okay */; else if (!strcmp(a, "--list-submodules")) o->showsubmod = 1; else check_lg2(-1, "Unsupported option", a); } if (o->format == FORMAT_DEFAULT) o->format = FORMAT_LONG; if (o->format == FORMAT_LONG) o->showbranch = 1; if (o->npaths > 0) { o->statusopt.pathspec.strings = o->pathspec; o->statusopt.pathspec.count = o->npaths; } }
0
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2/examples/add.c
/* * libgit2 "add" example - shows how to modify the index * * Written by the libgit2 contributors * * To the extent possible under law, the author(s) have dedicated all copyright * and related and neighboring rights to this software to the public domain * worldwide. This software is distributed without any warranty. * * You should have received a copy of the CC0 Public Domain Dedication along * with this software. If not, see * <http://creativecommons.org/publicdomain/zero/1.0/>. */ #include "common.h" /** * The following example demonstrates how to add files with libgit2. * * It will use the repository in the current working directory, and act * on files passed as its parameters. * * Recognized options are: * -v/--verbose: show the file's status after acting on it. * -n/--dry-run: do not actually change the index. * -u/--update: update the index instead of adding to it. */ enum index_mode { INDEX_NONE, INDEX_ADD, }; struct index_options { int dry_run; int verbose; git_repository *repo; enum index_mode mode; int add_update; }; /* Forward declarations for helpers */ static void parse_opts(const char **repo_path, struct index_options *opts, struct args_info *args); int print_matched_cb(const char *path, const char *matched_pathspec, void *payload); int lg2_add(git_repository *repo, int argc, char **argv) { git_index_matched_path_cb matched_cb = NULL; git_index *index; git_strarray array = {0}; struct index_options options = {0}; struct args_info args = ARGS_INFO_INIT; options.mode = INDEX_ADD; /* Parse the options & arguments. */ parse_opts(NULL, &options, &args); strarray_from_args(&array, &args); /* Grab the repository's index. */ check_lg2(git_repository_index(&index, repo), "Could not open repository index", NULL); /* Setup a callback if the requested options need it */ if (options.verbose || options.dry_run) { matched_cb = &print_matched_cb; } options.repo = repo; /* Perform the requested action with the index and files */ if (options.add_update) { git_index_update_all(index, &array, matched_cb, &options); } else { git_index_add_all(index, &array, 0, matched_cb, &options); } /* Cleanup memory */ git_index_write(index); git_index_free(index); return 0; } /* * This callback is called for each file under consideration by * git_index_(update|add)_all above. * It makes uses of the callback's ability to abort the action. */ int print_matched_cb(const char *path, const char *matched_pathspec, void *payload) { struct index_options *opts = (struct index_options *)(payload); int ret; unsigned status; (void)matched_pathspec; /* Get the file status */ if (git_status_file(&status, opts->repo, path) < 0) return -1; if ((status & GIT_STATUS_WT_MODIFIED) || (status & GIT_STATUS_WT_NEW)) { printf("add '%s'\n", path); ret = 0; } else { ret = 1; } if (opts->dry_run) ret = 1; return ret; } void init_array(git_strarray *array, int argc, char **argv) { unsigned int i; array->count = argc; array->strings = calloc(array->count, sizeof(char *)); assert(array->strings != NULL); for (i = 0; i < array->count; i++) { array->strings[i] = argv[i]; } return; } void print_usage(void) { fprintf(stderr, "usage: add [options] [--] file-spec [file-spec] [...]\n\n"); fprintf(stderr, "\t-n, --dry-run dry run\n"); fprintf(stderr, "\t-v, --verbose be verbose\n"); fprintf(stderr, "\t-u, --update update tracked files\n"); exit(1); } static void parse_opts(const char **repo_path, struct index_options *opts, struct args_info *args) { if (args->argc <= 1) print_usage(); for (args->pos = 1; args->pos < args->argc; ++args->pos) { const char *curr = args->argv[args->pos]; if (curr[0] != '-') { if (!strcmp("add", curr)) { opts->mode = INDEX_ADD; continue; } else if (opts->mode == INDEX_NONE) { fprintf(stderr, "missing command: %s", curr); print_usage(); break; } else { /* We might be looking at a filename */ break; } } else if (match_bool_arg(&opts->verbose, args, "--verbose") || match_bool_arg(&opts->dry_run, args, "--dry-run") || match_str_arg(repo_path, args, "--git-dir") || (opts->mode == INDEX_ADD && match_bool_arg(&opts->add_update, args, "--update"))) { continue; } else if (match_bool_arg(NULL, args, "--help")) { print_usage(); break; } else if (match_arg_separator(args)) { break; } else { fprintf(stderr, "Unsupported option %s.\n", curr); print_usage(); } } }
0
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2/examples/stash.c
/* * libgit2 "stash" example - shows how to use the stash API * * Written by the libgit2 contributors * * To the extent possible under law, the author(s) have dedicated all copyright * and related and neighboring rights to this software to the public domain * worldwide. This software is distributed without any warranty. * * You should have received a copy of the CC0 Public Domain Dedication along * with this software. If not, see * <http://creativecommons.org/publicdomain/zero/1.0/>. */ #include <stdarg.h> #include "common.h" enum subcmd { SUBCMD_APPLY, SUBCMD_LIST, SUBCMD_POP, SUBCMD_PUSH }; struct opts { enum subcmd cmd; int argc; char **argv; }; static void usage(const char *fmt, ...) { va_list ap; fputs("usage: git stash list\n", stderr); fputs(" or: git stash ( pop | apply )\n", stderr); fputs(" or: git stash [push]\n", stderr); fputs("\n", stderr); va_start(ap, fmt); vfprintf(stderr, fmt, ap); va_end(ap); exit(1); } static void parse_subcommand(struct opts *opts, int argc, char *argv[]) { char *arg = (argc < 2) ? "push" : argv[1]; enum subcmd cmd; if (!strcmp(arg, "apply")) { cmd = SUBCMD_APPLY; } else if (!strcmp(arg, "list")) { cmd = SUBCMD_LIST; } else if (!strcmp(arg, "pop")) { cmd = SUBCMD_POP; } else if (!strcmp(arg, "push")) { cmd = SUBCMD_PUSH; } else { usage("invalid command %s", arg); return; } opts->cmd = cmd; opts->argc = (argc < 2) ? argc - 1 : argc - 2; opts->argv = argv; } static int cmd_apply(git_repository *repo, struct opts *opts) { if (opts->argc) usage("apply does not accept any parameters"); check_lg2(git_stash_apply(repo, 0, NULL), "Unable to apply stash", NULL); return 0; } static int list_stash_cb(size_t index, const char *message, const git_oid *stash_id, void *payload) { UNUSED(stash_id); UNUSED(payload); printf("stash@{%"PRIuZ"}: %s\n", index, message); return 0; } static int cmd_list(git_repository *repo, struct opts *opts) { if (opts->argc) usage("list does not accept any parameters"); check_lg2(git_stash_foreach(repo, list_stash_cb, NULL), "Unable to list stashes", NULL); return 0; } static int cmd_push(git_repository *repo, struct opts *opts) { git_signature *signature; git_commit *stash; git_oid stashid; if (opts->argc) usage("push does not accept any parameters"); check_lg2(git_signature_default(&signature, repo), "Unable to get signature", NULL); check_lg2(git_stash_save(&stashid, repo, signature, NULL, GIT_STASH_DEFAULT), "Unable to save stash", NULL); check_lg2(git_commit_lookup(&stash, repo, &stashid), "Unable to lookup stash commit", NULL); printf("Saved working directory %s\n", git_commit_summary(stash)); git_signature_free(signature); git_commit_free(stash); return 0; } static int cmd_pop(git_repository *repo, struct opts *opts) { if (opts->argc) usage("pop does not accept any parameters"); check_lg2(git_stash_pop(repo, 0, NULL), "Unable to pop stash", NULL); printf("Dropped refs/stash@{0}\n"); return 0; } int lg2_stash(git_repository *repo, int argc, char *argv[]) { struct opts opts = { 0 }; parse_subcommand(&opts, argc, argv); switch (opts.cmd) { case SUBCMD_APPLY: return cmd_apply(repo, &opts); case SUBCMD_LIST: return cmd_list(repo, &opts); case SUBCMD_PUSH: return cmd_push(repo, &opts); case SUBCMD_POP: return cmd_pop(repo, &opts); } 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/examples/for-each-ref.c
#include <git2.h> #include "common.h" static int show_ref(git_reference *ref, void *data) { git_repository *repo = data; git_reference *resolved = NULL; char hex[GIT_OID_HEXSZ+1]; const git_oid *oid; git_object *obj; if (git_reference_type(ref) == GIT_REFERENCE_SYMBOLIC) check_lg2(git_reference_resolve(&resolved, ref), "Unable to resolve symbolic reference", git_reference_name(ref)); oid = git_reference_target(resolved ? resolved : ref); git_oid_fmt(hex, oid); hex[GIT_OID_HEXSZ] = 0; check_lg2(git_object_lookup(&obj, repo, oid, GIT_OBJECT_ANY), "Unable to lookup object", hex); printf("%s %-6s\t%s\n", hex, git_object_type2string(git_object_type(obj)), git_reference_name(ref)); if (resolved) git_reference_free(resolved); return 0; } int lg2_for_each_ref(git_repository *repo, int argc, char **argv) { UNUSED(argv); if (argc != 1) fatal("Sorry, no for-each-ref options supported yet", NULL); check_lg2(git_reference_foreach(repo, show_ref, repo), "Could not iterate over references", NULL); 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/examples/config.c
/* * libgit2 "config" example - shows how to use the config API * * Written by the libgit2 contributors * * To the extent possible under law, the author(s) have dedicated all copyright * and related and neighboring rights to this software to the public domain * worldwide. This software is distributed without any warranty. * * You should have received a copy of the CC0 Public Domain Dedication along * with this software. If not, see * <http://creativecommons.org/publicdomain/zero/1.0/>. */ #include "common.h" static int config_get(git_config *cfg, const char *key) { git_config_entry *entry; int error; if ((error = git_config_get_entry(&entry, cfg, key)) < 0) { if (error != GIT_ENOTFOUND) printf("Unable to get configuration: %s\n", git_error_last()->message); return 1; } puts(entry->value); /* Free the git_config_entry after use with `git_config_entry_free()`. */ git_config_entry_free(entry); return 0; } static int config_set(git_config *cfg, const char *key, const char *value) { if (git_config_set_string(cfg, key, value) < 0) { printf("Unable to set configuration: %s\n", git_error_last()->message); return 1; } return 0; } int lg2_config(git_repository *repo, int argc, char **argv) { git_config *cfg; int error; if ((error = git_repository_config(&cfg, repo)) < 0) { printf("Unable to obtain repository config: %s\n", git_error_last()->message); goto out; } if (argc == 2) { error = config_get(cfg, argv[1]); } else if (argc == 3) { error = config_set(cfg, argv[1], argv[2]); } else { printf("USAGE: %s config <KEY> [<VALUE>]\n", argv[0]); error = 1; } /** * The configuration file must be freed once it's no longer * being used by the user. */ git_config_free(cfg); out: 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/docs/code_of_conduct.md
# Contributor Covenant Code of Conduct ## Our Pledge In the interest of fostering an open and welcoming environment, we as contributors and maintainers pledge to making participation in our project and our community a harassment-free experience for everyone, regardless of age, body size, disability, ethnicity, gender identity and expression, level of experience, nationality, personal appearance, race, religion, or sexual identity and orientation. ## Our Standards Examples of behavior that contributes to creating a positive environment include: * Using welcoming and inclusive language * Being respectful of differing viewpoints and experiences * Gracefully accepting constructive criticism * Focusing on what is best for the community * Showing empathy towards other community members Examples of unacceptable behavior by participants include: * The use of sexualized language or imagery and unwelcome sexual attention or advances * Trolling, insulting/derogatory comments, and personal or political attacks * Public or private harassment * Publishing others' private information, such as a physical or electronic address, without explicit permission * Other conduct which could reasonably be considered inappropriate in a professional setting ## Our Responsibilities Project maintainers are responsible for clarifying the standards of acceptable behavior and are expected to take appropriate and fair corrective action in response to any instances of unacceptable behavior. Project maintainers have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, or to ban temporarily or permanently any contributor for other behaviors that they deem inappropriate, threatening, offensive, or harmful. ## Scope This Code of Conduct applies both within project spaces and in public spaces when an individual is representing the project or its community. Examples of representing a project or community include using an official project e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event. Representation of a project may be further defined and clarified by project maintainers. ## Enforcement Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by contacting the project team at [[email protected]][email]. All complaints will be reviewed and investigated and will result in a response that is deemed necessary and appropriate to the circumstances. The project team is obligated to maintain confidentiality with regard to the reporter of an incident. Further details of specific enforcement policies may be posted separately. Project maintainers who do not follow or enforce the Code of Conduct in good faith may face temporary or permanent repercussions as determined by other members of the project's leadership. ## Attribution This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, available at [http://contributor-covenant.org/version/1/4][version] [email]: mailto:[email protected] [homepage]: http://contributor-covenant.org [version]: http://contributor-covenant.org/version/1/4/
0
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2/docs/threading.md
Threading in libgit2 ================== Unless otherwise specified, libgit2 objects cannot be safely accessed by multiple threads simultaneously. There are also caveats on the cryptographic libraries libgit2 or its dependencies link to (more on this later). For libgit2 itself, provided you take the following into consideration you won't run into issues: Sharing objects --------------- Use an object from a single thread at a time. Most data structures do not guard against concurrent access themselves. This is because they are rarely used in isolation and it makes more sense to synchronize access via a larger lock or similar mechanism. There are some objects which are read-only/immutable and are thus safe to share across threads, such as references and configuration snapshots. Error messages -------------- The error message is thread-local. The `git_error_last()` call must happen on the same thread as the error in order to get the message. Often this will be the case regardless, but if you use something like the [GCD](http://en.wikipedia.org/wiki/Grand_Central_Dispatch) on macOS (where code is executed on an arbitrary thread), the code must make sure to retrieve the error code on the thread where the error happened. Threading and cryptographic libraries ======================================= On Windows ---------- When built as a native Windows DLL, libgit2 uses WinCNG and WinHTTP, both of which are thread-safe. You do not need to do anything special. When using libssh2 which itself uses WinCNG, there are no special steps necessary. If you are using a MinGW or similar environment where libssh2 uses OpenSSL or libgcrypt, then the general case affects you. On macOS ----------- By default we make use of CommonCrypto and SecureTransport for cryptographic support. These are thread-safe and you do not need to do anything special. Note that libssh2 may still use OpenSSL itself. In that case, the general case still affects you if you use ssh. General Case ------------ libgit2 will default to OpenSSL for HTTPS transport (except on Windows and macOS, as mentioned above). On any system, mbedTLS _may_ be optionally enabled as the security provider. OpenSSL is thread-safe starting at version 1.1.0. If your copy of libgit2 is linked against that version, you do not need to take any further steps. Older versions of OpenSSL are made to be thread-implementation agnostic, and the users of the library must set which locking function it should use. libgit2 cannot know what to set as the user of libgit2 may also be using OpenSSL independently and the locking settings must then live outside the lifetime of libgit2. Even if libgit2 doesn't use OpenSSL directly, OpenSSL can still be used by libssh2 depending on the configuration. If OpenSSL is used by more than one library, you only need to set up threading for OpenSSL once. If libgit2 is linked against OpenSSL < 1.1.0, it provides a last-resort convenience function `git_openssl_set_locking()` (available in `sys/openssl.h`) to use the platform-native mutex mechanisms to perform the locking, which you can use if you do not want to use OpenSSL outside of libgit2, or you know that libgit2 will outlive the rest of the operations. It is then not safe to use OpenSSL multi-threaded after libgit2's shutdown function has been called. Note `git_openssl_set_locking()` only works if libgit2 uses OpenSSL directly - if OpenSSL is only used as a dependency of libssh2 as described above, `git_openssl_set_locking()` is a no-op. If your programming language offers a package/bindings for OpenSSL, you should very strongly prefer to use that in order to set up locking, as they provide a level of coordination which is impossible when using this function. See the [OpenSSL documentation](https://www.openssl.org/docs/crypto/threads.html) on threading for more details, and http://trac.libssh2.org/wiki/MultiThreading for a specific example of providing the threading callbacks. libssh2 may be linked against OpenSSL or libgcrypt. If it uses OpenSSL, see the above paragraphs. If it uses libgcrypt, then you need to set up its locking before using it multi-threaded. libgit2 has no direct connection to libgcrypt and thus has no convenience functions for it (but libgcrypt has macros). Read libgcrypt's [threading documentation for more information](http://www.gnupg.org/documentation/manuals/gcrypt/Multi_002dThreading.html) It is your responsibility as an application author or packager to know what your dependencies are linked against and to take the appropriate steps to ensure the cryptographic libraries are thread-safe. We agree that this situation is far from ideal but at this time it is something the application authors need to deal with.
0
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2/docs/projects.md
Projects For LibGit2 ==================== So, you want to start helping out with `libgit2`? That's fantastic! We welcome contributions and we promise we'll try to be nice. This is a list of libgit2 related projects that new contributors can take on. It includes a number of good starter projects as well as some larger ideas that no one is actively working on. ## Before You Start Please start by reading the [README.md](../README.md), [contributing.md](contributing.md), and [conventions.md](conventions.md) files before diving into one of these projects. Those explain our work flow and coding conventions to help ensure that your work will be easily integrated into libgit2. Next, work through the build instructions and make sure you can clone the repository, compile it, and run the tests successfully. That will make sure that your development environment is set up correctly and you are ready to start on libgit2 development. ## Starter Projects These are good small projects to get started with libgit2. * Look at the `examples/` programs, find an existing one that mirrors a core Git command and add a missing command-line option. There are many gaps right now and this helps demonstrate how to use the library. Here are some specific ideas (though there are many more): * Fix the `examples/diff.c` implementation of the `-B` (a.k.a. `--break-rewrites`) command line option to actually look for the optional `[<n>][/<m>]` configuration values. There is an existing comment that reads `/* TODO: parse thresholds */`. The trick to this one will be doing it in a manner that is clean and simple, but still handles the various cases correctly (e.g. `-B/70%` is apparently a legal setting). * As an extension to the matching idea for `examples/log.c`, add the `-i` option to use `strcasestr()` for matches. * For `examples/log.c`, implement the `--first-parent` option now that libgit2 supports it in the revwalk API. * Pick a Git command that is not already emulated in `examples/` and write a new example that mirrors the behavior. Examples don't have to be perfect emulations, but should demonstrate how to use the libgit2 APIs to get results that are similar to Git commands. This lets you (and us) easily exercise a particular facet of the API and measure compatibility and feature parity with core git. * Submit a PR to clarify documentation! While we do try to document all of the APIs, your fresh eyes on the documentation will find areas that are confusing much more easily. If none of these appeal to you, take a look at our issues list to see if there are any unresolved issues you'd like to jump in on. ## Larger Projects These are ideas for larger projects mostly taken from our backlog of [Issues](https://github.com/libgit2/libgit2/issues). Please don't dive into one of these as a first project for libgit2 - we'd rather get to know you first by successfully shipping your work on one of the smaller projects above. Some of these projects are broken down into subprojects and/or have some incremental steps listed towards the larger goal. Those steps might make good smaller projects by themselves. * Port part of the Git test suite to run against the command line emulation in `examples/` * Pick a Git command that is emulated in our `examples/` area * Extract the Git tests that exercise that command * Convert the tests to call our emulation * These tests could go in `examples/tests/`... * Add hooks API to enumerate and manage hooks (not run them at this point) * Enumeration of available hooks * Lookup API to see which hooks have a script and get the script * Read/write API to load a hook script and write a hook script * Eventually, callback API to invoke a hook callback when libgit2 executes the action in question * Isolate logic of ignore evaluation into a standalone API * Upgrade internal libxdiff code to latest from core Git * Tree builder improvements: * Extend to allow building a tree hierarchy * Apply-patch API * Add a patch editing API to enable "git add -p" type operations * Textconv API to filter binary data before generating diffs (something like the current Filter API, probably). * Performance profiling and improvement * Support "git replace" ref replacements * Include conflicts in diff results and in status * GIT_DELTA_CONFLICT for items in conflict (with multiple files) * Appropriate flags for status * Support sparse checkout (i.e. "core.sparsecheckout" and ".git/info/sparse-checkout")
0
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2/docs/release.md
# Releasing the library We have three kinds of releases: "full" releases, maintenance releases and security releases. Full ones release the state of the `main` branch whereas maintenance releases provide bugfixes building on top of the currently released series. Security releases are also for the current series but only contain security fixes on top of the previous release. ## Full release We aim to release once every six months. We start the process by opening an issue. This is accompanied with a feature freeze. From now until the release, only bug fixes are to be merged. Use the following as a base for the issue Release v0.X Let's release v0.X, codenamed: <something witty> - [ ] Bump the versions in the headers (`include/git2/version.h`) - [ ] Bump the versions in the clib manifest (`package.json`) - [ ] Make a release candidate - [ ] Plug any final leaks - [ ] Fix any last-minute issues - [ ] Make sure changelog.md reflects everything worth discussing - [ ] Update the version in changelog.md and the header - [ ] Produce a release candidate - [ ] Tag - [ ] Create maint/v0.X - [ ] Update any bindings the core team works with We tag at least one release candidate. This RC must carry the new version in the headers, including the SOVERSION. If there are no significant issues found, we can go straight to the release after a single RC. This is up to the discretion of the release manager. There is no set time to have the candidate out, but we should we should give downstream projects at least a week to give feedback. Preparing the first release candidate includes updating the version number of libgit2 to the new version number. To do so, a pull request shall be submitted that adjusts the version number in the following places: - docs/changelog.md - include/git2/version.h - package.json As soon as the pull request is merged, the merge commit shall be tagged with a lightweight tag. The tagging happens via GitHub's "releases" tab which lets us attach release notes to a particular tag. In the description we include the changes in `docs/changelog.md` between the last full release. Use the following as a base for the release notes This is the first release of the v0.X series, <codename>. The changelog follows. followed by the three sections in the changelog. For release candidates we can avoid copying the full changelog and only include any new entries. During the freeze, and certainly after the first release candidate, any bindings the core team work with should be updated in order to discover any issues that might come up with the multitude of approaches to memory management, embedding or linking. Create a branch `maint/v0.X` at the current state of `main` after you've created the tag. This will be used for maintenance releases and lets our dependents track the latest state of the series. ## Maintenance release Every once in a while, when we feel we've accumulated a significant amount of backportable fixes in the mainline branch, we produce a maintenance release in order to provide fixes or improvements for those who track the releases. This also lets our users and integrators receive updates without having to upgrade to the next full release. As a rule of thumb, it's a good idea to produce a maintenance release for the current series when we're getting ready for a full release. This gives the (still) current series a last round of fixes without having to upgrade (which with us potentially means adjusting to API changes). Start by opening an issue. Use the following as a base. Release v0.X.Y Enough fixes have accumulated, let's release v0.X.Y - [ ] Select the changes we want to backport - [ ] Update maint/v0.X - [ ] Tag The list of changes to backport does not need to be comprehensive and we might not backport something if the code in mainline has diverged significantly. These fixes do not include those which require API or ABI changes as we release under the same SOVERSION. Do not merge into the `maint/v0.X` until we are getting ready to produce a new release. There is always the possibility that we will need to produce a security release and those must only include the relevant security fixes and not arbitrary fixes we were planning on releasing at some point. Here we do not use release candidates as the changes are supposed to be small and proven. ## Security releases This is the same as a maintenance release, except that the fix itself will most likely be developed in a private repository and will only be visible to a select group of people until the release. We have committed to providing security fixes for the latest two released versions. E.g. if the latest version is v0.28.x, then we will provide security fixes for both v0.28.x and v0.27.y. ## Updating documentation We use docurium to generate our documentation. It is a tool written in ruby which leverages libclang's documentation parser. Install docurium gem install docurium and run it against our description file with the tip of `main` checked out. cm doc api.docurium It will start up a few proceses and write out the results as a new commit onto the `gh-pages` branch. That can be pushed to GitHub to update what will show up on our documentation reference site.
0
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2/docs/merge-df_conflicts.txt
Anc / Our / Thr represent the ancestor / ours / theirs side of a merge from branch "branch" into HEAD. Workdir represents the expected files in the working directory. Index represents the expected files in the index, with stage markers. Anc Our Thr Workdir Index 1 D D D/F D/F D/F [0] 2 D D+ D~HEAD (mod/del) D/F [0] D/F D/F D [1] D [2] 3 D D D/F D/F [0] D/F 4 D D+ D~branch (mod/del) D/F [0] D/F D/F D [1] D [3] 5 D D/F (add/add) D/F [2] D/F D/F [3] D/F 6 D/F D/F D D [0] D 7 D/F D/F+ D/F (mod/del) D/F [1] D D~branch (fil/dir) D/F [2] D [3] 8 D/F D/F D D [0] D 9 D/F D/F+ D/F (mod/del) D/F [1] D D~HEAD (fil/dir) D [2] D/F [3] 10 D/F D/F (fil/dir) D/F [0] D D~HEAD D [2] D
0
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2/docs/coding-style.md
# libgit2 Coding Style This documentation describes the preferred coding style for the libgit2 project. While not all parts of our code base conform to this coding style, the outlined rules are what we aim for. Note that in no case do we accept changes that convert huge parts of the code base to use our coding style. Instead, it is encouraged to modernize small parts of code you're going to modify anyway for a given change you want to introduce. A good rule to follow is the Boy Scout Rule: "Leave the campground cleaner than you found it." ## C Coding Style The following sections define the coding style for all code files and headers. ### Indentation and Alignment Code is indented by tabs, where a tab is 8 spaces. Each opening scope increases the indentation level. ```c int foobar(int void) { if (condition) doit(); /* Body */ } ``` Switch statements have their `case`s aligned with the `switch` keyword. Case bodies are indented by an additional level. Case bodies should not open their own scope to declare variables. ```c switch (c) { case 'a': case 'b': return 0; default: return -1; } ``` Multi-line conditions should be aligned with the opening brace of the current statement: ```c if (one_very_long_condition(c) && another_very_long_condition(c)) doit(); ``` ### Spaces There must be no space between the function and its arguments, arguments must be separated by a space: ```c int doit(int first_arg, int second_arg); doit(1, 2); ``` For any binary or ternary operators, the arguments and separator must be separated by a space: ```c 1 + 2; x ? x : NULL; ``` Unary operators do not have a space between them and the argument they refer to: ```c *c &c ``` The `sizeof` operator always must not have a space and must use braces around the type: ``` sizeof(int) ``` There must be a space after the keywords `if`, `switch`, `case`, `do` and `while`. ### Braces Functions must have their opening brace on the following line: ```c void foobar(void) { doit(); } ``` For conditions, braces should be placed on the same line as the condition: ```c if (condition(c)) { doit(); dothat(); } while (true) { doit(); } ``` In case a condition's body has a single line, only, it's allowed to omit braces, except if any of its `else if` or `else` branches has more than one line: ```c if (condition(c)) doit(); if (condition(c)) doit(); else if (other_condition(c)) doit(); /* This example must use braces as the `else if` requires them. */ if (condition(c)) { doit(); } else if (other_condition(c)) { doit(); dothat(); } else { abort(); } ``` ### Comments Comments must use C-style `/* */` comments. C++-style `// `comments are not allowed in our codebase. This is a strict requirement as libgit2 tries to be compliant with the ISO C90 standard, which only allows C-style comments. Single-line comments may have their opening and closing tag on the same line: ```c /* This is a short comment. */ ``` For multi-line comments, the opening and closing tag should be empty: ```c /* * This is a rather long and potentially really unwiedly but informative * multiline comment that helps quite a lot. */ ``` Public functions must have documentation that explain their usage, internal functions should have a comment. We use Docurium to generate documentation derived from these comments, which uses syntax similar to Doxygen. The first line should be a short summary of what the function does. More in-depth explanation should be separated from that first line by an empty line. Parameters and return values should be documented via `@return` and `@param` tags: ```c /* * Froznicate the string. * * Froznicate the string by foobaring its internal structure into a more obvious * translation. Note that the returned string is a newly allocated string that * shall be `free`d by the caller. * * @param s String to froznicate * @return A newly allocated string or `NULL` in case an error occurred. */ char *froznicate(const char *s); ``` ### Variables Variables must be declared at the beginning of their scope. This is a strict requirement as libgit2 tries to be compliant with the ISO C90 standard, which forbids mixed declarations and code: ```c void foobar(void) { char *c = NULL; int a, b; a = 0; b = 1; return c; } ``` ### Naming Variables must have all-lowercase names. In case a variable name has multiple words, words should be separated by an underscore `_` character. While recommended to use descriptive naming, common variable names like `i` for indices are allowed. All public functions must have a `git` prefix as well as a prefix indicating their respective subsystem. E.g. a function that opens a repository should be called `git_repository_open()`. Functions that are not public but declared in an internal header file for use by other subsystems should follow the same naming pattern. File-local static functions must not have a `git` prefix, but should have a prefix indicating their respective subsystem. All structures declared in the libgit2 project must have a `typedef`, we do not use `struct type` variables. Type names follow the same schema as functions. ### Error Handling The libgit2 project mostly uses error codes to indicate errors. Error codes are always of type `int`, where `0` indicates success and a negative error code indicates an error case. In some cases, positive error codes may be used to indicate special cases. Returned values that are not an error code should be returned via an out parameter. Out parameters must always come first in the list of arguments. ```c int doit(const char **out, int arg) { if (!arg) return -1; *out = "Got an argument"; return 0; } ``` To avoid repetitive and fragile error handling in case a function has resources that need to be free'd, we use `goto out`s: ```c int doit(char **out, int arg) { int error = 0; char *c; c = malloc(strlen("Got an argument") + 1); if (!c) { error = -1; goto out; } if (!arg) { error = -1; goto out; } strcpy(c, "Got an argument") *out = c; out: if (error) free(c); return error; } ``` When calling functions that return an error code, you should assign the error code to an `error` variable and, in case an error case is indicated and no custom error handling is required, return that error code: ```c int foobar(void) { int error; if ((error = doit()) < 0) return error; return 0; } ``` When doing multiple function calls where all of the functions return an error code, it's common practice to chain these calls together: ```c int doit(void) { int error; if ((error = dothis()) < 0 || (error = dothat()) < 0) return error; return 0; } ``` ## CMake Coding Style The following section defines the coding style for our CMake build system. ### Indentation Code is indented by tabs, where a tab is 8 spaces. Each opening scope increases the indentation level. ```cmake if(CONDITION) doit() endif() ``` ### Spaces There must be no space between keywords and their opening brace. While this is the same as in our C codebase for function calls, this also applies to conditional keywords. This is done to avoid the awkward-looking `else ()` statement. ```cmake if(CONDITION) doit() else() dothat() endif() ``` ### Case While CMake is completely case-insensitive when it comes to function calls, we want to agree on a common coding style for this. To reduce the danger of repetitive strain injuries, all function calls should be lower-case (NB: this is not currently the case yet, but introduced as a new coding style by this document). Variables are written all-uppercase. In contrast to functions, variables are case-sensitive in CMake. As CMake itself uses upper-case variables in all places, we should follow suit and do the same. Control flow keywords must be all lowercase. In contrast to that, test keywords must be all uppercase: ```cmake if(NOT CONDITION) doit() elseif(FOO AND BAR) dothat() endif() ``` ### Targets CMake code should not use functions that modify the global scope but prefer their targeted equivalents, instead. E.g. instead of using `include_directories()`, you must use `target_include_directories()`. An exception to this rule is setting up global compiler flags like warnings or flags required to set up the build type. ### Dependencies Dependencies should not be discovered or set up in the main "CMakeLists.txt" module. Instead, they should either have their own module in our top-level "cmake/" directory or have a "CMakeLists.txt" in their respective "deps/" directory in case it is a vendored library. All dependencies should expose interface library targets that can be linked against with `target_link_libraries()`.
0
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2/docs/error-handling.md
Error reporting in libgit2 ========================== Libgit2 tries to follow the POSIX style: functions return an `int` value with 0 (zero) indicating success and negative values indicating an error. There are specific negative error codes for each "expected failure" (e.g. `GIT_ENOTFOUND` for files that take a path which might be missing) and a generic error code (-1) for all critical or non-specific failures (e.g. running out of memory or system corruption). When a negative value is returned, an error message is also set. The message can be accessed via the `git_error_last` function which will return a pointer to a `git_error` structure containing the error message text and the class of error (i.e. what part of the library generated the error). For instance: An object lookup by SHA prefix (`git_object_lookup_prefix`) has two expected failure cases: the SHA is not found at all which returns `GIT_ENOTFOUND` or the SHA prefix is ambiguous (i.e. two or more objects share the prefix) which returns `GIT_EAMBIGUOUS`. There are any number of critical failures (such as a packfile being corrupted, a loose object having the wrong access permissions, etc.) all of which will return -1. When the object lookup is successful, it will return 0. If libgit2 was compiled with threads enabled (`-DTHREADSAFE=ON` when using CMake), then the error message will be kept in thread-local storage, so it will not be modified by other threads. If threads are not enabled, then the error message is in global data. All of the error return codes, the `git_error` type, the error access functions, and the error classes are defined in `include/git2/errors.h`. See the documentation there for details on the APIs for accessing, clearing, and even setting error codes. When writing libgit2 code, please be smart and conservative when returning error codes. Functions usually have a maximum of two or three "expected errors" and in most cases only one. If you feel there are more possible expected error scenarios, then the API you are writing may be at too high a level for core libgit2. Example usage ------------- When using libgit2, you will typically capture the return value from functions using an `int` variable and check to see if it is negative. When that happens, you can, if you wish, look at the specific value or look at the error message that was generated. ~~~c { git_repository *repo; int error = git_repository_open(&repo, "path/to/repo"); if (error < 0) { fprintf(stderr, "Could not open repository: %s\n", git_error_last()->message); exit(1); } ... use `repo` here ... git_repository_free(repo); /* void function - no error return code */ } ~~~ Some of the error return values do have meaning. Optionally, you can look at the specific error values to decide what to do. ~~~c { git_repository *repo; const char *path = "path/to/repo"; int error = git_repository_open(&repo, path); if (error < 0) { if (error == GIT_ENOTFOUND) fprintf(stderr, "Could not find repository at path '%s'\n", path); else fprintf(stderr, "Unable to open repository: %s\n", git_error_last()->message); exit(1); } ... happy ... } ~~~ Some of the higher-level language bindings may use a range of information from libgit2 to convert error return codes into exceptions, including the specific error return codes and even the class of error and the error message returned by `git_error_last`, but the full range of that logic is beyond the scope of this document. Example internal implementation ------------------------------- Internally, libgit2 detects error scenarios, records error messages, and returns error values. Errors from low-level functions are generally passed upwards (unless the higher level can either handle the error or wants to translate the error into something more meaningful). ~~~c int git_repository_open(git_repository **repository, const char *path) { /* perform some logic to open the repository */ if (p_exists(path) < 0) { git_error_set(GIT_ERROR_REPOSITORY, "The path '%s' doesn't exist", path); return GIT_ENOTFOUND; } ... } ~~~ Note that some error codes have been defined with a specific meaning in the context of callbacks: - `GIT_EUSER` provides a way to bubble up a non libgit2-related failure, which allows it to be preserved all the way up to the initial function call (a `git_cred` setup trying to access an unavailable LDAP server for instance). - `GIT_EPASSTHROUGH` provides a way to tell libgit2 that it should behave as if no callback was provided. This is of special interest to bindings, which would always provide a C function as a "trampoline", and decide at runtime what to do. The public error API -------------------- - `const git_error *git_error_last(void)`: The main function used to look up the last error. This may return NULL if no error has occurred. Otherwise this should return a `git_error` object indicating the class of error and the error message that was generated by the library. Do not use this function unless the prior call to a libgit2 API returned an error, as it can otherwise give misleading results. libgit2's error strings are not cleared aggressively, and this function may return an error string that reflects a prior error, possibly even reflecting internal state. The last error is stored in thread-local storage when libgit2 is compiled with thread support, so you do not have to worry about another thread overwriting the value. When thread support is off, the last error is a global value. _Note_ There are some known bugs in the library where this may return NULL even when an error code was generated. Please report these as bugs, but in the meantime, please code defensively and check for NULL when calling this function. - `void git_error_clear(void)`: This function clears the last error. The library will call this when an error is generated by low level function and the higher level function handles the error. _Note_ There are some known bugs in the library where a low level function's error message is not cleared by higher level code that handles the error and returns zero. Please report these as bugs, but in the meantime, a zero return value from a libgit2 API does not guarantee that `git_error_last()` will return NULL. - `void git_error_set(int error_class, const char *message)`: This function can be used when writing a custom backend module to set the libgit2 error message. See the documentation on this function for its use. Normal usage of libgit2 will probably never need to call this API. - `void git_error_set_oom(void)`: This is a standard function for reporting an out-of-memory error. It is written in a manner that it doesn't have to allocate any extra memory in order to record the error, so this is the best way to report that scenario. Deviations from the standard ---------------------------- There are some public functions that do not return `int` values. There are two primary cases: * `void` return values: If a function has a `void` return, then it will never fail. This primary will be used for object destructors. * `git_xyz *` return values: These are simple accessor functions where the only meaningful error would typically be looking something up by index and having the index be out of bounds. In those cases, the function will typically return NULL. * Boolean return values: There are some cases where a function cannot fail and wants to return a boolean value. In those cases, we try to return 1 for true and 0 for false. These cases are rare and the return value for the function should probably be an `unsigned int` to denote these cases. If you find an exception, please open an issue and let's fix it. There are a few other exceptions to these rules here and there in the library, but those are extremely rare and should probably be converted over to other to more standard patterns for usage. Feel free to open issues pointing these out. There are some known bugs in the library where some functions may return a negative value but not set an error message and some other functions may return zero (no error) and yet leave an error message set. Please report these cases as issues and they will be fixed. In the meanwhile, please code defensively, checking that the return value of `git_error_last` is not NULL before using it, and not relying on `git_error_last` to return NULL when a function returns 0 for success. The internal error API ---------------------- - `void git_error_set(int error_class, const char *fmt, ...)`: This is the main internal function for setting an error. It works like `printf` to format the error message. See the notes of `git_error_set_str` for a general description of how error messages are stored (and also about special handling for `error_class` of `GIT_ERROR_OS`). Writing error messages ---------------------- Here are some guidelines when writing error messages: - Use proper English, and an impersonal or past tenses: *The given path does not exist*, *Failed to lookup object in ODB* - Use short, direct and objective messages. **One line, max**. libgit2 is a low level library: think that all the messages reported will be thrown as Ruby or Python exceptions. Think how long are common exception messages in those languages. - **Do not add redundant information to the error message**, specially information that can be inferred from the context. E.g. in `git_repository_open`, do not report a message like "Failed to open repository: path not found". Somebody is calling that function. If it fails, they already know that the repository failed to open! General guidelines for error reporting -------------------------------------- - Libgit2 does not handle programming errors with these functions. Programming errors are `assert`ed, and when their source is internal, fixed as soon as possible. This is C, people. Example of programming errors that would **not** be handled: passing NULL to a function that expects a valid pointer; passing a `git_tree` to a function that expects a `git_commit`. All these cases need to be identified with `assert` and fixed asap. Example of a runtime error: failing to parse a `git_tree` because it contains invalid data. Failing to open a file because it doesn't exist on disk. These errors are handled, a meaningful error message is set, and an error code is returned. - In general, *do not* try to overwrite errors internally and *do* propagate error codes from lower level functions to the higher level. There are some cases where propagating an error code will be more confusing rather than less, so there are some exceptions to this rule, but the default behavior should be to simply clean up and pass the error on up to the caller. **WRONG** ~~~c int git_commit_parent(...) { ... if (git_commit_lookup(parent, repo, parent_id) < 0) { git_error_set(GIT_ERROR_COMMIT, "Overwrite lookup error message"); return -1; /* mask error code */ } ... } ~~~ **RIGHT** ~~~c int git_commit_parent(...) { ... error = git_commit_lookup(parent, repo, parent_id); if (error < 0) { /* cleanup intermediate objects if necessary */ /* leave error message and propagate error code */ 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/docs/changelog.md
v1.3 ---- This is release v1.3.0, "Zugunruhe". This release includes only minor new features that will be helpful for users to have an orderly transition to the v2.0 lineage. ## New Features * Support custom git extensions by @ethomson in https://github.com/libgit2/libgit2/pull/6031 * Introduce `git_email_create`; deprecate `git_diff_format_email` by @ethomson in https://github.com/libgit2/libgit2/pull/6061 ## Deprecated APIs * `git_oidarray_free` is deprecated; callers should use `git_oidarray_dispose` ## Bug fixes * #6028: Check if `threadstate->error_t.message` is not `git_buf__initbuf` before freeing. by @arroz in https://github.com/libgit2/libgit2/pull/6029 * remote: Mark `git_remote_name_is_valid` as `GIT_EXTERN` by @lhchavez in https://github.com/libgit2/libgit2/pull/6032 * Fix config parsing for multiline with multiple quoted comment chars by @basile-henry in https://github.com/libgit2/libgit2/pull/6043 * indexer: Avoid one `mmap(2)`/`munmap(2)` pair per `git_indexer_append` call by @lhchavez in https://github.com/libgit2/libgit2/pull/6039 * merge: Check file mode when resolving renames by @ccstolley in https://github.com/libgit2/libgit2/pull/6060 * Allow proxy options when connecting with a detached remote. by @lrm29 in https://github.com/libgit2/libgit2/pull/6058 * win32: allow empty environment variables by @ethomson in https://github.com/libgit2/libgit2/pull/6063 * Fixes for deprecated APIs by @ethomson in https://github.com/libgit2/libgit2/pull/6066 * filter: use a `git_oid` in filter options, not a pointer by @ethomson in https://github.com/libgit2/libgit2/pull/6067 * diff: update `GIT_DIFF_IGNORE_BLANK_LINES` by @ethomson in https://github.com/libgit2/libgit2/pull/6068 * Attribute lookups are always on relative paths by @ethomson in https://github.com/libgit2/libgit2/pull/6073 * Handle long paths when querying attributes by @ethomson in https://github.com/libgit2/libgit2/pull/6075 ## Code cleanups * notes: use a buffer internally by @ethomson in https://github.com/libgit2/libgit2/pull/6047 * Fix coding style for pointer by @punkymaniac in https://github.com/libgit2/libgit2/pull/6045 * Use __typeof__ GNUC keyword for ISO C compatibility by @duncanthomson in https://github.com/libgit2/libgit2/pull/6041 * Discover libssh2 without pkg-config by @stac47 in https://github.com/libgit2/libgit2/pull/6053 * Longpath filter bug by @lrm29 in https://github.com/libgit2/libgit2/pull/6055 * Add test to ensure empty proxy env behaves like unset env by @sathieu in https://github.com/libgit2/libgit2/pull/6052 * Stdint header condition has been reverted. by @lolgear in https://github.com/libgit2/libgit2/pull/6020 * buf: `common_prefix` takes a string array by @ethomson in https://github.com/libgit2/libgit2/pull/6077 * oidarray: introduce `git_oidarray_dispose` by @ethomson in https://github.com/libgit2/libgit2/pull/6076 * examples: Free the git_config and git_config_entry after use by @257 in https://github.com/libgit2/libgit2/pull/6071 ## CI Improvements * ci: pull libssh2 from www.libssh2.org by @ethomson in https://github.com/libgit2/libgit2/pull/6064 ## Documentation changes * Update README.md by @shijinglu in https://github.com/libgit2/libgit2/pull/6050 ## New Contributors * @basile-henry made their first contribution in https://github.com/libgit2/libgit2/pull/6043 * @duncanthomson made their first contribution in https://github.com/libgit2/libgit2/pull/6041 * @stac47 made their first contribution in https://github.com/libgit2/libgit2/pull/6053 * @shijinglu made their first contribution in https://github.com/libgit2/libgit2/pull/6050 * @ccstolley made their first contribution in https://github.com/libgit2/libgit2/pull/6060 * @sathieu made their first contribution in https://github.com/libgit2/libgit2/pull/6052 * @257 made their first contribution in https://github.com/libgit2/libgit2/pull/6071 **Full Changelog**: https://github.com/libgit2/libgit2/compare/v1.2.0...v1.3.0 --------------------------------------------------------------------- v1.2 ----- This is release v1.2.0, "Absacker". This release includes many new features: in particular, support for commit graphs, multi-pack indexes, and `core.longpaths` support. This is meant to be the final minor release in the v1 lineage. v2.0 will be the next major release and will remove deprecated APIs and may include breaking changes. ## Deprecated APIs * revspec: rename git_revparse_mode_t to git_revspec_t by @ethomson in https://github.com/libgit2/libgit2/pull/5786 * tree: deprecate `git_treebuilder_write_with_buffer` by @ethomson in https://github.com/libgit2/libgit2/pull/5815 * Deprecate `is_valid_name` functions; replace with `name_is_valid` functions by @ethomson in https://github.com/libgit2/libgit2/pull/5659 * filter: stop taking git_buf as user input by @ethomson in https://github.com/libgit2/libgit2/pull/5859 * remote: introduce remote_ready_cb, deprecate resolve_url callback by @ethomson in https://github.com/libgit2/libgit2/pull/6012 * Introduce `create_commit_cb`, deprecate `signing_cb` by @ethomson in https://github.com/libgit2/libgit2/pull/6016 * filter: filter drivers stop taking git_buf as user input by @ethomson in https://github.com/libgit2/libgit2/pull/6011 * buf: deprecate public git_buf writing functions by @ethomson in https://github.com/libgit2/libgit2/pull/6017 ## New features * winhttp: support optional client cert by @ianhattendorf in https://github.com/libgit2/libgit2/pull/5384 * Add support for additional SSH hostkey types. by @arroz in https://github.com/libgit2/libgit2/pull/5750 * Handle ipv6 addresses by @ethomson in https://github.com/libgit2/libgit2/pull/5741 * zlib: Add support for building with Chromium's zlib implementation by @lhchavez in https://github.com/libgit2/libgit2/pull/5748 * commit-graph: Introduce a parser for commit-graph files by @lhchavez in https://github.com/libgit2/libgit2/pull/5762 * patch: add owner accessor by @KOLANICH in https://github.com/libgit2/libgit2/pull/5731 * commit-graph: Support lookups of entries in a commit-graph by @lhchavez in https://github.com/libgit2/libgit2/pull/5763 * commit-graph: Introduce `git_commit_graph_needs_refresh()` by @lhchavez in https://github.com/libgit2/libgit2/pull/5764 * Working directory path validation by @ethomson in https://github.com/libgit2/libgit2/pull/5823 * Support `core.longpaths` on Windows by @ethomson in https://github.com/libgit2/libgit2/pull/5857 * git_reference_create_matching: Treat all-zero OID as "must be absent" by @novalis in https://github.com/libgit2/libgit2/pull/5842 * diff:add option to ignore blank line changes by @yuuri in https://github.com/libgit2/libgit2/pull/5853 * [Submodule] Git submodule dup by @lolgear in https://github.com/libgit2/libgit2/pull/5890 * commit-graph: Use the commit-graph in revwalks by @lhchavez in https://github.com/libgit2/libgit2/pull/5765 * commit-graph: Introduce `git_commit_list_generation_cmp` by @lhchavez in https://github.com/libgit2/libgit2/pull/5766 * graph: Create `git_graph_reachable_from_any()` by @lhchavez in https://github.com/libgit2/libgit2/pull/5767 * Support reading attributes from a specific commit by @ethomson in https://github.com/libgit2/libgit2/pull/5952 * [Branch] Branch upstream with format by @lolgear in https://github.com/libgit2/libgit2/pull/5861 * Dynamically load OpenSSL (optionally) by @ethomson in https://github.com/libgit2/libgit2/pull/5974 * Set refs/remotes/origin/HEAD to default branch when branch is specified by @A-Ovchinnikov-mx in https://github.com/libgit2/libgit2/pull/6010 * midx: Add a way to write multi-pack-index files by @lhchavez in https://github.com/libgit2/libgit2/pull/5404 * Use error code GIT_EAUTH for authentication failures by @josharian in https://github.com/libgit2/libgit2/pull/5395 * midx: Introduce git_odb_write_multi_pack_index() by @lhchavez in https://github.com/libgit2/libgit2/pull/5405 * Checkout dry-run by @J0Nes90 in https://github.com/libgit2/libgit2/pull/5841 * mbedTLS: Fix setting certificate directory by @mikezackles in https://github.com/libgit2/libgit2/pull/6004 * remote: introduce remote_ready_cb, deprecate resolve_url callback by @ethomson in https://github.com/libgit2/libgit2/pull/6012 * Introduce `create_commit_cb`, deprecate `signing_cb` by @ethomson in https://github.com/libgit2/libgit2/pull/6016 * commit-graph: Add a way to write commit-graph files by @lhchavez in https://github.com/libgit2/libgit2/pull/5778 ## Bug fixes * Define `git___load` when building with `-DTHREADSAFE=OFF` by @lhchavez in https://github.com/libgit2/libgit2/pull/5664 * Make the Windows leak detection more robust by @lhchavez in https://github.com/libgit2/libgit2/pull/5661 * Refactor "global" state by @ethomson in https://github.com/libgit2/libgit2/pull/5546 * threadstate: rename tlsdata when building w/o threads by @ethomson in https://github.com/libgit2/libgit2/pull/5668 * Include `${MBEDTLS_INCLUDE_DIR}` when compiling `crypt_mbedtls.c` by @staticfloat in https://github.com/libgit2/libgit2/pull/5685 * Fix the `-DTHREADSAFE=OFF` build by @lhchavez in https://github.com/libgit2/libgit2/pull/5690 * Add missing worktree_dir check and test case by @rbmclean in https://github.com/libgit2/libgit2/pull/5692 * msvc crtdbg -> win32 leakcheck by @ethomson in https://github.com/libgit2/libgit2/pull/5580 * Introduce GIT_ASSERT macros by @ethomson in https://github.com/libgit2/libgit2/pull/5327 * Also add the raw hostkey to `git_cert_hostkey` by @lhchavez in https://github.com/libgit2/libgit2/pull/5704 * Make the odb race-free by @lhchavez in https://github.com/libgit2/libgit2/pull/5595 * Make the pack and mwindow implementations data-race-free by @lhchavez in https://github.com/libgit2/libgit2/pull/5593 * Thread-free implementation by @ethomson in https://github.com/libgit2/libgit2/pull/5719 * Thread-local storage: a generic internal library (with no allocations) by @ethomson in https://github.com/libgit2/libgit2/pull/5720 * Friendlier getting started in the lack of git_libgit2_init by @ethomson in https://github.com/libgit2/libgit2/pull/5578 * Make git__strntol64() ~70%* faster by @lhchavez in https://github.com/libgit2/libgit2/pull/5735 * Cache the parsed submodule config when diffing by @lhchavez in https://github.com/libgit2/libgit2/pull/5727 * pack: continue zlib while we can make progress by @ethomson in https://github.com/libgit2/libgit2/pull/5740 * Avoid using `__builtin_mul_overflow` with the clang+32-bit combo by @lhchavez in https://github.com/libgit2/libgit2/pull/5742 * repository: use intptr_t's in the config map cache by @ethomson in https://github.com/libgit2/libgit2/pull/5746 * Build with NO_MMAP by @0xdky in https://github.com/libgit2/libgit2/pull/5583 * Add documentation for git_blob_filter_options.version by @JoshuaS3 in https://github.com/libgit2/libgit2/pull/5759 * blob: fix name of `GIT_BLOB_FILTER_ATTRIBUTES_FROM_HEAD` by @ethomson in https://github.com/libgit2/libgit2/pull/5760 * Cope with empty default branch by @ethomson in https://github.com/libgit2/libgit2/pull/5770 * README: instructions for using libgit2 without compiling by @ethomson in https://github.com/libgit2/libgit2/pull/5772 * Use `p_pwrite`/`p_pread` consistently throughout the codebase by @lhchavez in https://github.com/libgit2/libgit2/pull/5769 * midx: Fix a bug in `git_midx_needs_refresh()` by @lhchavez in https://github.com/libgit2/libgit2/pull/5768 * mwindow: Fix a bug in the LRU window finding code by @lhchavez in https://github.com/libgit2/libgit2/pull/5783 * refdb_fs: Check git_sortedcache wlock/rlock errors by @mamapanda in https://github.com/libgit2/libgit2/pull/5800 * index: Check git_vector_dup error in write_entries by @mamapanda in https://github.com/libgit2/libgit2/pull/5801 * Fix documentation formating on repository.h by @punkymaniac in https://github.com/libgit2/libgit2/pull/5806 * include: fix typos in comments by @tniessen in https://github.com/libgit2/libgit2/pull/5805 * Fix some typos by @aaronfranke in https://github.com/libgit2/libgit2/pull/5797 * Check git_signature_dup failure by @mamapanda in https://github.com/libgit2/libgit2/pull/5817 * merge: Check insert_head_ids error in create_virtual_base by @mamapanda in https://github.com/libgit2/libgit2/pull/5818 * winhttp: skip certificate check if unable to send request by @ianhattendorf in https://github.com/libgit2/libgit2/pull/5814 * Default to GIT_BRANCH_DEFAULT if init.defaultBranch is empty string by @ianhattendorf in https://github.com/libgit2/libgit2/pull/5832 * Fix diff_entrycount -> diff_num_deltas doc typo by @mjsir911 in https://github.com/libgit2/libgit2/pull/5838 * repo: specify init.defaultbranch is meant to be a branch name by @carlosmn in https://github.com/libgit2/libgit2/pull/5835 * repo: remove an inappropriate use of PASSTHROUGH by @carlosmn in https://github.com/libgit2/libgit2/pull/5834 * src: fix typos in header files by @tniessen in https://github.com/libgit2/libgit2/pull/5843 * test: clean up memory leaks by @ethomson in https://github.com/libgit2/libgit2/pull/5858 * buf: remove unnecessary buf_text namespace by @ethomson in https://github.com/libgit2/libgit2/pull/5860 * Fix bug in git_diff_find_similar. by @staktrace in https://github.com/libgit2/libgit2/pull/5839 * Fix issues with Proxy Authentication after httpclient refactor by @implausible in https://github.com/libgit2/libgit2/pull/5852 * tests: clean up memory leak, fail on leak for win32 by @ethomson in https://github.com/libgit2/libgit2/pull/5892 * Tolerate readlink size less than st_size by @dtolnay in https://github.com/libgit2/libgit2/pull/5900 * Define WINHTTP_NO_CLIENT_CERT_CONTEXT if needed by @jacquesg in https://github.com/libgit2/libgit2/pull/5929 * Update from regex to pcre licensing information in docs/contributing.md by @boretrk in https://github.com/libgit2/libgit2/pull/5916 * Consider files executable only if the user can execute them by @novalis in https://github.com/libgit2/libgit2/pull/5915 * git__timer: Limit ITimer usage to AmigaOS4 by @boretrk in https://github.com/libgit2/libgit2/pull/5936 * Fix memory leak in git_smart__connect by @punkymaniac in https://github.com/libgit2/libgit2/pull/5908 * config: fix included configs not refreshed more than once by @Batchyx in https://github.com/libgit2/libgit2/pull/5926 * Fix wrong time_t used in function by @NattyNarwhal in https://github.com/libgit2/libgit2/pull/5938 * fix check for ignoring of negate rules by @palmin in https://github.com/libgit2/libgit2/pull/5824 * Make `FIND_PACKAGE(PythonInterp)` prefer `python3` by @lhchavez in https://github.com/libgit2/libgit2/pull/5913 * git__timer: Allow compilation on systems without CLOCK_MONOTONIC by @boretrk in https://github.com/libgit2/libgit2/pull/5945 * stdintification: use int64_t and INT64_C instead of long long by @NattyNarwhal in https://github.com/libgit2/libgit2/pull/5941 * Optional stricter allocation checking (for `malloc(0)` cases) by @ethomson in https://github.com/libgit2/libgit2/pull/5951 * Variadic arguments aren't in C89 by @NattyNarwhal in https://github.com/libgit2/libgit2/pull/5948 * Fix typo in general.c by @Crayon2000 in https://github.com/libgit2/libgit2/pull/5954 * common.h: use inline when compiling for C99 and later by @boretrk in https://github.com/libgit2/libgit2/pull/5953 * Fix one memory leak in master by @lhchavez in https://github.com/libgit2/libgit2/pull/5957 * tests: reset odb backend priority by @ethomson in https://github.com/libgit2/libgit2/pull/5961 * cmake: extended futimens checking on macOS by @ethomson in https://github.com/libgit2/libgit2/pull/5962 * amiga: use ';' as path list separator on AmigaOS by @boretrk in https://github.com/libgit2/libgit2/pull/5978 * Respect the force flag on refspecs in git_remote_fetch by @alexjg in https://github.com/libgit2/libgit2/pull/5854 * Fix LIBGIT2_FILENAME not being passed to the resource compiler by @jairbubbles in https://github.com/libgit2/libgit2/pull/5994 * sha1dc: remove conditional for <sys/types.h> by @boretrk in https://github.com/libgit2/libgit2/pull/5997 * openssl: don't fail when we can't customize allocators by @ethomson in https://github.com/libgit2/libgit2/pull/5999 * C11 warnings by @boretrk in https://github.com/libgit2/libgit2/pull/6005 * open: input validation for empty segments in path by @boretrk in https://github.com/libgit2/libgit2/pull/5950 * Introduce GIT_WARN_UNUSED_RESULT by @lhchavez in https://github.com/libgit2/libgit2/pull/5802 * GCC C11 warnings by @boretrk in https://github.com/libgit2/libgit2/pull/6006 * array: check dereference from void * type by @boretrk in https://github.com/libgit2/libgit2/pull/6007 * Homogenize semantics for atomic-related functions by @lhchavez in https://github.com/libgit2/libgit2/pull/5747 * git_array_alloc: return objects of correct type by @boretrk in https://github.com/libgit2/libgit2/pull/6008 * CMake. hash sha1 header has been added. by @lolgear in https://github.com/libgit2/libgit2/pull/6013 * tests: change comments to c89 style by @boretrk in https://github.com/libgit2/libgit2/pull/6015 * Set Host Header to match CONNECT authority target by @lollipopman in https://github.com/libgit2/libgit2/pull/6022 * Fix worktree iteration when repository has no common directory by @kcsaul in https://github.com/libgit2/libgit2/pull/5943 ## Documentation improvements * Update README.md for additional Delphi bindings by @todaysoftware in https://github.com/libgit2/libgit2/pull/5831 * Fix documentation formatting by @punkymaniac in https://github.com/libgit2/libgit2/pull/5850 * docs: fix incorrect comment marker by @tiennou in https://github.com/libgit2/libgit2/pull/5897 * Patch documentation by @punkymaniac in https://github.com/libgit2/libgit2/pull/5903 * Fix misleading doc for `git_index_find` by @arxanas in https://github.com/libgit2/libgit2/pull/5910 * docs: stop mentioning libgit2's "master" branch by @Batchyx in https://github.com/libgit2/libgit2/pull/5925 * docs: fix some missing includes that cause Docurium to error out by @tiennou in https://github.com/libgit2/libgit2/pull/5917 * Patch documentation by @punkymaniac in https://github.com/libgit2/libgit2/pull/5940 ## Development improvements * WIP: .devcontainer: settings for a codespace workflow by @ethomson in https://github.com/libgit2/libgit2/pull/5508 ## CI Improvements * Add a ThreadSanitizer build by @lhchavez in https://github.com/libgit2/libgit2/pull/5597 * ci: more GitHub Actions by @ethomson in https://github.com/libgit2/libgit2/pull/5706 * ci: run coverity in the nightly builds by @ethomson in https://github.com/libgit2/libgit2/pull/5707 * ci: only report main branch in README status by @ethomson in https://github.com/libgit2/libgit2/pull/5708 * Fix the `ENABLE_WERROR=ON` build in Groovy Gorilla (gcc 10.2) by @lhchavez in https://github.com/libgit2/libgit2/pull/5715 * Re-enable the RC4 test by @carlosmn in https://github.com/libgit2/libgit2/pull/4418 * ci: run codeql by @ethomson in https://github.com/libgit2/libgit2/pull/5709 * github-actions: Also rename the main branch here by @lhchavez in https://github.com/libgit2/libgit2/pull/5771 * ci: don't use ninja on macOS by @ethomson in https://github.com/libgit2/libgit2/pull/5780 * ci: use GitHub for storing mingw-w64 build dependency by @ethomson in https://github.com/libgit2/libgit2/pull/5855 * docker: remove the entrypoint by @ethomson in https://github.com/libgit2/libgit2/pull/5980 * http: don't require a password by @ethomson in https://github.com/libgit2/libgit2/pull/5972 * ci: update nightly to use source path by @ethomson in https://github.com/libgit2/libgit2/pull/5989 * ci: add centos 7 and centos 8 by @ethomson in https://github.com/libgit2/libgit2/pull/5992 * ci: update centos builds by @ethomson in https://github.com/libgit2/libgit2/pull/5995 * ci: tag new containers with the latest tag by @ethomson in https://github.com/libgit2/libgit2/pull/6000 ## Dependency updates * ntlm: [ntlmclient](https://github.com/ethomson/ntlmclient) is now v0.9.1 **Full Changelog**: https://github.com/libgit2/libgit2/compare/v1.1.0...v1.2.0 --------------------------------------------------------------------- v1.1 ---- This is release v1.1, "Fernweh". ### Changes or improvements * Our bundled PCRE dependency has been updated to 8.44. * The `refs/remotes/origin/HEAD` file will be created at clone time to point to the origin's default branch. * libgit2 now uses the `__atomic_` intrinsics instead of `__sync_` intrinsics on supported gcc and clang versions. * The `init.defaultBranch` setting is now respected and `master` is no longer the hardcoded as the default branch name. * Patch files that do not contain an `index` line can now be parsed. * Configuration files with multi-line values can now contain quotes split across multiple lines. * Windows clients now attempt to use TLS1.3 when available. * Servers that request an upgrade to a newer HTTP version are silently ignored instead of erroneously failing. * Users can pass `NULL` to the options argument to `git_describe_commit`. * Clones and fetches of very large packfiles now succeeds on 32-bit platforms. * Custom reference database backends can now handle the repository's `HEAD` correctly. * Repositories with a large number of packfiles no longer exhaust the number of file descriptors. * The test framework now supports TAP output when the `-t` flag is specified. * The test framework can now specify an exact match to a test function using a trailing `$`. * All checkout types support `GIT_CHECKOUT_DISABLE_PATHSPEC_MATCH`. * `git_blame` now can ignore whitespace changes using the option `GIT_BLAME_IGNORE_WHITESPACE`. * Several new examples have been created, including an examples for commit, add and push. * Mode changes during rename are now supported in patch application. * `git_checkout_head` now correctly removes untracked files in a subdirectory when the `FORCE | REMOVE_UNTRACKED` options are specified. v1.0.1 ------ This is a bugfix release with the following changes: - Calculating information about renamed files during merges is more efficient because dissimilarity about files is now being cached and no longer needs to be recomputed. - The `git_worktree_prune_init_options` has been correctly restored for backward compatibility. In v1.0 it was incorrectly deprecated with a typo. - The optional ntlmclient dependency now supports NetBSD. - A bug where attempting to stash on a bare repository may have failed has been fixed. - Configuration files that are unreadable due to permissions are now silently ignored, and treated as if they do not exist. This matches git's behavior; previously this case would have been an error. - v4 index files are now correctly written; previously we would read them correctly but would not write the prefix-compression accurately, causing corruption. - A bug where the smart HTTP transport could not read large data packets has been fixed. Previously, fetching from servers like Gerrit, that sent large data packets, would error. --------------------------------------------------------------------- v1.0 ---- This is release v1.0 "Luftschloss", which is the first stabe release of libgit2. The API will stay compatible across all releases of the same major version. This release includes bugfixes only and supersedes v0.99, which will stop being maintained. Both v0.27 and v0.28 stay supported in accordance with our release policy. ### Changes or improvements - CMake was converted to make use of the GNUInstallDirs module for both our pkgconfig and install targets in favor of our custom build options `BIN_INSTALL_DIR`, `LIB_INSTALL_DIR` and `INCLUDE_INSTALL_DIR`. Instead, you can now use CMakes standard variables `CMAKE_INSTALL_BINDIR`, `CMAKE_INSTALL_LIBDIR` and `CMAKE_INSTALL_INCLUDEDIR`. - Some CMake build options accepted either a specific value or a boolean value to disable the option altogether or use automatic detection. We only accepted "ON" or "OFF", but none of the other values CMake recognizes as boolean. This was aligned with CMake's understanding of booleans. - The installed pkgconfig file contained incorrect values for both `libdir` and `includedir` variables. - If using pcre2 for regular expressions, then we incorrectly added "pcre2" instead of "pcre2-8" to our pkgconfig dependencies, which was corrected. - Fixed building the bundled ntlmclient dependency on FreeBSD, OpenBSD and SunOS. - When writing symlinks on Windows, we incorrectly handled relative symlink targets, which was corrected. - When using the HTTP protocol via macOS' SecureTransport implementation, reads could stall at the end of the session and only continue after a timeout of 60 seconds was reached. - The filesystem-based reference callback didn't corectly initialize the backend version. - A segmentation fault was fixed when calling `git_blame_buffer()` for files that were modified and added to the index. - A backwards-incompatible change was introduced when we moved some structures from "git2/credentials.h" into "git2/sys/credentials.h". This was fixed in the case where you do not use hard deprecation. - Improved error handling in various places. v0.99 ----- This is v0.99 "Torschlusspanik". This will be the last minor release before libgit2 v1.0. We expect to only respond to bugs in this release, to stabilize it for next major release. It contains significant refactorings, but is expected to be API-compatible with v0.28.0. ### Changes or improvements * When fetching from an anonymous remote using a URL with authentication information provided in the URL (eg `https://foo:[email protected]/repo`), we would erroneously include the literal URL in the FETCH_HEAD file. We now remove that to match git's behavior. * Some credential structures, enums and values have been renamed: `git_cred` is now `git_credential`. `git_credtype_t` is now `git_credential_t`. Functions and types beginning with `git_cred_` now begin with `git_credential`, and constants beginning with `GIT_CREDTYPE` now begin with `GIT_CREDENTIAL`. The former names are deprecated. * Several function signatures have been changed to return an `int` to indicate error conditions. We encourage you to check them for errors in the standard way. * `git_attr_cache_flush` * `git_error_set_str` * `git_index_name_clear` * `git_index_reuc_clear` * `git_libgit2_version` * `git_mempack_reset` * `git_oid_cpy` * `git_oid_fmt` * `git_oid_fromraw` * `git_oid_nfmt` * `git_oid_pathfmt` * `git_remote_stop` * `git_remote_disconnect` * `git_repository__cleanup` * `git_repository_set_config` * `git_repository_set_index` * `git_repository_set_odb` * `git_repository_set_refdb` * `git_revwalk_reset` * `git_revwalk_simplify_first_parent` * `git_revwalk_sorting` * `git_treebuilder_clear` * `git_treebuilder_filter` * The NTLM and Negotiate authentication mechanisms are now supported when talking to git implementations hosted on Apache or nginx servers. * The `HEAD` symbolic reference can no longer be deleted. * `git_merge_driver_source_repo` no longer returns a `const git_repository *`, it now returns a non-`const` `git_repository *`. * Relative symbolic links are now supported on Windows when `core.symlinks` is enabled. * Servers that provide query parameters with a redirect are now supported. * `git_submodule_sync` will now resolve relative URLs. * When creating git endpoint URLs, double-slashes are no longer used when the given git URL has a trailing slash. * On Windows, a `DllMain` function is no longer included and thread-local storage has moved to fiber-local storage in order to prevent race conditions during shutdown. * The tracing mechanism (`GIT_TRACE`) is now enabled by default and does not need to be explicitly enabled in CMake. * The size of Git objects is now represented by `git_object_size_t` instead of `off_t`. * Binary patches without data can now be parsed. * A configuration snapshot can now be created from another configuration snapshot, not just a "true" configuration object. * The `git_commit_with_signature` API will now ensure that referenced objects exist in the object database. * Stash messages containing newlines will now be replaced with spaces; they will no longer be (erroneously) written to the repository. * `git_commit_create_with_signature` now verifies the commit information to ensure that it points to a valid tree and valid parents. * `git_apply` has an option `GIT_APPLY_CHECK` that will only do a dry-run. The index and working directory will remain unmodified, and application will report if it would have worked. * Patches produced by Mercurial (those that lack some git extended headers) can now be parsed and applied. * Reference locks are obeyed correctly on POSIX platforms, instead of being removed. * Patches with empty new files can now be read and applied. * `git_apply_to_tree` can now correctly apply patches that add new files. * The program data configuration on Windows (`C:\ProgramData\Git\config`) must be owned by an administrator, a system account or the current user to be read. * `git_blob_filtered_content` is now deprecated in favor of `git_blob_filter`. * Configuration files can now be included conditionally using the `onbranch` conditional. * Checkout can now properly create and remove symbolic links to directories on Windows. * Stash no longer recomputes trees when committing a worktree, for improved performance. * Repository templates can now include a `HEAD` file to default the initial default branch. * Some configuration structures, enums and values have been renamed: `git_cvar_map` is now `git_configmap`, `git_cvar_t` is now `git_configmap_t`, `GIT_CVAR_FALSE` is now `GIT_CONFIGMAP_FALSE`, `GIT_CVAR_TRUE` is now `GIT_CONFIGMAP_TRUE`, `GIT_CVAR_INT32` is now `GIT_CONFIGMAP_INT32`, and `GIT_CVAR_STRING` is now `GIT_CONFIGMAP_STRING`. The former names are deprecated. * Repositories can now be created at the root of a Windows drive. * Configuration lookups are now more efficiently cached. * `git_commit_create_with_signature` now supports a `NULL` signature, which will create a commit without adding a signature. * When a repository lacks an `info` "common directory", we will no longer erroneously return `GIT_ENOTFOUND` for all attribute lookups. * Several attribute macros have been renamed: `GIT_ATTR_TRUE` is now `GIT_ATTR_IS_TRUE`, `GIT_ATTR_FALSE` is now `GIT_ATTR_IS_FALSE`, `GIT_ATTR_UNSPECIFIED` is now `GIT_ATTR_IS_UNSPECIFIED`. The attribute enum `git_attr_t` is now `git_attr_value_t` and its values have been renamed: `GIT_ATTR_UNSPECIFIED_T` is now `GIT_ATTR_VALUE_UNSPECIFIED`, `GIT_ATTR_TRUE_T` is now `GIT_ATTR_VALUE_TRUE`, `GIT_ATTR_FALSE_T` is now `GIT_ATTR_VALUE_FALSE`, and `GIT_ATTR_VALUE_T` is now `GIT_ATTR_VALUE_STRING`. The former names are deprecated. * `git_object__size` is now `git_object_size`. The former name is deprecated. * `git_tag_create_frombuffer` is now `git_tag_create_from_buffer`. The former name is deprecated. * Several blob creation functions have been renamed: `git_blob_create_frombuffer` is now named `git_blob_create_from_buffer`, `git_blob_create_fromdisk` is now named `git_blob_create_from_disk`, `git_blob_create_fromworkdir` is now named `git_blob_create_from_workdir`, `git_blob_create_fromstream` is now named `git_blob_create_from_stream`, and `git_blob_create_fromstream_commit` is now named `git_blob_create_from_stream_commit`. The former names are deprecated. * The function `git_oid_iszero` is now named `git_oid_is_zero`. The former name is deprecated. * Pattern matching is now done using `wildmatch` instead of `fnmatch` for compatibility with git. * The option initialization functions suffixed by `init_options` are now suffixed with `options_init`. (For example, `git_checkout_init_options` is now `git_checkout_options_init`.) The former names are deprecated. * NTLM2 authentication is now supported on non-Windows platforms. * The `git_cred_sign_callback` callback is now named `git_cred_sign_cb`. The `git_cred_ssh_interactive_callback` callback is now named `git_cred_ssh_interactive_cb`. * Ignore files now: * honor escaped trailing whitespace. * do not incorrectly negate sibling paths of a negated pattern. * honor rules that stop ignoring files after a wildcard * Attribute files now: * honor leading and trailing whitespace. * treat paths beginning with `\` as absolute only on Windows. * properly handle escaped characters. * stop reading macros defined in subdirectories * The C locale is now correctly used when parsing regular expressions. * The system PCRE2 or PCRE regular expression libraries are now used when `regcomp_l` is not available on the system. If none of these are available on the system, an included version of PCRE is used. * Wildcards in reference specifications are now supported beyond simply a bare wildcard (`*`) for compatibility with git. * When `git_ignore_path_is_ignored` is provided a path with a trailing slash (eg, `dir/`), it will now treat it as a directory for the purposes of ignore matching. * Patches that add or remove a file with a space in the path can now be correctly parsed. * The `git_remote_completion_type` type is now `git_remote_completion_t`. The former name is deprecated. * The `git_odb_backend_malloc` is now `git_odb_backend_data_alloc`. The former name is deprecated. * The `git_transfer_progress_cb` callback is now `git_indexer_progress_cb` and the `git_transfer_progress` structure is now `git_indexer_progress`. The former names are deprecated. * The example projects are now contained in a single `lg2` executable for ease of use. * libgit2 now correctly handles more URLs, such as `http://example.com:/repo.git` (colon but no port), `http://example.com` (no path), and `http://example.com:8080/` (path is /, nonstandard port). * A carefully constructed commit object with a very large number of parents may lead to potential out-of-bounds writes or potential denial of service. * The ProgramData configuration file is always read for compatibility with Git for Windows and Portable Git installations. The ProgramData location is not necessarily writable only by administrators, so we now ensure that the configuration file is owned by the administrator or the current user. ### API additions * The SSH host key now supports SHA-256 when `GIT_CERT_SSH_SHA256` is set. * The diff format option `GIT_DIFF_FORMAT_PATCH_ID` can now be used to emit an output like `git patch-id`. * The `git_apply_options_init` function will initialize a `git_apply_options` structure. * The remote callbacks structure adds a `git_url_resolve_cb` callback that is invoked when connecting to a server, so that applications may edit or replace the URL before connection. * The information about the original `HEAD` in a rebase operation is available with `git_rebase_orig_head_name`. Its ID is available with `git_rebase_orig_head_id`. The `onto` reference name is available with `git_rebase_onto_name` and its ID is available with `git_rebase_onto_id`. * ODB backends can now free backend data when an error occurs during its backend data creation using `git_odb_backend_data_free`. * Options may be specified to `git_repository_foreach_head` to control its behavior: `GIT_REPOSITORY_FOREACH_HEAD_SKIP_REPO` will not skip the main repository's HEAD reference, while `GIT_REPOSITORY_FOREACH_HEAD_SKIP_WORKTREES` will now skip the worktree HEAD references. * The `GIT_OPT_DISABLE_PACK_KEEP_FILE_CHECKS` option can be specified to `git_libgit2_opts()` to avoid looking for `.keep` files that correspond to packfiles. This setting can improve performance when packfiles are stored on high-latency filesystems like network filesystems. * Blobs can now be filtered with `git_blob_filter`, which allows for options to be set with `git_blob_filter_options`, including `GIT_FILTER_NO_SYSTEM_ATTRIBUTES` to disable filtering with system-level attributes in `/etc/gitattributes` and `GIT_ATTR_CHECK_INCLUDE_HEAD` to enable filtering with `.gitattributes` files in the HEAD revision. ### API removals * The unused `git_headlist_cb` function declaration was removed. * The unused `git_time_monotonic` API is removed. * The erroneously exported `inttypes.h` header was removed. # Security Fixes - CVE-2019-1348: the fast-import stream command "feature export-marks=path" allows writing to arbitrary file paths. As libgit2 does not offer any interface for fast-import, it is not susceptible to this vulnerability. - CVE-2019-1349: by using NTFS 8.3 short names, backslashes or alternate filesystreams, it is possible to cause submodules to be written into pre-existing directories during a recursive clone using git. As libgit2 rejects cloning into non-empty directories by default, it is not susceptible to this vulnerability. - CVE-2019-1350: recursive clones may lead to arbitrary remote code executing due to improper quoting of command line arguments. As libgit2 uses libssh2, which does not require us to perform command line parsing, it is not susceptible to this vulnerability. - CVE-2019-1351: Windows provides the ability to substitute drive letters with arbitrary letters, including multi-byte Unicode letters. To fix any potential issues arising from interpreting such paths as relative paths, we have extended detection of DOS drive prefixes to accomodate for such cases. - CVE-2019-1352: by using NTFS-style alternative file streams for the ".git" directory, it is possible to overwrite parts of the repository. While this has been fixed in the past for Windows, the same vulnerability may also exist on other systems that write to NTFS filesystems. We now reject any paths starting with ".git:" on all systems. - CVE-2019-1353: by using NTFS-style 8.3 short names, it was possible to write to the ".git" directory and thus overwrite parts of the repository, leading to possible remote code execution. While this problem was already fixed in the past for Windows, other systems accessing NTFS filesystems are vulnerable to this issue too. We now enable NTFS protecions by default on all systems to fix this attack vector. - CVE-2019-1354: on Windows, backslashes are not a valid part of a filename but are instead interpreted as directory separators. As other platforms allowed to use such paths, it was possible to write such invalid entries into a Git repository and was thus an attack vector to write into the ".git" dierctory. We now reject any entries starting with ".git\" on all systems. - CVE-2019-1387: it is possible to let a submodule's git directory point into a sibling's submodule directory, which may result in overwriting parts of the Git repository and thus lead to arbitrary command execution. As libgit2 doesn't provide any way to do submodule clones natively, it is not susceptible to this vulnerability. Users of libgit2 that have implemented recursive submodule clones manually are encouraged to review their implementation for this vulnerability. ### Breaking API changes * The "private" implementation details of the `git_cred` structure have been moved to a dedicated `git2/sys/cred.h` header, to clarify that the underlying structures are only provided for custom transport implementers. The breaking change is that the `username` member of the underlying struct is now hidden, and a new `git_cred_get_username` function has been provided. * Some errors of class `GIT_ERROR_NET` now have class `GIT_ERROR_HTTP`. Most authentication failures now have error code `GIT_EAUTH` instead of `GIT_ERROR`. ### Breaking CMake configuration changes * The CMake option to use a system http-parser library, instead of the bundled dependency, has changed. This is due to a deficiency in http-parser that we have fixed in our implementation. The bundled library is now the default, but if you wish to force the use of the system http-parser implementation despite incompatibilities, you can specify `-DUSE_HTTP_PARSER=system` to CMake. * The interactions between `USE_HTTPS` and `SHA1_BACKEND` have been streamlined. The detection was moved to a new `USE_SHA1`, modeled after `USE_HTTPS`, which takes the values "CollisionDetection/Backend/Generic", to better match how the "hashing backend" is selected, the default (ON) being "CollisionDetection". If you were using `SHA1_BACKEND` previously, you'll need to check the value you've used, or switch to the autodetection. ### Authors The following individuals provided changes that were included in this release: * Aaron Patterson * Alberto Fanjul * Anders Borum * Augie Fackler * Augustin Fabre * Ayush Shridhar * brian m. carlson * buddyspike * Carlos Martín Nieto * cheese1 * Dan Skorupski * Daniel Cohen Gindi * Dave Lee * David Brooks * David Turner * Denis Laxalde * Dhruva Krishnamurthy * Dominik Ritter * Drew DeVault * Edward Thomson * Eric Huss * Erik Aigner * Etienne Samson * Gregory Herrero * Heiko Voigt * Ian Hattendorf * Jacques Germishuys * Janardhan Pulivarthi * Jason Haslam * Johannes Schindelin * Jordan Wallet * Josh Bleecher Snyder * kas * kdj0c * Laurence McGlashan * lhchavez * Lukas Berk * Max Kostyukevich * Patrick Steinhardt * pcpthm * Remy Suen * Robert Coup * romkatv * Scott Furry * Sebastian Henke * Stefan Widgren * Steve King Jr * Sven Strickroth * Tobias Nießen * Tyler Ang-Wanek * Tyler Wanek --------------------------------------------------------------------- v0.28 ----- ### Changes or improvements * The library is now always built with cdecl calling conventions on Windows; the ability to build a stdcall library has been removed. * Reference log creation now honors `core.logallrefupdates=always`. * Fix some issues with the error-reporting in the OpenSSL backend. * HTTP proxy support is now builtin; libcurl is no longer used to support proxies and is removed as a dependency. * Certificate and credential callbacks can now return `GIT_PASSTHROUGH` to decline to act; libgit2 will behave as if there was no callback set in the first place. * The line-ending filtering logic - when checking out files - has been updated to match newer git (>= git 2.9) for proper interoperability. * Symbolic links are now supported on Windows when `core.symlinks` is set to `true`. * Submodules with names which attempt to perform path traversal now have their configuration ignored. Such names were blindly appended to the `$GIT_DIR/modules` and a malicious name could lead to an attacker writing to an arbitrary location. This matches git's handling of CVE-2018-11235. * Object validation is now performed during tree creation in the `git_index_write_tree_to` API. * Configuration variable may now be specified on the same line as a section header; previously this was erroneously a parser error. * When an HTTP server supports both NTLM and Negotiate authentication mechanisms, we would previously fail to authenticate with any mechanism. * The `GIT_OPT_SET_PACK_MAX_OBJECTS` option can now set the maximum number of objects allowed in a packfile being downloaded; this can help limit the maximum memory used when fetching from an untrusted remote. * Line numbers in diffs loaded from patch files were not being populated; they are now included in the results. * The repository's index is reloaded from disk at the beginning of `git_merge` operations to ensure that it is up-to-date. * Mailmap handling APIs have been introduced, and the new commit APIs `git_commit_committer_with_mailmap` and `git_commit_author_with_mailmap` will use the mailmap to resolve the committer and author information. In addition, blame will use the mailmap given when the `GIT_BLAME_USE_MAILMAP` option. * Ignore handling for files in ignored folders would be ignored. * Worktrees can now be backed by bare repositories. * Trailing spaces are supported in `.gitignore` files, these spaces were previously (and erroneously) treated as part of the pattern. * The library can now be built with mbedTLS support for HTTPS. * The diff status character 'T' will now be presented by the `git_diff_status_char` API for diff entries that change type. * Revision walks previously would sometimes include commits that should have been ignored; this is corrected. * Revision walks are now more efficient when the output is unsorted; we now avoid walking all the way to the beginning of history unnecessarily. * Error-handling around index extension loading has been fixed. We were previously always misreporting a truncated index (#4858). ### API additions * The index may now be iterated atomically using `git_index_iterator`. * Remote objects can now be created with extended options using the `git_remote_create_with_opts` API. * Diff objects can now be applied as changes to the working directory, index or both, emulating the `git apply` command. Additionally, `git_apply_to_tree` can apply those changes to a tree object as a fully in-memory operation. * You can now swap out memory allocators via the `GIT_OPT_SET_ALLOCATOR` option with `git_libgit2_opts()`. * You can now ensure that functions do not discard unwritten changes to the index via the `GIT_OPT_ENABLE_UNSAVED_INDEX_SAFETY` option to `git_libgit2_opts()`. This will cause functions that implicitly re-read the index (eg, `git_checkout`) to fail if you have staged changes to the index but you have not written the index to disk. (Unless the checkout has the FORCE flag specified.) At present, this defaults to off, but we intend to enable this more broadly in the future, as a warning or error. We encourage you to examine your code to ensure that you are not relying on the current behavior that implicitly removes staged changes. * Reference specifications can be parsed from an arbitrary string with the `git_refspec_parse` API. * You can now get the name and path of worktrees using the `git_worktree_name` and `git_worktree_path` APIs, respectively. * The `ref` field has been added to `git_worktree_add_options` to enable the creation of a worktree from a pre-existing branch. * It's now possible to analyze merge relationships between any two references, not just against `HEAD`, using `git_merge_analysis_for_ref`. ### API removals * The `git_buf_free` API is deprecated; it has been renamed to `git_buf_dispose` for consistency. The `git_buf_free` API will be retained for backward compatibility for the foreseeable future. * The `git_otype` enumeration and its members are deprecated and have been renamed for consistency. The `GIT_OBJ_` enumeration values are now prefixed with `GIT_OBJECT_`. The old enumerations and macros will be retained for backward compatibility for the foreseeable future. * Several index-related APIs have been renamed for consistency. The `GIT_IDXENTRY_` enumeration values and macros have been renamed to be prefixed with `GIT_INDEX_ENTRY_`. The `GIT_INDEXCAP` enumeration values are now prefixed with `GIT_INDEX_CAPABILITY_`. The old enumerations and macros will be retained for backward compatibility for the foreseeable future. * The error functions and enumeration values have been renamed for consistency. The `giterr_` functions and values prefix have been renamed to be prefixed with `git_error_`; similarly, the `GITERR_` constants have been renamed to be prefixed with `GIT_ERROR_`. The old enumerations and macros will be retained for backward compatibility for the foreseeable future. ### Breaking API changes * The default checkout strategy changed from `DRY_RUN` to `SAFE` (#4531). * Adding a symlink as .gitmodules into the index from the workdir or checking out such files is not allowed as this can make a Git implementation write outside of the repository and bypass the fsck checks for CVE-2018-11235. --------------------------------------------------------------------- v0.27 --------- ### Changes or improvements * Improved `p_unlink` in `posix_w32.c` to try and make a file writable before sleeping in the retry loop to prevent unnecessary calls to sleep. * The CMake build infrastructure has been improved to speed up building time. * A new CMake option "-DUSE_HTTPS=<backend>" makes it possible to explicitly choose an HTTP backend. * A new CMake option "-DSHA1_BACKEND=<backend>" makes it possible to explicitly choose an SHA1 backend. The collision-detecting backend is now the default. * A new CMake option "-DUSE_BUNDLED_ZLIB" makes it possible to explicitly use the bundled zlib library. * A new CMake option "-DENABLE_REPRODUCIBLE_BUILDS" makes it possible to generate a reproducible static archive. This requires support from your toolchain. * The minimum required CMake version has been bumped to 2.8.11. * Writing to a configuration file now preserves the case of the key given by the caller for the case-insensitive portions of the key (existing sections are used even if they don't match). * We now support conditional includes in configuration files. * Fix for handling re-reading of configuration files with includes. * Fix for reading patches which contain exact renames only. * Fix for reading patches with whitespace in the compared files' paths. * We will now fill `FETCH_HEAD` from all passed refspecs instead of overwriting with the last one. * There is a new diff option, `GIT_DIFF_INDENT_HEURISTIC` which activates a heuristic which takes into account whitespace and indentation in order to produce better diffs when dealing with ambiguous diff hunks. * Fix for pattern-based ignore rules where files ignored by a rule cannot be un-ignored by another rule. * Sockets opened by libgit2 are now being closed on exec(3) if the platform supports it. * Fix for peeling annotated tags from packed-refs files. * Fix reading huge loose objects from the object database. * Fix files not being treated as modified when only the file mode has changed. * We now explicitly reject adding submodules to the index via `git_index_add_frombuffer`. * Fix handling of `GIT_DIFF_FIND_RENAMES_FROM_REWRITES` raising `SIGABRT` when one file has been deleted and another file has been rewritten. * Fix for WinHTTP not properly handling NTLM and Negotiate challenges. * When using SSH-based transports, we now repeatedly ask for the passphrase to decrypt the private key in case a wrong passphrase is being provided. * When generating conflict markers, they will now use the same line endings as the rest of the file. ### API additions * The `git_merge_file_options` structure now contains a new setting, `marker_size`. This allows users to set the size of markers that delineate the sides of merged files in the output conflict file. By default this is 7 (`GIT_MERGE_CONFLICT_MARKER_SIZE`), which produces output markers like `<<<<<<<` and `>>>>>>>`. * `git_remote_create_detached()` creates a remote that is not associated to any repository (and does not apply configuration like 'insteadof' rules). This is mostly useful for e.g. emulating `git ls-remote` behavior. * `git_diff_patchid()` lets you generate patch IDs for diffs. * `git_status_options` now has an additional field `baseline` to allow creating status lists against different trees. * New family of functions to allow creating notes for a specific notes commit instead of for a notes reference. * New family of functions to allow parsing message trailers. This API is still experimental and may change in future releases. ### API removals ### Breaking API changes * Signatures now distinguish between +0000 and -0000 UTC offsets. * The certificate check callback in the WinHTTP transport will now receive the `message_cb_payload` instead of the `cred_acquire_payload`. * We are now reading symlinked directories under .git/refs. * We now refuse creating branches named "HEAD". * We now refuse reading and writing all-zero object IDs into the object database. * We now read the effective user's configuration file instead of the real user's configuration in case libgit2 runs as part of a setuid binary. * The `git_odb_open_rstream` function and its `readstream` callback in the `git_odb_backend` interface have changed their signatures to allow providing the object's size and type to the caller. --------------------------------------------------------------------- v0.26 ----- ### Changes or improvements * Support for opening, creating and modifying worktrees. * We can now detect SHA1 collisions resulting from the SHAttered attack. These checks can be enabled at build time via `-DUSE_SHA1DC`. * Fix for missing implementation of `git_merge_driver_source` getters. * Fix for installed pkg-config file being broken when the prefix contains spaces. * We now detect when the hashsum of on-disk objects does not match their expected hashsum. * We now support open-ended ranges (e.g. "master..", "...master") in our revision range parsing code. * We now correctly compute ignores with leading "/" in subdirectories. * We now optionally call `fsync` on loose objects, packfiles and their indexes, loose references and packed reference files. * We can now build against OpenSSL v1.1 and against LibreSSL. * `GIT_MERGE_OPTIONS_INIT` now includes a setting to perform rename detection. This aligns this structure with the default by `git_merge` and `git_merge_trees` when `NULL` was provided for the options. * Improvements for reading index v4 files. * Perform additional retries for filesystem operations on Windows when files are temporarily locked by other processes. ### API additions * New family of functions to handle worktrees: * `git_worktree_list()` lets you look up worktrees for a repository. * `git_worktree_lookup()` lets you get a specific worktree. * `git_worktree_open_from_repository()` lets you get the associated worktree of a repository. a worktree. * `git_worktree_add` lets you create new worktrees. * `git_worktree_prune` lets you remove worktrees from disk. * `git_worktree_lock()` and `git_worktree_unlock()` let you lock respectively unlock a worktree. * `git_repository_open_from_worktree()` lets you open a repository via * `git_repository_head_for_worktree()` lets you get the current `HEAD` for a linked worktree. * `git_repository_head_detached_for_worktree()` lets you check whether a linked worktree is in detached HEAD mode. * `git_repository_item_path()` lets you retrieve paths for various repository files. * `git_repository_commondir()` lets you retrieve the common directory of a repository. * `git_branch_is_checked_out()` allows you to check whether a branch is checked out in a repository or any of its worktrees. * `git_repository_submodule_cache_all()` and `git_repository_submodule_cache_clear()` functions allow you to prime or clear the submodule cache of a repository. * You can disable strict hash verifications via the `GIT_OPT_ENABLE_STRICT_HASH_VERIFICATION` option with `git_libgit2_opts()`. * You can enable us calling `fsync` for various files inside the ".git" directory by setting the `GIT_OPT_ENABLE_FSYNC_GITDIR` option with `git_libgit2_opts()`. * You can now enable "offset deltas" when creating packfiles and negotiating packfiles with a remote server by setting `GIT_OPT_ENABLE_OFS_DELTA` option with `GIT_libgit2_opts()`. * You can now set the default share mode on Windows for opening files using `GIT_OPT_SET_WINDOWS_SHAREMODE` option with `git_libgit2_opts()`. You can query the current share mode with `GIT_OPT_GET_WINDOWS_SHAREMODE`. * `git_transport_smart_proxy_options()' enables you to get the proxy options for smart transports. * The `GIT_FILTER_INIT` macro and the `git_filter_init` function are provided to initialize a `git_filter` structure. ### Breaking API changes * `clone_checkout_strategy` has been removed from `git_submodule_update_option`. The checkout strategy used to clone will be the same strategy specified in `checkout_opts`. v0.25 ------- ### Changes or improvements * Fix repository discovery with `git_repository_discover` and `git_repository_open_ext` to match git's handling of a ceiling directory at the current directory. git only checks ceiling directories when its search ascends to a parent directory. A ceiling directory matching the starting directory will not prevent git from finding a repository in the starting directory or a parent directory. * Do not fail when deleting remotes in the presence of broken global configs which contain branches. * Support for reading and writing git index v4 files * Improve the performance of the revwalk and bring us closer to git's code. * The reference db has improved support for concurrency and returns `GIT_ELOCKED` when an operation could not be performed due to locking. * Nanosecond resolution is now activated by default, following git's change to do this. * We now restrict the set of ciphers we let OpenSSL use by default. * Users can now register their own merge drivers for use with `.gitattributes`. The library also gained built-in support for the union merge driver. * The default for creating references is now to validate that the object does exist. * Add `git_proxy_options` which is used by the different networking implementations to let the caller specify the proxy settings instead of relying on the environment variables. ### API additions * You can now get the user-agent used by libgit2 using the `GIT_OPT_GET_USER_AGENT` option with `git_libgit2_opts()`. It is the counterpart to `GIT_OPT_SET_USER_AGENT`. * The `GIT_OPT_SET_SSL_CIPHERS` option for `git_libgit2_opts()` lets you specify a custom list of ciphers to use for OpenSSL. * `git_commit_create_buffer()` creates a commit and writes it into a user-provided buffer instead of writing it into the object db. Combine it with `git_commit_create_with_signature()` in order to create a commit with a cryptographic signature. * `git_blob_create_fromstream()` and `git_blob_create_fromstream_commit()` allow you to create a blob by writing into a stream. Useful when you do not know the final size or want to copy the contents from another stream. * New flags for `git_repository_open_ext`: * `GIT_REPOSITORY_OPEN_NO_DOTGIT` - Do not check for a repository by appending `/.git` to the `start_path`; only open the repository if `start_path` itself points to the git directory. * `GIT_REPOSITORY_OPEN_FROM_ENV` - Find and open a git repository, respecting the environment variables used by the git command-line tools. If set, `git_repository_open_ext` will ignore the other flags and the `ceiling_dirs` argument, and will allow a NULL `path` to use `GIT_DIR` or search from the current directory. The search for a repository will respect `$GIT_CEILING_DIRECTORIES` and `$GIT_DISCOVERY_ACROSS_FILESYSTEM`. The opened repository will respect `$GIT_INDEX_FILE`, `$GIT_NAMESPACE`, `$GIT_OBJECT_DIRECTORY`, and `$GIT_ALTERNATE_OBJECT_DIRECTORIES`. In the future, this flag will also cause `git_repository_open_ext` to respect `$GIT_WORK_TREE` and `$GIT_COMMON_DIR`; currently, `git_repository_open_ext` with this flag will error out if either `$GIT_WORK_TREE` or `$GIT_COMMON_DIR` is set. * `git_diff_from_buffer()` can create a `git_diff` object from the contents of a git-style patch file. * `git_index_version()` and `git_index_set_version()` to get and set the index version * `git_odb_expand_ids()` lets you check for the existence of multiple objects at once. * The new `git_blob_dup()`, `git_commit_dup()`, `git_tag_dup()` and `git_tree_dup()` functions provide type-specific wrappers for `git_object_dup()` to reduce noise and increase type safety for callers. * `git_reference_dup()` lets you duplicate a reference to aid in ownership management and cleanup. * `git_signature_from_buffer()` lets you create a signature from a string in the format that appear in objects. * `git_tree_create_updated()` lets you create a tree based on another one together with a list of updates. For the covered update cases, it's more efficient than the `git_index` route. * `git_apply_patch()` applies hunks from a `git_patch` to a buffer. * `git_diff_to_buf()` lets you print an entire diff directory to a buffer, similar to how `git_patch_to_buf()` works. * `git_proxy_init_options()` is added to initialize a `git_proxy_options` structure at run-time. * `git_merge_driver_register()`, `git_merge_driver_unregister()` let you register and unregister a custom merge driver to be used when `.gitattributes` specifies it. * `git_merge_driver_lookup()` can be used to look up a merge driver by name. * `git_merge_driver_source_repo()`, `git_merge_driver_source_ancestor()`, `git_merge_driver_source_ours()`, `git_merge_driver_source_theirs()`, `git_merge_driver_source_file_options()` added as accessors to `git_merge_driver_source`. ### API removals * `git_blob_create_fromchunks()` has been removed in favour of `git_blob_create_fromstream()`. ### Breaking API changes * `git_packbuilder_object_count` and `git_packbuilder_written` now return a `size_t` instead of a `uint32_t` for more thorough compatibility with the rest of the library. * `git_packbuiler_progress` now provides explicitly sized `uint32_t` values instead of `unsigned int`. * `git_diff_file` now includes an `id_abbrev` field that reflects the number of nibbles set in the `id` field. * `git_odb_backend` now has a `freshen` function pointer. This optional function pointer is similar to the `exists` function, but it will update a last-used marker. For filesystem-based object databases, this updates the timestamp of the file containing the object, to indicate "freshness". If this is `NULL`, then it will not be called and the `exists` function will be used instead. * `git_remote_connect()` now accepts `git_proxy_options` argument, and `git_fetch_options` and `git_push_options` each have a `proxy_opts` field. * `git_merge_options` now provides a `default_driver` that can be used to provide the name of a merge driver to be used to handle files changed during a merge. --------------------------------------------------------------------- v0.24 ------- ### Changes or improvements * Custom merge drivers can now be registered, which allows callers to configure callbacks to honor `merge=driver` configuration in `.gitattributes`. * Custom filters can now be registered with wildcard attributes, for example `filter=*`. Consumers should examine the attributes parameter of the `check` function for details. * Symlinks are now followed when locking a file, which can be necessary when multiple worktrees share a base repository. * You can now set your own user-agent to be sent for HTTP requests by using the `GIT_OPT_SET_USER_AGENT` with `git_libgit2_opts()`. * You can set custom HTTP header fields to be sent along with requests by passing them in the fetch and push options. * Tree objects are now assumed to be sorted. If a tree is not correctly formed, it will give bad results. This is the git approach and cuts a significant amount of time when reading the trees. * Filter registration is now protected against concurrent registration. * Filenames which are not valid on Windows in an index no longer cause to fail to parse it on that OS. * Rebases can now be performed purely in-memory, without touching the repository's workdir. * When adding objects to the index, or when creating new tree or commit objects, the inputs are validated to ensure that the dependent objects exist and are of the correct type. This object validation can be disabled with the GIT_OPT_ENABLE_STRICT_OBJECT_CREATION option. * The WinHTTP transport's handling of bad credentials now behaves like the others, asking for credentials again. ### API additions * `git_config_lock()` has been added, which allow for transactional/atomic complex updates to the configuration, removing the opportunity for concurrent operations and not committing any changes until the unlock. * `git_diff_options` added a new callback `progress_cb` to report on the progress of the diff as files are being compared. The documentation of the existing callback `notify_cb` was updated to reflect that it only gets called when new deltas are added to the diff. * `git_fetch_options` and `git_push_options` have gained a `custom_headers` field to set the extra HTTP header fields to send. * `git_stream_register_tls()` lets you register a callback to be used as the constructor for a TLS stream instead of the libgit2 built-in one. * `git_commit_header_field()` allows you to look up a specific header field in a commit. * `git_commit_extract_signature()` extracts the signature from a commit and gives you both the signature and the signed data so you can verify it. ### API removals * No APIs were removed in this version. ### Breaking API changes * The `git_merge_tree_flag_t` is now `git_merge_flag_t`. Subsequently, its members are no longer prefixed with `GIT_MERGE_TREE_FLAG` but are now prefixed with `GIT_MERGE_FLAG`, and the `tree_flags` field of the `git_merge_options` structure is now named `flags`. * The `git_merge_file_flags_t` enum is now `git_merge_file_flag_t` for consistency with other enum type names. * `git_cert` descendent types now have a proper `parent` member * It is the responsibility of the refdb backend to decide what to do with the reflog on ref deletion. The file-based backend must delete it, a database-backed one may wish to archive it. * `git_config_backend` has gained two entries. `lock` and `unlock` with which to implement the transactional/atomic semantics for the configuration backend. * `git_index_add` and `git_index_conflict_add()` will now use the case as provided by the caller on case insensitive systems. Previous versions would keep the case as it existed in the index. This does not affect the higher-level `git_index_add_bypath` or `git_index_add_frombuffer` functions. * The `notify_payload` field of `git_diff_options` was renamed to `payload` to reflect that it's also the payload for the new progress callback. * The `git_config_level_t` enum has gained a higher-priority value `GIT_CONFIG_LEVEL_PROGRAMDATA` which represent a rough Windows equivalent to the system level configuration. * `git_rebase_options` now has a `merge_options` field. * The index no longer performs locking itself. This is not something users of the library should have been relying on as it's not part of the concurrency guarantees. * `git_remote_connect()` now takes a `custom_headers` argument to set the extra HTTP header fields to send. --------------------------------------------------------------------- v0.23 ------ ### Changes or improvements * Patience and minimal diff drivers can now be used for merges. * Merges can now ignore whitespace changes. * Updated binary identification in CRLF filtering to avoid false positives in UTF-8 files. * Rename and copy detection is enabled for small files. * Checkout can now handle an initial checkout of a repository, making `GIT_CHECKOUT_SAFE_CREATE` unnecessary for users of clone. * The signature parameter in the ref-modifying functions has been removed. Use `git_repository_set_ident()` and `git_repository_ident()` to override the signature to be used. * The local transport now auto-scales the number of threads to use when creating the packfile instead of sticking to one. * Reference renaming now uses the right id for the old value. * The annotated version of branch creation, HEAD detaching and reset allow for specifying the expression from the user to be put into the reflog. * `git_rebase_commit` now returns `GIT_EUNMERGED` when you attempt to commit with unstaged changes. * On Mac OS X, we now use SecureTransport to provide the cryptographic support for HTTPS connections insead of OpenSSL. * Checkout can now accept an index for the baseline computations via the `baseline_index` member. * The configuration for fetching is no longer stored inside the `git_remote` struct but has been moved to a `git_fetch_options`. The remote functions now take these options or the callbacks instead of setting them beforehand. * `git_submodule` instances are no longer cached or shared across lookup. Each submodule represents the configuration at the time of loading. * The index now uses diffs for `add_all()` and `update_all()` which gives it a speed boost and closer semantics to git. * The ssh transport now reports the stderr output from the server as the error message, which allows you to get the "repository not found" messages. * `git_index_conflict_add()` will remove staged entries that exist for conflicted paths. * The flags for a `git_diff_file` will now have the `GIT_DIFF_FLAG_EXISTS` bit set when a file exists on that side of the diff. This is useful for understanding whether a side of the diff exists in the presence of a conflict. * The constructor for a write-stream into the odb now takes `git_off_t` instead of `size_t` for the size of the blob, which allows putting large files into the odb on 32-bit systems. * The remote's push and pull URLs now honor the url.$URL.insteadOf configuration. This allows modifying URL prefixes to a custom value via gitconfig. * `git_diff_foreach`, `git_diff_blobs`, `git_diff_blob_to_buffer`, and `git_diff_buffers` now accept a new binary callback of type `git_diff_binary_cb` that includes the binary diff information. * The race condition mitigations described in `racy-git.txt` have been implemented. * If libcurl is installed, we will use it to connect to HTTP(S) servers. ### API additions * The `git_merge_options` gained a `file_flags` member. * Parsing and retrieving a configuration value as a path is exposed via `git_config_parse_path()` and `git_config_get_path()` respectively. * `git_repository_set_ident()` and `git_repository_ident()` serve to set and query which identity will be used when writing to the reflog. * `git_config_entry_free()` frees a config entry. * `git_config_get_string_buf()` provides a way to safely retrieve a string from a non-snapshot configuration. * `git_annotated_commit_from_revspec()` allows to get an annotated commit from an extended sha synatx string. * `git_repository_set_head_detached_from_annotated()`, `git_branch_create_from_annotated()` and `git_reset_from_annotated()` allow for the caller to provide an annotated commit through which they can control what expression is put into the reflog as the source/target. * `git_index_add_frombuffer()` can now create a blob from memory buffer and add it to the index which is attached to a repository. * The structure `git_fetch_options` has been added to determine the runtime configuration for fetching, such as callbacks, pruning and autotag behaviour. It has the runtime initializer `git_fetch_init_options()`. * The enum `git_fetch_prune_t` has been added, letting you specify the pruning behaviour for a fetch. * A push operation will notify the caller of what updates it indends to perform on the remote, which provides similar information to git's pre-push hook. * `git_stash_apply()` can now apply a stashed state from the stash list, placing the data into the working directory and index. * `git_stash_pop()` will apply a stashed state (like `git_stash_apply()`) but will remove the stashed state after a successful application. * A new error code `GIT_EEOF` indicates an early EOF from the server. This typically indicates an error with the URL or configuration of the server, and tools can use this to show messages about failing to communicate with the server. * A new error code `GIT_EINVALID` indicates that an argument to a function is invalid, or an invalid operation was requested. * `git_diff_index_to_workdir()` and `git_diff_tree_to_index()` will now produce deltas of type `GIT_DELTA_CONFLICTED` to indicate that the index side of the delta is a conflict. * The `git_status` family of functions will now produce status of type `GIT_STATUS_CONFLICTED` to indicate that a conflict exists for that file in the index. * `git_index_entry_is_conflict()` is a utility function to determine if a given index entry has a non-zero stage entry, indicating that it is one side of a conflict. * It is now possible to pass a keypair via a buffer instead of a path. For this, `GIT_CREDTYPE_SSH_MEMORY` and `git_cred_ssh_key_memory_new()` have been added. * `git_filter_list_contains` will indicate whether a particular filter will be run in the given filter list. * `git_commit_header_field()` has been added, which allows retrieving the contents of an arbitrary header field. * `git_submodule_set_branch()` allows to set the configured branch for a submodule. ### API removals * `git_remote_save()` and `git_remote_clear_refspecs()` have been removed. Remote's configuration is changed via the configuration directly or through a convenience function which performs changes to the configuration directly. * `git_remote_set_callbacks()`, `git_remote_get_callbacks()` and `git_remote_set_transport()` have been removed and the remote no longer stores this configuration. * `git_remote_set_fetch_refpecs()` and `git_remote_set_push_refspecs()` have been removed. There is no longer a way to set the base refspecs at run-time. * `git_submodule_save()` has been removed. The submodules are no longer configured via the objects. * `git_submodule_reload_all()` has been removed as we no longer cache submodules. ### Breaking API changes * `git_smart_subtransport_cb` now has a `param` parameter. * The `git_merge_options` structure member `flags` has been renamed to `tree_flags`. * The `git_merge_file_options` structure member `flags` is now an unsigned int. It was previously a `git_merge_file_flags_t`. * `GIT_CHECKOUT_SAFE_CREATE` has been removed. Most users will generally be able to switch to `GIT_CHECKOUT_SAFE`, but if you require missing file handling during checkout, you may now use `GIT_CHECKOUT_SAFE | GIT_CHECKOUT_RECREATE_MISSING`. * The `git_clone_options` and `git_submodule_update_options` structures no longer have a `signature` field. * The following functions have removed the signature and/or log message parameters in favour of git-emulating ones. * `git_branch_create()`, `git_branch_move()` * `git_rebase_init()`, `git_rebase_abort()` * `git_reference_symbolic_create_matching()`, `git_reference_symbolic_create()`, `git_reference_create()`, `git_reference_create_matching()`, `git_reference_symbolic_set_target()`, `git_reference_set_target()`, `git_reference_rename()` * `git_remote_update_tips()`, `git_remote_fetch()`, `git_remote_push()` * `git_repository_set_head()`, `git_repository_set_head_detached()`, `git_repository_detach_head()` * `git_reset()` * `git_config_get_entry()` now gives back a ref-counted `git_config_entry`. You must free it when you no longer need it. * `git_config_get_string()` will return an error if used on a non-snapshot configuration, as there can be no guarantee that the returned pointer is valid. * `git_note_default_ref()` now uses a `git_buf` to return the string, as the string is otherwise not guaranteed to stay allocated. * `git_rebase_operation_current()` will return `GIT_REBASE_NO_OPERATION` if it is called immediately after creating a rebase session but before you have applied the first patch. * `git_rebase_options` now contains a `git_checkout_options` struct that will be used for functions that modify the working directory, namely `git_rebase_init`, `git_rebase_next` and `git_rebase_abort`. As a result, `git_rebase_open` now also takes a `git_rebase_options` and only the `git_rebase_init` and `git_rebase_open` functions take a `git_rebase_options`, where they will persist the options to subsequent `git_rebase` calls. * The `git_clone_options` struct now has fetch options in a `fetch_opts` field instead of remote callbacks in `remote_callbacks`. * The remote callbacks has gained a new member `push_negotiation` which gets called before sending the update commands to the server. * The following functions no longer act on a remote instance but change the repository's configuration. Their signatures have changed accordingly: * `git_remote_set_url()`, `git_remote_seturl()` * `git_remote_add_fetch()`, `git_remote_add_push()` and * `git_remote_set_autotag()` * `git_remote_connect()` and `git_remote_prune()` now take a pointer to the callbacks. * `git_remote_fetch()` and `git_remote_download()` now take a pointer to fetch options which determine the runtime configuration. * The `git_remote_autotag_option_t` values have been changed. It has gained a `_UNSPECIFIED` default value to specify no override for the configured setting. * `git_remote_update_tips()` now takes a pointer to the callbacks as well as a boolean whether to write `FETCH_HEAD` and the autotag setting. * `git_remote_create_anonymous()` no longer takes a fetch refspec as url-only remotes cannot have configured refspecs. * The `git_submodule_update_options` struct now has fetch options in the `fetch_opts` field instead of callbacks in the `remote_callbacks` field. * The following functions no longer act on a submodule instance but change the repository's configuration. Their signatures have changed accordingly: * `git_submodule_set_url()`, `git_submodule_set_ignore()`, `git_submodule_set_update()`, `git_submodule_set_fetch_recurse_submodules()`. * `git_submodule_status()` no longer takes a submodule instance but a repsitory, a submodule name and an ignore setting. * The `push` function in the `git_transport` interface now takes a pointer to the remote callbacks. * The `git_index_entry` struct's fields' types have been changed to more accurately reflect what is in fact stored in the index. Specifically, time and file size are 32 bits intead of 64, as these values are truncated. * `GIT_EMERGECONFLICT` is now `GIT_ECONFLICT`, which more accurately describes the nature of the error. * It is no longer allowed to call `git_buf_grow()` on buffers borrowing the memory they point to. --------------------------------------------------------------------- v0.22 ------ ### Changes or improvements * `git_signature_new()` now requires a non-empty email address. * Use CommonCrypto libraries for SHA-1 calculation on Mac OS X. * Disable SSL compression and SSLv2 and SSLv3 ciphers in favor of TLSv1 in OpenSSL. * The fetch behavior of remotes with autotag set to `GIT_REMOTE_DOWNLOAD_TAGS_ALL` has been changed to match git 1.9.0 and later. In this mode, libgit2 now fetches all tags in addition to whatever else needs to be fetched. * `git_checkout()` now handles case-changing renames correctly on case-insensitive filesystems; for example renaming "readme" to "README". * The search for libssh2 is now done via pkg-config instead of a custom search of a few directories. * Add support for core.protectHFS and core.protectNTFS. Add more validation for filenames which we write such as references. * The local transport now generates textual progress output like git-upload-pack does ("counting objects"). * `git_checkout_index()` can now check out an in-memory index that is not necessarily the repository's index, so you may check out an index that was produced by git_merge and friends while retaining the cached information. * Remove the default timeout for receiving / sending data over HTTP using the WinHTTP transport layer. * Add SPNEGO (Kerberos) authentication using GSSAPI on Unix systems. * Provide built-in objects for the empty blob (e69de29) and empty tree (4b825dc) objects. * The index' tree cache is now filled upon read-tree and write-tree and the cache is written to disk. * LF -> CRLF filter refuses to handle mixed-EOL files * LF -> CRLF filter now runs when * text = auto (with Git for Windows 1.9.4) * File unlocks are atomic again via rename. Read-only files on Windows are made read-write if necessary. * Share open packfiles across repositories to share descriptors and mmaps. * Use a map for the treebuilder, making insertion O(1) * The build system now accepts an option EMBED_SSH_PATH which when set tells it to include a copy of libssh2 at the given location. This is enabled for MSVC. * Add support for refspecs with the asterisk in the middle of a pattern. * Fetching now performs opportunistic updates. To achieve this, we introduce a difference between active and passive refspecs, which make `git_remote_download()` and `git_remote_fetch()` to take a list of resfpecs to be the active list, similarly to how git fetch accepts a list on the command-line. * The THREADSAFE option to build libgit2 with threading support has been flipped to be on by default. * The remote object has learnt to prune remote-tracking branches. If the remote is configured to do so, this will happen via `git_remote_fetch()`. You can also call `git_remote_prune()` after connecting or fetching to perform the prune. ### API additions * Introduce `git_buf_text_is_binary()` and `git_buf_text_contains_nul()` for consumers to perform binary detection on a git_buf. * `git_branch_upstream_remote()` has been introduced to provide the branch.<name>.remote configuration value. * Introduce `git_describe_commit()` and `git_describe_workdir()` to provide a description of the current commit (and working tree, respectively) based on the nearest tag or reference * Introduce `git_merge_bases()` and the `git_oidarray` type to expose all merge bases between two commits. * Introduce `git_merge_bases_many()` to expose all merge bases between multiple commits. * Introduce rebase functionality (using the merge algorithm only). Introduce `git_rebase_init()` to begin a new rebase session, `git_rebase_open()` to open an in-progress rebase session, `git_rebase_commit()` to commit the current rebase operation, `git_rebase_next()` to apply the next rebase operation, `git_rebase_abort()` to abort an in-progress rebase and `git_rebase_finish()` to complete a rebase operation. * Introduce `git_note_author()` and `git_note_committer()` to get the author and committer information on a `git_note`, respectively. * A factory function for ssh has been added which allows to change the path of the programs to execute for receive-pack and upload-pack on the server, `git_transport_ssh_with_paths()`. * The ssh transport supports asking the remote host for accepted credential types as well as multiple challeges using a single connection. This requires to know which username you want to connect as, so this introduces the USERNAME credential type which the ssh transport will use to ask for the username. * The `GIT_EPEEL` error code has been introduced when we cannot peel a tag to the requested object type; if the given object otherwise cannot be peeled, `GIT_EINVALIDSPEC` is returned. * Introduce `GIT_REPOSITORY_INIT_RELATIVE_GITLINK` to use relative paths when writing gitlinks, as is used by git core for submodules. * `git_remote_prune()` has been added. See above for description. * Introduce reference transactions, which allow multiple references to be locked at the same time and updates be queued. This also allows us to safely update a reflog with arbitrary contents, as we need to do for stash. ### API removals * `git_remote_supported_url()` and `git_remote_is_valid_url()` have been removed as they have become essentially useless with rsync-style ssh paths. * `git_clone_into()` and `git_clone_local_into()` have been removed from the public API in favour of `git_clone callbacks`. * The option to ignore certificate errors via `git_remote_cert_check()` is no longer present. Instead, `git_remote_callbacks` has gained a new entry which lets the user perform their own certificate checks. ### Breaking API changes * `git_cherry_pick()` is now `git_cherrypick()`. * The `git_submodule_update()` function was renamed to `git_submodule_update_strategy()`. `git_submodule_update()` is now used to provide functionalty similar to "git submodule update". * `git_treebuilder_create()` was renamed to `git_treebuilder_new()` to better reflect it being a constructor rather than something which writes to disk. * `git_treebuilder_new()` (was `git_treebuilder_create()`) now takes a repository so that it can query repository configuration. Subsequently, `git_treebuilder_write()` no longer takes a repository. * `git_threads_init()` and `git_threads_shutdown()` have been renamed to `git_libgit2_init()` and `git_libgit2_shutdown()` to better explain what their purpose is, as it's grown to be more than just about threads. * `git_libgit2_init()` and `git_libgit2_shutdown()` now return the number of initializations of the library, so consumers may schedule work on the first initialization. * The `git_transport_register()` function no longer takes a priority and takes a URL scheme name (eg "http") instead of a prefix like "http://" * `git_index_name_entrycount()` and `git_index_reuc_entrycount()` now return size_t instead of unsigned int. * The `context_lines` and `interhunk_lines` fields in `git_diff`_options are now `uint32_t` instead of `uint16_t`. This allows to set them to `UINT_MAX`, in effect asking for "infinite" context e.g. to iterate over all the unmodified lines of a diff. * `git_status_file()` now takes an exact path. Use `git_status_list_new()` if pathspec searching is needed. * `git_note_create()` has changed the position of the notes reference name to match `git_note_remove()`. * Rename `git_remote_load()` to `git_remote_lookup()` to bring it in line with the rest of the lookup functions. * `git_remote_rename()` now takes the repository and the remote's current name. Accepting a remote indicates we want to change it, which we only did partially. It is much clearer if we accept a name and no loaded objects are changed. * `git_remote_delete()` now accepts the repository and the remote's name instead of a loaded remote. * `git_merge_head` is now `git_annotated_commit`, to better reflect its usage for multiple functions (including rebase) * The `git_clone_options` struct no longer provides the `ignore_cert_errors` or `remote_name` members for remote customization. Instead, the `git_clone_options` struct has two new members, `remote_cb` and `remote_cb_payload`, which allow the caller to completely override the remote creation process. If needed, the caller can use this callback to give their remote a name other than the default (origin) or disable cert checking. The `remote_callbacks` member has been preserved for convenience, although it is not used when a remote creation callback is supplied. * The `git_clone`_options struct now provides `repository_cb` and `repository_cb_payload` to allow the user to create a repository with custom options. * The `git_push` struct to perform a push has been replaced with `git_remote_upload()`. The refspecs and options are passed as a function argument. `git_push_update_tips()` is now also `git_remote_update_tips()` and the callbacks are in the same struct as the rest. * The `git_remote_set_transport()` function now sets a transport factory function, rather than a pre-existing transport instance. * The `git_transport` structure definition has moved into the sys/transport.h file. * libgit2 no longer automatically sets the OpenSSL locking functions. This is not something which we can know to do. A last-resort convenience function is provided in sys/openssl.h, `git_openssl_set_locking()` which can be used to set the locking.
0
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2/docs/conventions.md
# Libgit2 Conventions We like to keep the source consistent and readable. Herein are some guidelines that should help with that. ## External API We have a few rules to avoid surprising ways of calling functions and some rules for consumers of the library to avoid stepping on each other's toes. - Property accessors return the value directly (e.g. an `int` or `const char *`) but if a function can fail, we return a `int` value and the output parameters go first in the parameter list, followed by the object that a function is operating on, and then any other arguments the function may need. - If a function returns an object as a return value, that function is a getter and the object's lifetime is tied to the parent object. Objects which are returned as the first argument as a pointer-to-pointer are owned by the caller and it is responsible for freeing it. Strings are returned via `git_buf` in order to allow for re-use and safe freeing. - Most of what libgit2 does relates to I/O so as a general rule you should assume that any function can fail due to errors as even getting data from the filesystem can result in all sorts of errors and complex failure cases. - Paths inside the Git system are separated by a slash (0x2F). If a function accepts a path on disk, then backslashes (0x5C) are also accepted on Windows. - Do not mix allocators. If something has been allocated by libgit2, you do not know which is the right free function in the general case. Use the free functions provided for each object type. ## Compatibility `libgit2` runs on many different platforms with many different compilers. The public API of `libgit2` is [ANSI C](http://en.wikipedia.org/wiki/ANSI_C) (a.k.a. C89) compatible. Internally, `libgit2` is written using a portable subset of C99 - in order to maximize compatibility (e.g. with MSVC) we avoid certain C99 extensions. Specifically, we keep local variable declarations at the tops of blocks only and we avoid `//` style comments. Also, to the greatest extent possible, we try to avoid lots of `#ifdef`s inside the core code base. This is somewhat unavoidable, but since it can really hamper maintainability, we keep it to a minimum. ## Match Surrounding Code If there is one rule to take away from this document, it is *new code should match the surrounding code in a way that makes it impossible to distinguish the new from the old.* Consistency is more important to us than anyone's personal opinion about where braces should be placed or spaces vs. tabs. If a section of code is being completely rewritten, it is okay to bring it in line with the standards that are laid out here, but we will not accept submissions that contain a large number of changes that are merely reformatting. ## Naming Things All external types and functions start with `git_` and all `#define` macros start with `GIT_`. The `libgit2` API is mostly broken into related functional modules each with a corresponding header. All functions in a module should be named like `git_modulename_functioname()` (e.g. `git_repository_open()`). Functions with a single output parameter should name that parameter `out`. Multiple outputs should be named `foo_out`, `bar_out`, etc. Parameters of type `git_oid` should be named `id`, or `foo_id`. Calls that return an OID should be named `git_foo_id`. Where a callback function is used, the function should also include a user-supplied extra input that is a `void *` named "payload" that will be passed through to the callback at each invocation. ## Typedefs Wherever possible, use `typedef`. In some cases, if a structure is just a collection of function pointers, the pointer types don't need to be separately typedef'd, but loose function pointer types should be. ## Exports All exported functions must be declared as: ```c GIT_EXTERN(result_type) git_modulename_functionname(arg_list); ``` ## Internals Functions whose *modulename* is followed by two underscores, for example `git_odb__read_packed`, are semi-private functions. They are primarily intended for use within the library itself, and may disappear or change their signature in a future release. ## Parameters Out parameters come first. Whenever possible, pass argument pointers as `const`. Some structures (such as `git_repository` and `git_index`) have mutable internal structure that prevents this. Callbacks should always take a `void *` payload as their last parameter. Callback pointers are grouped with their payloads, and typically come last when passed as arguments: ```c int git_foo(git_repository *repo, git_foo_cb callback, void *payload); ``` ## Memory Ownership Some APIs allocate memory which the caller is responsible for freeing; others return a pointer into a buffer that's owned by some other object. Make this explicit in the documentation. ## Return codes Most public APIs should return an `int` error code. As is typical with most C library functions, a zero value indicates success and a negative value indicates failure. Some bindings will transform these returned error codes into exception types, so returning a semantically appropriate error code is important. Check [`include/git2/errors.h`](https://github.com/libgit2/libgit2/blob/development/include/git2/errors.h) for the return codes already defined. In your implementation, use `git_error_set()` to provide extended error information to callers. If a `libgit2` function internally invokes another function that reports an error, but the error is not propagated up, use `git_error_clear()` to prevent callers from getting the wrong error message later on. ## Structs Most public types should be opaque, e.g.: ```C typedef struct git_odb git_odb; ``` ...with allocation functions returning an "instance" created within the library, and not within the application. This allows the type to grow (or shrink) in size without rebuilding client code. To preserve ABI compatibility, include an `int version` field in all transparent structures, and initialize to the latest version in the constructor call. Increment the "latest" version whenever the structure changes, and try to only append to the end of the structure. ## Option Structures If a function's parameter count is too high, it may be desirable to package up the options in a structure. Make them transparent, include a version field, and provide an initializer constant or constructor. Using these structures should be this easy: ```C git_foo_options opts = GIT_FOO_OPTIONS_INIT; opts.baz = BAZ_OPTION_ONE; git_foo(&opts); ``` ## Enumerations Typedef all enumerated types. If each option stands alone, use the enum type for passing them as parameters; if they are flags to be OR'ed together, pass them as `unsigned int` or `uint32_t` or some appropriate type. ## Code Layout Try to keep lines less than 80 characters long. This is a loose requirement, but going significantly over 80 columns is not nice. Use common sense to wrap most code lines; public function declarations can use a couple of different styles: ```c /** All on one line is okay if it fits */ GIT_EXTERN(int) git_foo_simple(git_oid *id); /** Otherwise one argument per line is a good next step */ GIT_EXTERN(int) git_foo_id( git_oid **out, int a, int b); ``` Indent with tabs; set your editor's tab width to eight for best effect. Avoid trailing whitespace and only commit Unix-style newlines (i.e. no CRLF in the repository - just set `core.autocrlf` to true if you are writing code on a Windows machine). ## Documentation All comments should conform to Doxygen "javadoc" style conventions for formatting the public API documentation. Try to document every parameter, and keep the comments up to date if you change the parameter list. ## Public Header Template Use this template when creating a new public header. ```C #ifndef INCLUDE_git_${filename}_h__ #define INCLUDE_git_${filename}_h__ #include "git/common.h" /** * @file git/${filename}.h * @brief Git some description * @defgroup git_${filename} some description routines * @ingroup Git * @{ */ GIT_BEGIN_DECL /* ... definitions ... */ /** @} */ GIT_END_DECL #endif ``` ## Inlined functions All inlined functions must be declared as: ```C GIT_INLINE(result_type) git_modulename_functionname(arg_list); ``` `GIT_INLINE` (or `inline`) should not be used in public headers in order to preserve ANSI C compatibility. ## Tests `libgit2` uses the [clar](https://github.com/vmg/clar) testing framework. All PRs should have corresponding tests. * If the PR fixes an existing issue, the test should fail prior to applying the PR and succeed after applying it. * If the PR is for new functionality, then the tests should exercise that new functionality to a certain extent. We don't require 100% coverage right now (although we are getting stricter over time). When adding new tests, we prefer if you attempt to reuse existing test data (in `tests-clar/resources/`) if possible. If you are going to add new test repositories, please try to strip them of unnecessary files (e.g. sample hooks, etc).
0
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2/docs/fuzzing.md
# Fuzzing libgit2 is currently using [libFuzzer](https://libfuzzer.info) to perform automated fuzz testing. libFuzzer only works with clang. ## Prerequisites for building fuzz targets: 1. All the prerequisites for [building libgit2](https://github.com/libgit2/libgit2). 2. A recent version of clang. 6.0 is preferred. [pre-build Debian/Ubuntu packages](https://github.com/libgit2/libgit2) ## Build 1. Create a build directory beneath the libgit2 source directory, and change into it: `mkdir build && cd build` 2. Choose one sanitizers to add. The currently supported sanitizers are [`address`](https://clang.llvm.org/docs/AddressSanitizer.html), [`undefined`](https://clang.llvm.org/docs/UndefinedBehaviorSanitizer.html), and [`leak`/`address,leak`](https://clang.llvm.org/docs/LeakSanitizer.html). 3. Create the cmake build environment and configure the build with the sanitizer chosen: `CC=/usr/bin/clang-6.0 CFLAGS="-fsanitize=address" cmake -DBUILD_CLAR=OFF -DBUILD_FUZZERS=ON -DCMAKE_BUILD_TYPE=RelWithDebInfo ..`. Note that building the fuzzer targets is incompatible with the tests and examples. 4. Build libgit2: `cmake --build .` 5. Exit the cmake build environment: `cd ..` ## Run the fuzz targets 1. `ASAN_SYMBOLIZER_PATH=/usr/bin/llvm-symbolize LSAN_OPTIONS=allocator_may_return_null=1 ASAN_OPTIONS=allocator_may_return_null=1 ./build/fuzzers/packfile_fuzzer fuzzers/corpora/packfile/` The `LSAN_OPTIONS` and `ASAN_OPTIONS` are there to allow `malloc(3)` to return `NULL`, which is expected if a huge chunk of memory is allocated. The `LLVM_PROFILE_FILE` environment string can also be added to override the path where libFuzzer will write the coverage report. ## Get coverage In order to get coverage information, you need to add the "-fcoverage-mapping" and "-fprofile-instr-generate CFLAGS, and then run the fuzz target with `-runs=0`. That will produce a file called `default.profraw` (this behavior can be overridden by setting the `LLVM_PROFILE_FILE="yourfile.profraw"` environment variable). 1. `llvm-profdata-6.0 merge -sparse default.profraw -o fuzz_packfile_raw.profdata` transforms the data from a sparse representation into a format that can be used by the other tools. 2. `llvm-cov-6.0 report ./build/fuzz/fuzz_packfile_raw -instr-profile=fuzz_packfile_raw.profdata` shows a high-level per-file coverage report. 3. `llvm-cov-6.0 show ./build/fuzz/fuzz_packfile_raw -instr-profile=fuzz_packfile_raw.profdata [source file]` shows a line-by-line coverage analysis of all the codebase (or a single source file). ## Standalone mode In order to ensure that there are no regresions, each fuzzer target can be run in a standalone mode. This can be done by passing `-DUSE_STANDALONE_FUZZERS=ON`. This makes it compatible with gcc. This does not use the fuzzing engine, but just invokes every file in the chosen corpus. In order to get full coverage, though, you might want to also enable one of the sanitizers. You might need a recent version of clang to get full support. ## References * [libFuzzer](https://llvm.org/docs/LibFuzzer.html) documentation. * [Source-based Code Coverage](https://clang.llvm.org/docs/SourceBasedCodeCoverage.html).
0
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2/docs/contributing.md
# Welcome to libgit2! We're making it easy to do interesting things with git, and we'd love to have your help. ## Licensing By contributing to libgit2, you agree to release your contribution under the terms of the license. Except for the `examples` and the `deps` directories, all code is released under the [GPL v2 with linking exception](../COPYING). The `examples` code is governed by the [CC0 Public Domain Dedication](../examples/COPYING), so that you may copy from them into your own application. The bundled dependencies in the `deps` directories are governed by the following licenses: - http-parser is licensed under [MIT license](../deps/http-parser/COPYING) - pcre is governed by [BSD license](../deps/pcre/LICENCE) - winhttp is governed by [LGPL v2.1+](../deps/winhttp/COPYING.LGPL) and [GPL v2 with linking exception](../deps/winhttp/COPYING.GPL) - zlib is governed by [zlib license](../deps/zlib/COPYING) ## Discussion & Chat We hang out in the [`#libgit2`](http://webchat.freenode.net/?channels=#libgit2)) channel on irc.freenode.net. Also, feel free to open an [Issue](https://github.com/libgit2/libgit2/issues/new) to start a discussion about any concerns you have. We like to use Issues for that so there is an easily accessible permanent record of the conversation. ## Libgit2 Versions The `main` branch is the main branch where development happens. Releases are tagged (e.g. [v0.21.0](https://github.com/libgit2/libgit2/releases/tag/v0.21.0) ) and when a critical bug fix needs to be backported, it will be done on a `<tag>-maint` maintenance branch. ## Reporting Bugs First, know which version of libgit2 your problem is in and include it in your bug report. This can either be a tag (e.g. [v0.17.0](https://github.com/libgit2/libgit2/releases/tag/v0.17.0)) or a commit SHA (e.g. [01be7863](https://github.com/libgit2/libgit2/commit/01be7863)). Using [`git describe`](http://git-scm.com/docs/git-describe) is a great way to tell us what version you're working with. If you're not running against the latest `main` branch version, please compile and test against that to avoid re-reporting an issue that's already been fixed. It's *incredibly* helpful to be able to reproduce the problem. Please include a list of steps, a bit of code, and/or a zipped repository (if possible). Note that some of the libgit2 developers are employees of GitHub, so if your repository is private, find us on IRC and we'll figure out a way to help you. ## Pull Requests Our work flow is a [typical GitHub flow](https://guides.github.com/introduction/flow/index.html), where contributors fork the [libgit2 repository](https://github.com/libgit2/libgit2), make their changes on branch, and submit a [Pull Request](https://help.github.com/articles/using-pull-requests) (a.k.a. "PR"). Pull requests should usually be targeted at the `main` branch. Life will be a lot easier for you (and us) if you follow this pattern (i.e. fork, named branch, submit PR). If you use your fork's `main` branch directly, things can get messy. Please include a nice description of your changes when you submit your PR; if we have to read the whole diff to figure out why you're contributing in the first place, you're less likely to get feedback and have your change merged in. In addition to outlining your thought process in the PR's description, please also try to document it in your commits. We welcome it if every commit has a description of why you have been doing your changes alongside with your reasoning why this is a good idea. The messages shall be written in present-tense and in an imperative style (e.g. "Add feature foobar", not "Added feature foobar" or "Adding feature foobar"). Lines should be wrapped at 80 characters so people with small screens are able to read the commit messages in their terminal without any problem. To make it easier to attribute commits to certain parts of our code base, we also prefer to have the commit subject be prefixed with a "scope". E.g. if you are changing code in our merging subsystem, make sure to prefix the subject with "merge:". The first word following the colon shall start with an lowercase letter. The maximum line length for the subject is 70 characters, preferably shorter. If you are starting to work on a particular area, feel free to submit a PR that highlights your work in progress (and note in the PR title that it's not ready to merge). These early PRs are welcome and will help in getting visibility for your fix, allow others to comment early on the changes and also let others know that you are currently working on something. Before wrapping up a PR, you should be sure to: * Write tests to cover any functional changes * Update documentation for any changed public APIs * Add to the [`changelog.md`](changelog.md) file describing any major changes ## Unit Tests We believe that our unit tests allow us to keep the quality of libgit2 high: any new changes must not cause unit test failures, and new changes should include unit tests that cover the bug fixes or new features. For bug fixes, we prefer unit tests that illustrate the failure before the change, but pass with your changes. In addition to new tests, please ensure that your changes do not cause any other test failures. Running the entire test suite is helpful before you submit a pull request. When you build libgit2, the test suite will also be built. You can run most of the tests by simply running the resultant `libgit2_clar` binary. If you want to run a specific unit test, you can name it with the `-s` option. For example: libgit2_clar -sstatus::worktree::long_filenames Or you can run an entire class of tests. For example, to run all the worktree status tests: libgit2_clar -sstatus::worktree The default test run is fairly exhaustive, but it will exclude some unit tests by default: in particular, those that talk to network servers and the tests that manipulate the filesystem in onerous ways (and may need to have special privileges to run). To run the network tests: libgit2_clar -ionline In addition, various tests may be enabled by environment variables, like the ones that write exceptionally large repositories or manipulate the filesystem structure in unexpected ways. These tests *may be dangerous* to run on a normal machine and may harm your filesystem. It's not recommended that you run these; instead, the continuous integration servers will run these (in a sandbox). ## Porting Code From Other Open-Source Projects `libgit2` is licensed under the terms of the GPL v2 with a linking exception. Any code brought in must be compatible with those terms. The most common case is porting code from core Git. Git is a pure GPL project, which means that in order to port code to this project, we need the explicit permission of the author. Check the [`git.git-authors`](https://github.com/libgit2/libgit2/blob/development/git.git-authors) file for authors who have already consented. Other licenses have other requirements; check the license of the library you're porting code *from* to see what you need to do. As a general rule, MIT and BSD (3-clause) licenses are typically no problem. Apache 2.0 license typically doesn't work due to GPL incompatibility. If your pull request uses code from core Git, another project, or code from a forum / Stack Overflow, then *please* flag this in your PR and make sure you've given proper credit to the original author in the code snippet. ## Style Guide The public API of `libgit2` is [ANSI C](http://en.wikipedia.org/wiki/ANSI_C) (a.k.a. C89) compatible. Internally, `libgit2` is written using a portable subset of C99 - in order to compile with GCC, Clang, MSVC, etc., we keep local variable declarations at the tops of blocks only and avoid `//` style comments. Additionally, `libgit2` follows some extra conventions for function and type naming, code formatting, and testing. We like to keep the source code consistent and easy to read. Maintaining this takes some discipline, but it's been more than worth it. Take a look at the [conventions file](conventions.md). ## Starter Projects See our [projects list](projects.md).
0
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2/docs/differences-from-git.md
# Differences from Git In some instances, the functionality of libgit2 deviates slightly from Git. This can be because of technical limitations when developing a library, licensing limitations when converting functionality from Git to libgit2, or various other reasons. Repository and Workdir Path Reporting ------------------------------------- When asking Git for the absolute path of a repository via `git rev-parse --absolute-git-dir`, it will output the path to the ".git" folder without a trailing slash. In contrast to that, the call `git_repository_path(repo)` will return the path with a trailing slash: ``` git rev-parse --absolute-git-dir -> /home/user/projects/libgit2/.git git_repository_path(repo) -> /home/user/projects/libgit2/.git/ ``` The same difference exists when listing worktrees: ``` git worktree list -> /home/user/projects/libgit2 git_repository_workdir(repo) -> /home/user/projects/libgit2/ ``` Windows Junction Points ----------------------- In libgit2, junction points are treated like symbolic links. They're handled specially in `git_win32__file_attribute_to_stat` in `src/win/w32_util.h`. This means that libgit2 tracks the directory itself as a link. In Git for Windows, junction points are treated like regular directories. This means that Git for Windows tracks the contents of the directory.
0
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2/docs/win32-longpaths.md
core.longpaths support ====================== Historically, Windows has limited absolute path lengths to `MAX_PATH` (260) characters. Unfortunately, 260 characters is a punishing small maximum. This is especially true for developers where dependencies may have dependencies in a folder, each dependency themselves having dependencies in a sub-folder, ad (seemingly) infinitum. So although the Windows APIs _by default_ honor this 260 character maximum, you can get around this by using separate APIs. Git honors a `core.longpaths` configuration option that allows some paths on Windows to exceed these 260 character limits. And because they've gone and done it, that means that libgit2 has to honor this value, too. Since `core.longpaths` is a _configuration option_ that means that we need to be able to resolve a configuration - including in _the repository itself_ in order to know whether long paths should be supported. Therefore, in libgit2, `core.longpaths` affects paths in working directories _only_. Paths to the repository, and to items inside the `.git` folder, must be no longer than 260 characters. This definition is required to avoid a paradoxical setting: if you had a repository in a folder that was 280 characters long, how would you know whether `core.longpaths` support should be enabled? Even if `core.longpaths` was set to true in a system configuration file, the repository itself may set `core.longpaths` to false in _its_ configuration file, which you could only read if `core.longpaths` were set to true. Thus, `core.longpaths` must _only_ apply to working directory items, and cannot apply to the `.git` folder or its contents.
0
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2/docs/checkout-internals.md
Checkout Internals ================== Checkout has to handle a lot of different cases. It examines the differences between the target tree, the baseline tree and the working directory, plus the contents of the index, and groups files into five categories: 1. UNMODIFIED - Files that match in all places. 2. SAFE - Files where the working directory and the baseline content match that can be safely updated to the target. 3. DIRTY/MISSING - Files where the working directory differs from the baseline but there is no conflicting change with the target. One example is a file that doesn't exist in the working directory - no data would be lost as a result of writing this file. Which action will be taken with these files depends on the options you use. 4. CONFLICTS - Files where changes in the working directory conflict with changes to be applied by the target. If conflicts are found, they prevent any other modifications from being made (although there are options to override that and force the update, of course). 5. UNTRACKED/IGNORED - Files in the working directory that are untracked or ignored (i.e. only in the working directory, not the other places). Right now, this classification is done via 3 iterators (for the three trees), with a final lookup in the index. At some point, this may move to a 4 iterator version to incorporate the index better. The actual checkout is done in five phases (at least right now). 1. The diff between the baseline and the target tree is used as a base list of possible updates to be applied. 2. Iterate through the diff and the working directory, building a list of actions to be taken (and sending notifications about conflicts and dirty files). 3. Remove any files / directories as needed (because alphabetical iteration means that an untracked directory will end up sorted *after* a blob that should be checked out with the same name). 4. Update all blobs. 5. Update all submodules (after 4 in case a new .gitmodules blob was checked out) Checkout could be driven either off a target-to-workdir diff or a baseline-to-target diff. There are pros and cons of each. Target-to-workdir means the diff includes every file that could be modified, which simplifies bookkeeping, but the code to constantly refer back to the baseline gets complicated. Baseline-to-target has simpler code because the diff defines the action to take, but needs special handling for untracked and ignored files, if they need to be removed. The current checkout implementation is based on a baseline-to-target diff. Picking Actions =============== The most interesting aspect of this is phase 2, picking the actions that should be taken. There are a lot of corner cases, so it may be easier to start by looking at the rules for a simple 2-iterator diff: Key --- - B1,B2,B3 - blobs with different SHAs, - Bi - ignored blob (WD only) - T1,T2,T3 - trees with different SHAs, - Ti - ignored tree (WD only) - S1,S2 - submodules with different SHAs - Sd - dirty submodule (WD only) - x - nothing Diff with 2 non-workdir iterators --------------------------------- | | Old | New | | |----|-----|-----|------------------------------------------------------------| | 0 | x | x | nothing | | 1 | x | B1 | added blob | | 2 | x | T1 | added tree | | 3 | B1 | x | removed blob | | 4 | B1 | B1 | unmodified blob | | 5 | B1 | B2 | modified blob | | 6 | B1 | T1 | typechange blob -> tree | | 7 | T1 | x | removed tree | | 8 | T1 | B1 | typechange tree -> blob | | 9 | T1 | T1 | unmodified tree | | 10 | T1 | T2 | modified tree (implies modified/added/removed blob inside) | Now, let's make the "New" iterator into a working directory iterator, so we replace "added" items with either untracked or ignored, like this: Diff with non-work & workdir iterators -------------------------------------- | | Old | New | | |----|-----|-----|------------------------------------------------------------| | 0 | x | x | nothing | | 1 | x | B1 | untracked blob | | 2 | x | Bi | ignored file | | 3 | x | T1 | untracked tree | | 4 | x | Ti | ignored tree | | 5 | B1 | x | removed blob | | 6 | B1 | B1 | unmodified blob | | 7 | B1 | B2 | modified blob | | 8 | B1 | T1 | typechange blob -> tree | | 9 | B1 | Ti | removed blob AND ignored tree as separate items | | 10 | T1 | x | removed tree | | 11 | T1 | B1 | typechange tree -> blob | | 12 | T1 | Bi | removed tree AND ignored blob as separate items | | 13 | T1 | T1 | unmodified tree | | 14 | T1 | T2 | modified tree (implies modified/added/removed blob inside) | Note: if there is a corresponding entry in the old tree, then a working directory item won't be ignored (i.e. no Bi or Ti for tracked items). Now, expand this to three iterators: a baseline tree, a target tree, and an actual working directory tree: Checkout From 3 Iterators (2 not workdir, 1 workdir) ---------------------------------------------------- (base == old HEAD; target == what to checkout; actual == working dir) | |base | target | actual/workdir | | |-----|-----|------- |----------------|--------------------------------------------------------------------| | 0 | x | x | x | nothing | | 1 | x | x | B1/Bi/T1/Ti | untracked/ignored blob/tree (SAFE) | | 2+ | x | B1 | x | add blob (SAFE) | | 3 | x | B1 | B1 | independently added blob (FORCEABLE-2) | | 4* | x | B1 | B2/Bi/T1/Ti | add blob with content conflict (FORCEABLE-2) | | 5+ | x | T1 | x | add tree (SAFE) | | 6* | x | T1 | B1/Bi | add tree with blob conflict (FORCEABLE-2) | | 7 | x | T1 | T1/i | independently added tree (SAFE+MISSING) | | 8 | B1 | x | x | independently deleted blob (SAFE+MISSING) | | 9- | B1 | x | B1 | delete blob (SAFE) | | 10- | B1 | x | B2 | delete of modified blob (FORCEABLE-1) | | 11 | B1 | x | T1/Ti | independently deleted blob AND untrack/ign tree (SAFE+MISSING !!!) | | 12 | B1 | B1 | x | locally deleted blob (DIRTY || SAFE+CREATE) | | 13+ | B1 | B2 | x | update to deleted blob (SAFE+MISSING) | | 14 | B1 | B1 | B1 | unmodified file (SAFE) | | 15 | B1 | B1 | B2 | locally modified file (DIRTY) | | 16+ | B1 | B2 | B1 | update unmodified blob (SAFE) | | 17 | B1 | B2 | B2 | independently updated blob (FORCEABLE-1) | | 18+ | B1 | B2 | B3 | update to modified blob (FORCEABLE-1) | | 19 | B1 | B1 | T1/Ti | locally deleted blob AND untrack/ign tree (DIRTY) | | 20* | B1 | B2 | T1/Ti | update to deleted blob AND untrack/ign tree (F-1) | | 21+ | B1 | T1 | x | add tree with locally deleted blob (SAFE+MISSING) | | 22* | B1 | T1 | B1 | add tree AND deleted blob (SAFE) | | 23* | B1 | T1 | B2 | add tree with delete of modified blob (F-1) | | 24 | B1 | T1 | T1 | add tree with deleted blob (F-1) | | 25 | T1 | x | x | independently deleted tree (SAFE+MISSING) | | 26 | T1 | x | B1/Bi | independently deleted tree AND untrack/ign blob (F-1) | | 27- | T1 | x | T1 | deleted tree (MAYBE SAFE) | | 28+ | T1 | B1 | x | deleted tree AND added blob (SAFE+MISSING) | | 29 | T1 | B1 | B1 | independently typechanged tree -> blob (F-1) | | 30+ | T1 | B1 | B2 | typechange tree->blob with conflicting blob (F-1) | | 31* | T1 | B1 | T1/T2 | typechange tree->blob (MAYBE SAFE) | | 32+ | T1 | T1 | x | restore locally deleted tree (SAFE+MISSING) | | 33 | T1 | T1 | B1/Bi | locally typechange tree->untrack/ign blob (DIRTY) | | 34 | T1 | T1 | T1/T2 | unmodified tree (MAYBE SAFE) | | 35+ | T1 | T2 | x | update locally deleted tree (SAFE+MISSING) | | 36* | T1 | T2 | B1/Bi | update to tree with typechanged tree->blob conflict (F-1) | | 37 | T1 | T2 | T1/T2/T3 | update to existing tree (MAYBE SAFE) | | 38+ | x | S1 | x | add submodule (SAFE) | | 39 | x | S1 | S1/Sd | independently added submodule (SUBMODULE) | | 40* | x | S1 | B1 | add submodule with blob confilct (FORCEABLE) | | 41* | x | S1 | T1 | add submodule with tree conflict (FORCEABLE) | | 42 | S1 | x | S1/Sd | deleted submodule (SUBMODULE) | | 43 | S1 | x | x | independently deleted submodule (SUBMODULE) | | 44 | S1 | x | B1 | independently deleted submodule with added blob (SAFE+MISSING) | | 45 | S1 | x | T1 | independently deleted submodule with added tree (SAFE+MISSING) | | 46 | S1 | S1 | x | locally deleted submodule (SUBMODULE) | | 47+ | S1 | S2 | x | update locally deleted submodule (SAFE) | | 48 | S1 | S1 | S2 | locally updated submodule commit (SUBMODULE) | | 49 | S1 | S2 | S1 | updated submodule commit (SUBMODULE) | | 50+ | S1 | B1 | x | add blob with locally deleted submodule (SAFE+MISSING) | | 51* | S1 | B1 | S1 | typechange submodule->blob (SAFE) | | 52* | S1 | B1 | Sd | typechange dirty submodule->blob (SAFE!?!?) | | 53+ | S1 | T1 | x | add tree with locally deleted submodule (SAFE+MISSING) | | 54* | S1 | T1 | S1/Sd | typechange submodule->tree (MAYBE SAFE) | | 55+ | B1 | S1 | x | add submodule with locally deleted blob (SAFE+MISSING) | | 56* | B1 | S1 | B1 | typechange blob->submodule (SAFE) | | 57+ | T1 | S1 | x | add submodule with locally deleted tree (SAFE+MISSING) | | 58* | T1 | S1 | T1 | typechange tree->submodule (SAFE) | The number is followed by ' ' if no change is needed or '+' if the case needs to write to disk or '-' if something must be deleted and '*' if there should be a delete followed by an write. There are four tiers of safe cases: * SAFE == completely safe to update * SAFE+MISSING == safe except the workdir is missing the expect content * MAYBE SAFE == safe if workdir tree matches (or is missing) baseline content, which is unknown at this point * FORCEABLE == conflict unless FORCE is given * DIRTY == no conflict but change is not applied unless FORCE * SUBMODULE == no conflict and no change is applied unless a deleted submodule dir is empty Some slightly unusual circumstances: * 8 - parent dir is only deleted when file is, so parent will be left if empty even though it would be deleted if the file were present * 11 - core git does not consider this a conflict but attempts to delete T1 and gives "unable to unlink file" error yet does not skip the rest of the operation * 12 - without FORCE file is left deleted (i.e. not restored) so new wd is dirty (and warning message "D file" is printed), with FORCE, file is restored. * 24 - This should be considered MAYBE SAFE since effectively it is 7 and 8 combined, but core git considers this a conflict unless forced. * 26 - This combines two cases (1 & 25) (and also implied 8 for tree content) which are ok on their own, but core git treat this as a conflict. If not forced, this is a conflict. If forced, this actually doesn't have to write anything and leaves the new blob as an untracked file. * 32 - This is the only case where the baseline and target values match and yet we will still write to the working directory. In all other cases, if baseline == target, we don't touch the workdir (it is either already right or is "dirty"). However, since this case also implies that a ?/B1/x case will exist as well, it can be skipped. * 41 - It's not clear how core git distinguishes this case from 39 (mode?). * 52 - Core git makes destructive changes without any warning when the submodule is dirty and the type changes to a blob. Cases 3, 17, 24, 26, and 29 are all considered conflicts even though none of them will require making any updates to the working directory.
0
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2/docs/troubleshooting.md
Troubleshooting libgit2 Problems ================================ CMake Failures -------------- * **`Asked for OpenSSL TLS backend, but it wasn't found`** CMake cannot find your SSL/TLS libraries. By default, libgit2 always builds with HTTPS support, and you are encouraged to install the OpenSSL libraries for your system (eg, `apt-get install libssl-dev`). For development, if you simply want to disable HTTPS support entirely, pass the `-DUSE_HTTPS=OFF` argument to `cmake` when configuring it.
0
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2/docs/diff-internals.md
Diff is broken into four phases: 1. Building a list of things that have changed. These changes are called deltas (git_diff_delta objects) and are grouped into a git_diff_list. 2. Applying file similarity measurement for rename and copy detection (and to potentially split files that have changed radically). This step is optional. 3. Computing the textual diff for each delta. Not all deltas have a meaningful textual diff. For those that do, the textual diff can either be generated on the fly and passed to output callbacks or can be turned into a git_diff_patch object. 4. Formatting the diff and/or patch into standard text formats (such as patches, raw lists, etc). In the source code, step 1 is implemented in `src/diff.c`, step 2 in `src/diff_tform.c`, step 3 in `src/diff_patch.c`, and step 4 in `src/diff_print.c`. Additionally, when it comes to accessing file content, everything goes through diff drivers that are implemented in `src/diff_driver.c`. External Objects ---------------- * `git_diff_options` represents user choices about how a diff should be performed and is passed to most diff generating functions. * `git_diff_file` represents an item on one side of a possible delta * `git_diff_delta` represents a pair of items that have changed in some way - it contains two `git_diff_file` plus a status and other stuff. * `git_diff_list` is a list of deltas along with information about how those particular deltas were found. * `git_diff_patch` represents the actual diff between a pair of items. In some cases, a delta may not have a corresponding patch, if the objects are binary, for example. The content of a patch will be a set of hunks and lines. * A `hunk` is range of lines described by a `git_diff_range` (i.e. "lines 10-20 in the old file became lines 12-23 in the new"). It will have a header that compactly represents that information, and it will have a number of lines of context surrounding added and deleted lines. * A `line` is simple a line of data along with a `git_diff_line_t` value that tells how the data should be interpreted (e.g. context or added). Internal Objects ---------------- * `git_diff_file_content` is an internal structure that represents the data on one side of an item to be diffed; it is an augmented `git_diff_file` with more flags and the actual file data. * it is created from a repository plus a) a git_diff_file, b) a git_blob, or c) raw data and size * there are three main operations on git_diff_file_content: * _initialization_ sets up the data structure and does what it can up to, but not including loading and looking at the actual data * _loading_ loads the data, preprocesses it (i.e. applies filters) and potentially analyzes it (to decide if binary) * _free_ releases loaded data and frees any allocated memory * The internal structure of a `git_diff_patch` stores the actual diff between a pair of `git_diff_file_content` items * it may be "unset" if the items are not diffable * "empty" if the items are the same * otherwise it will consist of a set of hunks each of which covers some number of lines of context, additions and deletions * a patch is created from two git_diff_file_content items * a patch is fully instantiated in three phases: * initial creation and initialization * loading of data and preliminary data examination * diffing of data and optional storage of diffs * (TBD) if a patch is asked to store the diffs and the size of the diff is significantly smaller than the raw data of the two sides, then the patch may be flattened using a pool of string data * `git_diff_output` is an internal structure that represents an output target for a `git_diff_patch` * It consists of file, hunk, and line callbacks, plus a payload * There is a standard flattened output that can be used for plain text output * Typically we use a `git_xdiff_output` which drives the callbacks via the xdiff code taken from core Git. * `git_diff_driver` is an internal structure that encapsulates the logic for a given type of file * a driver is looked up based on the name and mode of a file. * the driver can then be used to: * determine if a file is binary (by attributes, by git_diff_options settings, or by examining the content) * give you a function pointer that is used to evaluate function context for hunk headers * At some point, the logic for getting a filtered version of file content or calculating the OID of a file may be moved into the driver.
0
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2/ci/coverity.sh
#!/bin/bash -e if test -z "$COVERITY_TOKEN" then echo "Need to set a coverity token" exit 1 fi case $(uname -m) in i?86) BITS=32;; amd64|x86_64) BITS=64;; *) echo "Unsupported arch '$(uname -m)'" exit 1;; esac SCAN_TOOL=https://scan.coverity.com/download/cxx/linux${BITS} SOURCE_DIR=$(realpath "$(dirname "${BASH_SOURCE[0]}")"/..) BUILD_DIR=${SOURCE_DIR}/coverity-build TOOL_DIR=${BUILD_DIR}/coverity-tools # Install coverity tools if ! test -d "$TOOL_DIR" then mkdir -p "$TOOL_DIR" curl --silent --show-error --location --data "project=libgit2&token=$COVERITY_TOKEN" "$SCAN_TOOL" | tar -xzC "$TOOL_DIR" ln -s "$(find "$TOOL_DIR" -type d -name 'cov-analysis*')" "$TOOL_DIR"/cov-analysis fi cp "${SOURCE_DIR}/script/user_nodefs.h" "$TOOL_DIR"/cov-analysis/config/ # Build libgit2 with Coverity mkdir -p "$BUILD_DIR" cd "$BUILD_DIR" cmake "$SOURCE_DIR" COVERITY_UNSUPPORTED=1 \ "$TOOL_DIR/cov-analysis/bin/cov-build" --dir cov-int \ cmake --build . # Upload results tar -czf libgit2.tgz cov-int REVISION=$(cd ${SOURCE_DIR} && git rev-parse --short HEAD) HTML="$(curl \ --silent --show-error \ --write-out "\n%{http_code}" \ --form token="$COVERITY_TOKEN" \ --form [email protected] \ --form [email protected] \ --form version="$REVISION" \ --form description="libgit2 build" \ https://scan.coverity.com/builds?project=libgit2)" # Status code is the last line STATUS_CODE="$(echo "$HTML" | tail -n1)" if test "${STATUS_CODE}" != 200 && test "${STATUS_CODE}" != 201 then echo "Received error code ${STATUS_CODE} from Coverity" exit 1 fi
0
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2/ci/test.sh
#!/usr/bin/env bash set -e if [ -n "$SKIP_TESTS" ]; then exit 0 fi # Windows doesn't run the NTLM tests properly (yet) if [[ "$(uname -s)" == MINGW* ]]; then SKIP_NTLM_TESTS=1 fi SOURCE_DIR=${SOURCE_DIR:-$( cd "$( dirname "${BASH_SOURCE[0]}" )" && dirname $( pwd ) )} BUILD_DIR=$(pwd) TMPDIR=${TMPDIR:-/tmp} USER=${USER:-$(whoami)} SUCCESS=1 CONTINUE_ON_FAILURE=0 cleanup() { echo "Cleaning up..." if [ ! -z "$GITDAEMON_PID" ]; then echo "Stopping git daemon..." kill $GITDAEMON_PID fi if [ ! -z "$SSHD_DIR" -a -f "${SSHD_DIR}/pid" ]; then echo "Stopping SSH..." kill $(cat "${SSHD_DIR}/pid") fi echo "Done." } run_test() { if [[ "$GITTEST_FLAKY_RETRY" > 0 ]]; then ATTEMPTS_REMAIN=$GITTEST_FLAKY_RETRY else ATTEMPTS_REMAIN=1 fi FAILED=0 while [[ "$ATTEMPTS_REMAIN" > 0 ]]; do if [ "$FAILED" -eq 1 ]; then echo "" echo "Re-running flaky ${1} tests..." echo "" fi RETURN_CODE=0 CLAR_SUMMARY="${BUILD_DIR}/results_${1}.xml" ctest -V -R "^${1}$" || RETURN_CODE=$? && true if [ "$RETURN_CODE" -eq 0 ]; then FAILED=0 break fi echo "Test exited with code: $RETURN_CODE" ATTEMPTS_REMAIN="$(($ATTEMPTS_REMAIN-1))" FAILED=1 done if [ "$FAILED" -ne 0 ]; then if [ "$CONTINUE_ON_FAILURE" -ne 1 ]; then exit 1 fi SUCCESS=0 fi } # Configure the test environment; run them early so that we're certain # that they're started by the time we need them. echo "##############################################################################" echo "## Configuring test environment" echo "##############################################################################" if [ -z "$SKIP_GITDAEMON_TESTS" ]; then echo "Starting git daemon..." GITDAEMON_DIR=`mktemp -d ${TMPDIR}/gitdaemon.XXXXXXXX` git init --bare "${GITDAEMON_DIR}/test.git" git daemon --listen=localhost --export-all --enable=receive-pack --base-path="${GITDAEMON_DIR}" "${GITDAEMON_DIR}" 2>/dev/null & GITDAEMON_PID=$! disown $GITDAEMON_PID fi if [ -z "$SKIP_PROXY_TESTS" ]; then curl --location --silent --show-error https://github.com/ethomson/poxyproxy/releases/download/v0.7.0/poxyproxy-0.7.0.jar >poxyproxy.jar echo "" echo "Starting HTTP proxy (Basic)..." java -jar poxyproxy.jar --address 127.0.0.1 --port 8080 --credentials foo:bar --auth-type basic --quiet & echo "" echo "Starting HTTP proxy (NTLM)..." java -jar poxyproxy.jar --address 127.0.0.1 --port 8090 --credentials foo:bar --auth-type ntlm --quiet & fi if [ -z "$SKIP_NTLM_TESTS" ]; then curl --location --silent --show-error https://github.com/ethomson/poxygit/releases/download/v0.4.0/poxygit-0.4.0.jar >poxygit.jar echo "" echo "Starting HTTP server..." NTLM_DIR=`mktemp -d ${TMPDIR}/ntlm.XXXXXXXX` git init --bare "${NTLM_DIR}/test.git" java -jar poxygit.jar --address 127.0.0.1 --port 9000 --credentials foo:baz --quiet "${NTLM_DIR}" & fi if [ -z "$SKIP_SSH_TESTS" ]; then echo "Starting ssh daemon..." HOME=`mktemp -d ${TMPDIR}/home.XXXXXXXX` SSHD_DIR=`mktemp -d ${TMPDIR}/sshd.XXXXXXXX` git init --bare "${SSHD_DIR}/test.git" cat >"${SSHD_DIR}/sshd_config" <<-EOF Port 2222 ListenAddress 0.0.0.0 Protocol 2 HostKey ${SSHD_DIR}/id_rsa PidFile ${SSHD_DIR}/pid AuthorizedKeysFile ${HOME}/.ssh/authorized_keys LogLevel DEBUG RSAAuthentication yes PasswordAuthentication yes PubkeyAuthentication yes ChallengeResponseAuthentication no StrictModes no # Required here as sshd will simply close connection otherwise UsePAM no EOF ssh-keygen -t rsa -f "${SSHD_DIR}/id_rsa" -N "" -q /usr/sbin/sshd -f "${SSHD_DIR}/sshd_config" -E "${SSHD_DIR}/log" # Set up keys mkdir "${HOME}/.ssh" ssh-keygen -t rsa -f "${HOME}/.ssh/id_rsa" -N "" -q cat "${HOME}/.ssh/id_rsa.pub" >>"${HOME}/.ssh/authorized_keys" while read algorithm key comment; do echo "[localhost]:2222 $algorithm $key" >>"${HOME}/.ssh/known_hosts" done <"${SSHD_DIR}/id_rsa.pub" # Get the fingerprint for localhost and remove the colons so we can # parse it as a hex number. Older versions have a different output # format. if [[ $(ssh -V 2>&1) == OpenSSH_6* ]]; then SSH_FINGERPRINT=$(ssh-keygen -F '[localhost]:2222' -f "${HOME}/.ssh/known_hosts" -l | tail -n 1 | cut -d ' ' -f 2 | tr -d ':') else SSH_FINGERPRINT=$(ssh-keygen -E md5 -F '[localhost]:2222' -f "${HOME}/.ssh/known_hosts" -l | tail -n 1 | cut -d ' ' -f 3 | cut -d : -f2- | tr -d :) fi fi # Run the tests that do not require network connectivity. if [ -z "$SKIP_OFFLINE_TESTS" ]; then echo "" echo "##############################################################################" echo "## Running (offline) tests" echo "##############################################################################" run_test offline fi if [ -n "$RUN_INVASIVE_TESTS" ]; then echo "" echo "Running invasive tests" echo "" export GITTEST_INVASIVE_FS_SIZE=1 export GITTEST_INVASIVE_MEMORY=1 export GITTEST_INVASIVE_SPEED=1 run_test invasive unset GITTEST_INVASIVE_FS_SIZE unset GITTEST_INVASIVE_MEMORY unset GITTEST_INVASIVE_SPEED fi if [ -z "$SKIP_ONLINE_TESTS" ]; then # Run the online tests. The "online" test suite only includes the # default online tests that do not require additional configuration. # The "proxy" and "ssh" test suites require further setup. echo "" echo "##############################################################################" echo "## Running (online) tests" echo "##############################################################################" export GITTEST_FLAKY_RETRY=5 run_test online unset GITTEST_FLAKY_RETRY # Run the online tests that immutably change global state separately # to avoid polluting the test environment. echo "" echo "##############################################################################" echo "## Running (online_customcert) tests" echo "##############################################################################" run_test online_customcert fi if [ -z "$SKIP_GITDAEMON_TESTS" ]; then echo "" echo "Running gitdaemon tests" echo "" export GITTEST_REMOTE_URL="git://localhost/test.git" run_test gitdaemon unset GITTEST_REMOTE_URL fi if [ -z "$SKIP_PROXY_TESTS" ]; then echo "" echo "Running proxy tests (Basic authentication)" echo "" export GITTEST_REMOTE_PROXY_HOST="localhost:8080" export GITTEST_REMOTE_PROXY_USER="foo" export GITTEST_REMOTE_PROXY_PASS="bar" run_test proxy unset GITTEST_REMOTE_PROXY_HOST unset GITTEST_REMOTE_PROXY_USER unset GITTEST_REMOTE_PROXY_PASS echo "" echo "Running proxy tests (NTLM authentication)" echo "" export GITTEST_REMOTE_PROXY_HOST="localhost:8090" export GITTEST_REMOTE_PROXY_USER="foo" export GITTEST_REMOTE_PROXY_PASS="bar" export GITTEST_FLAKY_RETRY=5 run_test proxy unset GITTEST_FLAKY_RETRY unset GITTEST_REMOTE_PROXY_HOST unset GITTEST_REMOTE_PROXY_USER unset GITTEST_REMOTE_PROXY_PASS fi if [ -z "$SKIP_NTLM_TESTS" ]; then echo "" echo "Running NTLM tests (IIS emulation)" echo "" export GITTEST_REMOTE_URL="http://localhost:9000/ntlm/test.git" export GITTEST_REMOTE_USER="foo" export GITTEST_REMOTE_PASS="baz" run_test auth_clone_and_push unset GITTEST_REMOTE_URL unset GITTEST_REMOTE_USER unset GITTEST_REMOTE_PASS echo "" echo "Running NTLM tests (Apache emulation)" echo "" export GITTEST_REMOTE_URL="http://localhost:9000/broken-ntlm/test.git" export GITTEST_REMOTE_USER="foo" export GITTEST_REMOTE_PASS="baz" run_test auth_clone_and_push unset GITTEST_REMOTE_URL unset GITTEST_REMOTE_USER unset GITTEST_REMOTE_PASS fi if [ -z "$SKIP_NEGOTIATE_TESTS" -a -n "$GITTEST_NEGOTIATE_PASSWORD" ]; then echo "" echo "Running SPNEGO tests" echo "" if [ "$(uname -s)" = "Darwin" ]; then KINIT_FLAGS="--password-file=STDIN" fi echo $GITTEST_NEGOTIATE_PASSWORD | kinit $KINIT_FLAGS [email protected] klist -5f export GITTEST_REMOTE_URL="https://test.libgit2.org/kerberos/empty.git" export GITTEST_REMOTE_DEFAULT="true" run_test auth_clone unset GITTEST_REMOTE_URL unset GITTEST_REMOTE_DEFAULT echo "" echo "Running SPNEGO tests (expect/continue)" echo "" export GITTEST_REMOTE_URL="https://test.libgit2.org/kerberos/empty.git" export GITTEST_REMOTE_DEFAULT="true" export GITTEST_REMOTE_EXPECTCONTINUE="true" run_test auth_clone unset GITTEST_REMOTE_URL unset GITTEST_REMOTE_DEFAULT unset GITTEST_REMOTE_EXPECTCONTINUE kdestroy -A fi if [ -z "$SKIP_SSH_TESTS" ]; then echo "" echo "Running ssh tests" echo "" export GITTEST_REMOTE_URL="ssh://localhost:2222/$SSHD_DIR/test.git" export GITTEST_REMOTE_USER=$USER export GITTEST_REMOTE_SSH_KEY="${HOME}/.ssh/id_rsa" export GITTEST_REMOTE_SSH_PUBKEY="${HOME}/.ssh/id_rsa.pub" export GITTEST_REMOTE_SSH_PASSPHRASE="" export GITTEST_REMOTE_SSH_FINGERPRINT="${SSH_FINGERPRINT}" run_test ssh unset GITTEST_REMOTE_URL unset GITTEST_REMOTE_USER unset GITTEST_REMOTE_SSH_KEY unset GITTEST_REMOTE_SSH_PUBKEY unset GITTEST_REMOTE_SSH_PASSPHRASE unset GITTEST_REMOTE_SSH_FINGERPRINT fi if [ -z "$SKIP_FUZZERS" ]; then echo "" echo "##############################################################################" echo "## Running fuzzers" echo "##############################################################################" ctest -V -R 'fuzzer' fi cleanup if [ "$SUCCESS" -ne 1 ]; then echo "Some tests failed." exit 1 fi echo "Success." exit 0
0
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2/ci/build.sh
#!/usr/bin/env bash # # Environment variables: # # SOURCE_DIR: Set to the directory of the libgit2 source (optional) # If not set, it will be derived relative to this script. set -e SOURCE_DIR=${SOURCE_DIR:-$( cd "$( dirname "${BASH_SOURCE[0]}" )" && dirname $( pwd ) )} BUILD_DIR=$(pwd) BUILD_PATH=${BUILD_PATH:=$PATH} CMAKE=$(which cmake) CMAKE_GENERATOR=${CMAKE_GENERATOR:-Unix Makefiles} if [[ "$(uname -s)" == MINGW* ]]; then BUILD_PATH=$(cygpath "$BUILD_PATH") fi indent() { sed "s/^/ /"; } echo "Source directory: ${SOURCE_DIR}" echo "Build directory: ${BUILD_DIR}" echo "" if [ "$(uname -s)" = "Darwin" ]; then echo "macOS version:" sw_vers | indent fi if [ -f "/etc/debian_version" ]; then echo "Debian version:" (source /etc/lsb-release && echo "${DISTRIB_DESCRIPTION}") | indent fi CORES=$(getconf _NPROCESSORS_ONLN || true) echo "Number of cores: ${CORES:-(Unknown)}" echo "Kernel version:" uname -a 2>&1 | indent echo "CMake version:" env PATH="${BUILD_PATH}" "${CMAKE}" --version 2>&1 | indent if test -n "${CC}"; then echo "Compiler version:" "${CC}" --version 2>&1 | indent fi echo "Environment:" if test -n "${CC}"; then echo "CC=${CC}" | indent fi if test -n "${CFLAGS}"; then echo "CFLAGS=${CFLAGS}" | indent fi echo "" echo "##############################################################################" echo "## Configuring build environment" echo "##############################################################################" echo cmake -DENABLE_WERROR=ON -DBUILD_EXAMPLES=ON -DBUILD_FUZZERS=ON -DUSE_STANDALONE_FUZZERS=ON -G \"${CMAKE_GENERATOR}\" ${CMAKE_OPTIONS} -S \"${SOURCE_DIR}\" env PATH="${BUILD_PATH}" "${CMAKE}" -DENABLE_WERROR=ON -DBUILD_EXAMPLES=ON -DBUILD_FUZZERS=ON -DUSE_STANDALONE_FUZZERS=ON -G "${CMAKE_GENERATOR}" ${CMAKE_OPTIONS} -S "${SOURCE_DIR}" echo "" echo "##############################################################################" echo "## Building libgit2" echo "##############################################################################" # Determine parallelism; newer cmake supports `--build --parallel` but # we cannot yet rely on that. if [ "${CMAKE_GENERATOR}" = "Unix Makefiles" -a "${CORES}" != "" ]; then BUILDER=(make -j ${CORES}) else BUILDER=("${CMAKE}" --build .) fi env PATH="${BUILD_PATH}" "${BUILDER[@]}"
0
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2/ci/getcontainer.sh
#!/bin/bash set -e IMAGE_NAME=$1 DOCKERFILE_PATH=$2 if [ "${IMAGE_NAME}" = "" ]; then echo "usage: $0 image_name [dockerfile]" exit 1 fi if [ "${DOCKERFILE_PATH}" = "" ]; then DOCKERFILE_PATH="${IMAGE_NAME}" fi if [ "${DOCKER_REGISTRY}" = "" ]; then echo "DOCKER_REGISTRY environment variable is unset." echo "Not running inside GitHub Actions or misconfigured?" exit 1 fi DOCKER_CONTAINER="${GITHUB_REPOSITORY}/${IMAGE_NAME}" DOCKER_REGISTRY_CONTAINER="${DOCKER_REGISTRY}/${DOCKER_CONTAINER}" echo "dockerfile=${DOCKERFILE_PATH}" >> $GITHUB_ENV echo "docker-container=${DOCKER_CONTAINER}" >> $GITHUB_ENV echo "docker-registry-container=${DOCKER_REGISTRY_CONTAINER}" >> $GITHUB_ENV # Identify the last git commit that touched the Dockerfiles # Use this as a hash to identify the resulting docker containers DOCKER_SHA=$(git log -1 --pretty=format:"%h" -- "${DOCKERFILE_PATH}") echo "docker-sha=${DOCKER_SHA}" >> $GITHUB_ENV DOCKER_REGISTRY_CONTAINER_SHA="${DOCKER_REGISTRY_CONTAINER}:${DOCKER_SHA}" echo "docker-registry-container-sha=${DOCKER_REGISTRY_CONTAINER_SHA}" >> $GITHUB_ENV echo "docker-registry-container-latest=${DOCKER_REGISTRY_CONTAINER}:latest" >> $GITHUB_ENV exists="true" docker login https://${DOCKER_REGISTRY} -u ${GITHUB_ACTOR} -p ${GITHUB_TOKEN} || exists="false" if [ "${exists}" != "false" ]; then docker pull ${DOCKER_REGISTRY_CONTAINER_SHA} || exists="false" fi if [ "${exists}" = "true" ]; then echo "docker-container-exists=true" >> $GITHUB_ENV else echo "docker-container-exists=false" >> $GITHUB_ENV fi
0
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2/ci/setup-mingw.sh
#!/bin/sh -e echo "##############################################################################" echo "## Downloading mingw" echo "##############################################################################" BUILD_TEMP=${BUILD_TEMP:=$TEMP} BUILD_TEMP=$(cygpath $BUILD_TEMP) case "$ARCH" in amd64) MINGW_URI="https://github.com/libgit2/ci-dependencies/releases/download/2021-05-04/mingw-x86_64-8.1.0-release-win32-sjlj-rt_v6-rev0.zip";; x86) MINGW_URI="https://github.com/libgit2/ci-dependencies/releases/download/2021-05-04/mingw-i686-8.1.0-release-win32-sjlj-rt_v6-rev0.zip";; esac if [ -z "$MINGW_URI" ]; then echo "No URL" exit 1 fi mkdir -p "$BUILD_TEMP" curl -s -L "$MINGW_URI" -o "$BUILD_TEMP"/mingw-"$ARCH".zip unzip -q "$BUILD_TEMP"/mingw-"$ARCH".zip -d "$BUILD_TEMP"
0
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2/ci/setup-osx.sh
#!/bin/sh set -x brew update brew install pkgconfig zlib curl openssl libssh2 ninja ln -s /Applications/Xcode.app/Contents/Developer/usr/lib/libLeaksAtExit.dylib /usr/local/lib
0
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2/script/sanitizers.supp
[undefined] # This library allows unaligned access on Intel-like processors. Prevent UBSan # from complaining about that. fun:sha1_compression_states
0
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2/script/valgrind.supp
{ ignore-zlib-errors-cond Memcheck:Cond obj:*libz.so* } { ignore-giterror-set-leak Memcheck:Leak ... fun:giterror_set } { ignore-git-global-state-leak Memcheck:Leak ... fun:git__global_state } { ignore-openssl-ssl-leak Memcheck:Leak ... obj:*libssl.so* ... } { ignore-openssl-crypto-leak Memcheck:Leak ... obj:*libcrypto.so* ... } { ignore-openssl-crypto-cond Memcheck:Cond obj:*libcrypto.so* ... } { ignore-openssl-init-leak Memcheck:Leak ... fun:git_openssl_stream_global_init ... } { ignore-openssl-legacy-init-leak Memcheck:Leak ... fun:OPENSSL_init_ssl__legacy ... } { ignore-openssl-malloc-leak Memcheck:Leak ... fun:git_openssl_malloc ... } { ignore-openssl-realloc-leak Memcheck:Leak ... fun:git_openssl_realloc ... } { ignore-glibc-getaddrinfo-cache Memcheck:Leak ... fun:__check_pf } { ignore-curl-global-init Memcheck:Leak ... fun:curl_global_init } { ignore-libssh2-init Memcheck:Leak ... fun:gcry_control fun:libssh2_init ... } { ignore-libssh2-session-create Memcheck:Leak ... fun:_git_ssh_session_create ... } { ignore-libssh2-setup-conn Memcheck:Leak ... fun:_git_ssh_setup_conn ... } { ignore-libssh2-gcrypt-control-leak Memcheck:Leak ... fun:gcry_control obj:*libssh2.so* } { ignore-libssh2-gcrypt-mpinew-leak Memcheck:Leak ... fun:gcry_mpi_new obj:*libssh2.so* } { ignore-libssh2-gcrypt-mpiscan-leak Memcheck:Leak ... fun:gcry_mpi_scan obj:*libssh2.so* ... } { ignore-libssh2-gcrypt-randomize-leak Memcheck:Leak ... fun:gcry_randomize obj:*libssh2.so* } { ignore-libssh2-gcrypt-sexpfindtoken-leak Memcheck:Leak ... fun:gcry_sexp_find_token obj:*libssh2.so* } { ignore-libssh2-gcrypt-pksign-leak Memcheck:Leak ... fun:gcry_pk_sign obj:*libssh2.so* } { ignore-libssh2-gcrypt-session-handshake Memcheck:Leak ... obj:*libssh2.so* obj:*libssh2.so* fun:libssh2_session_handshake ... } { ignore-openssl-undefined-in-read Memcheck:Cond ... obj:*libssl.so* ... fun:openssl_read ... } { ignore-openssl-undefined-in-connect Memcheck:Cond ... obj:*libssl.so* ... fun:openssl_connect ... } { ignore-libssh2-rsa-sha1-sign Memcheck:Leak ... obj:*libgcrypt.so* fun:_libssh2_rsa_sha1_sign ... } { ignore-libssh2-kexinit Memcheck:Leak ... obj:*libssh2.so* fun:kexinit ... } { ignore-noai6ai_cached-double-free Memcheck:Free fun:free fun:__libc_freeres ... fun:exit ... } { ignore-libcrypto-uninitialized-read-for-entropy Memcheck:Value8 ... obj:*libcrypto.so* ... } { ignore-dlopen-leak Memcheck:Leak ... fun:dlopen ... } { ignore-dlopen-leak Memcheck:Leak ... fun:_dlerror_run ... }
0
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2/script/thread-sanitizer.supp
# In attr_file_free, the locks are acquired in the opposite order in which they # are normally acquired. This is probably something worth fixing to have a # consistent lock hierarchy that is easy to understand. deadlock:attr_cache_lock # git_mwindow_file_register has the possibility of evicting some files from the # global cache. In order to avoid races and closing files that are currently # being accessed, before evicting any file it will attempt to acquire that # file's lock. Finally, git_mwindow_file_register is typically called with a # file lock held, because the caller will use the fd in the mwf immediately # after registering it. This causes ThreadSanitizer to observe different orders # of acquisition of the mutex (which implies a possibility of a deadlock), # _but_ since the files are added to the cache after other files have been # evicted, there cannot be a case where mwf A is trying to be registered while # evicting mwf B concurrently and viceversa: at most one of them can be present # in the cache. deadlock:git_mwindow_file_register # When invoking the time/timezone functions from git_signature_now(), they # access libc methods that need to be instrumented to correctly analyze the # data races. called_from_lib:libc.so.6 # TODO(#5592): Investigate and fix this. It can be triggered by the `thread` # test suite. race:git_filter_list__load_ext
0
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2/script/leaks.sh
#!/bin/sh export MallocStackLogging=1 export MallocScribble=1 export MallocLogFile=/dev/null export CLAR_AT_EXIT="leaks -quiet \$PPID" exec "$@"
0
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2/script/release.py
#!/usr/bin/env python from collections import namedtuple import argparse import base64 import copy import json import subprocess import sys import urllib.parse import urllib.request import urllib.error class Error(Exception): pass class Version(object): def __init__(self, version): versions = version.split(sep='.') if len(versions) < 2 or len(versions) > 3: raise Error("Invalid version string '{}'".format(version)) self.major = int(versions[0]) self.minor = int(versions[1]) self.revision = int(versions[2]) if len(versions) == 3 else 0 def __str__(self): return '{}.{}.{}'.format(self.major, self.minor, self.revision) def __eq__(self, other): return self.major == other.major and self.minor == other.minor and self.revision == other.revision def verify_version(version): expected = { 'VERSION': [ '"{}"'.format(version), None ], 'VER_MAJOR': [ str(version.major), None ], 'VER_MINOR': [ str(version.minor), None ], 'VER_REVISION': [ str(version.revision), None ], 'VER_PATCH': [ '0', None ], 'SOVERSION': [ '"{}.{}"'.format(version.major, version.minor), None ], } # Parse CMakeLists with open('CMakeLists.txt') as f: for line in f.readlines(): if line.startswith('project(libgit2 VERSION "{}"'.format(version)): break else: raise Error("cmake: invalid project definition") # Parse version.h with open('include/git2/version.h') as f: lines = f.readlines() for key in expected.keys(): define = '#define LIBGIT2_{} '.format(key) for line in lines: if line.startswith(define): expected[key][1] = line[len(define):].strip() break else: raise Error("version.h: missing define for '{}'".format(key)) for k, v in expected.items(): if v[0] != v[1]: raise Error("version.h: define '{}' does not match (got '{}', expected '{}')".format(k, v[0], v[1])) with open('package.json') as f: pkg = json.load(f) try: pkg_version = Version(pkg["version"]) except KeyError as err: raise Error("package.json: missing the field {}".format(err)) if pkg_version != version: raise Error("package.json: version does not match (got '{}', expected '{}')".format(pkg_version, version)) def generate_relnotes(tree, version): with open('docs/changelog.md') as f: lines = f.readlines() if not lines[0].startswith('v'): raise Error("changelog.md: missing section for v{}".format(version)) try: v = Version(lines[0][1:].strip()) except: raise Error("changelog.md: invalid version string {}".format(lines[0].strip())) if v != version: raise Error("changelog.md: changelog version doesn't match (got {}, expected {})".format(v, version)) if not lines[1].startswith('----'): raise Error("changelog.md: missing version header") if lines[2] != '\n': raise Error("changelog.md: missing newline after version header") for i, line in enumerate(lines[3:]): if not line.startswith('v'): continue try: Version(line[1:].strip()) break except: continue else: raise Error("changelog.md: cannot find section header of preceding release") return ''.join(lines[3:i + 3]).strip() def git(*args): process = subprocess.run([ 'git', *args ], stdout=subprocess.PIPE, stderr=subprocess.PIPE) if process.returncode != 0: raise Error('Failed executing git {}: {}'.format(' '.join(args), process.stderr.decode())) return process.stdout def post(url, data, contenttype, user, password): request = urllib.request.Request(url, data=data) request.add_header('Accept', 'application/json') request.add_header('Content-Type', contenttype) request.add_header('Content-Length', len(data)) request.add_header('Authorization', 'Basic ' + base64.b64encode('{}:{}'.format(user, password).encode()).decode()) try: response = urllib.request.urlopen(request) if response.getcode() != 201: raise Error("POST to '{}' failed: {}".format(url, response.reason)) except urllib.error.URLError as e: raise Error("POST to '{}' failed: {}".format(url, e)) data = json.load(response) return data def generate_asset(version, tree, archive_format): Asset = namedtuple('Asset', ['name', 'label', 'mimetype', 'data']) mimetype = 'application/{}'.format('gzip' if archive_format == 'tar.gz' else 'zip') return Asset( "libgit2-{}.{}".format(version, archive_format), "Release sources: libgit2-{}.{}".format(version, archive_format), mimetype, git('archive', '--format', archive_format, '--prefix', 'libgit2-{}/'.format(version), tree) ) def release(args): params = { "tag_name": 'v' + str(args.version), "name": 'libgit2 v' + str(args.version), "target_commitish": git('rev-parse', args.tree).decode().strip(), "body": generate_relnotes(args.tree, args.version), } assets = [ generate_asset(args.version, args.tree, 'tar.gz'), generate_asset(args.version, args.tree, 'zip'), ] if args.dryrun: for k, v in params.items(): print('{}: {}'.format(k, v)) for asset in assets: print('asset: name={}, label={}, mimetype={}, bytes={}'.format(asset.name, asset.label, asset.mimetype, len(asset.data))) return try: url = 'https://api.github.com/repos/{}/releases'.format(args.repository) response = post(url, json.dumps(params).encode(), 'application/json', args.user, args.password) except Error as e: raise Error('Could not create release: ' + str(e)) for asset in assets: try: url = list(urllib.parse.urlparse(response['upload_url'].split('{?')[0])) url[4] = urllib.parse.urlencode({ 'name': asset.name, 'label': asset.label }) post(urllib.parse.urlunparse(url), asset.data, asset.mimetype, args.user, args.password) except Error as e: raise Error('Could not upload asset: ' + str(e)) def main(): parser = argparse.ArgumentParser(description='Create a libgit2 release') parser.add_argument('--tree', default='HEAD', help='tree to create release for (default: HEAD)') parser.add_argument('--dryrun', action='store_true', help='generate release, but do not post it') parser.add_argument('--repository', default='libgit2/libgit2', help='GitHub repository to create repository in') parser.add_argument('--user', help='user to authenticate as') parser.add_argument('--password', help='password to authenticate with') parser.add_argument('version', type=Version, help='version of the new release') args = parser.parse_args() verify_version(args.version) release(args) if __name__ == '__main__': try: main() except Error as e: print(e) sys.exit(1)
0
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2/script/user_nodefs.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. */ #nodef GIT_ERROR_CHECK_ALLOC(ptr) if (ptr == NULL) { __coverity_panic__(); } #nodef GIT_ERROR_CHECK_ALLOC_BUF(buf) if (buf == NULL || git_buf_oom(buf)) { __coverity_panic__(); } #nodef GITERR_CHECK_ALLOC_ADD(out, one, two) \ if (GIT_ADD_SIZET_OVERFLOW(out, one, two)) { __coverity_panic__(); } #nodef GITERR_CHECK_ALLOC_ADD3(out, one, two, three) \ if (GIT_ADD_SIZET_OVERFLOW(out, one, two) || \ GIT_ADD_SIZET_OVERFLOW(out, *(out), three)) { __coverity_panic__(); } #nodef GITERR_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)) { __coverity_panic__(); } #nodef GITERR_CHECK_ALLOC_MULTIPLY(out, nelem, elsize) \ if (GIT_MULTIPLY_SIZET_OVERFLOW(out, nelem, elsize)) { __coverity_panic__(); } #nodef GIT_ERROR_CHECK_VERSION(S,V,N) if (git_error__check_version(S,V,N) < 0) { __coverity_panic__(); } #nodef LOOKS_LIKE_DRIVE_PREFIX(S) (strlen(S) >= 2 && git__isalpha((S)[0]) && (S)[1] == ':') #nodef git_vector_foreach(v, iter, elem) \ for ((iter) = 0; (v)->contents != NULL && (iter) < (v)->length && ((elem) = (v)->contents[(iter)], 1); (iter)++ ) #nodef git_vector_rforeach(v, iter, elem) \ for ((iter) = (v)->length - 1; (v)->contents != NULL && (iter) < SIZE_MAX && ((elem) = (v)->contents[(iter)], 1); (iter)-- )
0
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2/script/valgrind.sh
#!/bin/bash exec valgrind --leak-check=full --show-reachable=yes --error-exitcode=125 --num-callers=50 --suppressions="$(dirname "${BASH_SOURCE[0]}")/valgrind.supp" "$@"
0
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2/script/user_model.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. */ void *realloc(void *ptr, size_t size); void *memmove(void *dest, const void *src, size_t n); size_t strlen(const char *s); typedef struct va_list_str *va_list; typedef struct git_vector { void **contents; size_t length; } git_vector; typedef struct git_buf { char *ptr; size_t asize, size; } git_buf; int git_vector_insert(git_vector *v, void *element) { if (!v) __coverity_panic__(); v->contents = realloc(v->contents, ++v->length); if (!v->contents) __coverity_panic__(); v->contents[v->length] = element; return 0; } int git_buf_len(const struct git_buf *buf) { return strlen(buf->ptr); } int git_buf_vprintf(git_buf *buf, const char *format, va_list ap) { char ch, *s; size_t len; __coverity_string_null_sink__(format); __coverity_string_size_sink__(format); ch = *format; ch = *(char *)ap; buf->ptr = __coverity_alloc__(len); __coverity_writeall__(buf->ptr); buf->size = len; return 0; } int git_buf_put(git_buf *buf, const char *data, size_t len) { buf->ptr = __coverity_alloc__(buf->size + len + 1); memmove(buf->ptr + buf->size, data, len); buf->size += len; buf->ptr[buf->size + len] = 0; return 0; } int git_buf_set(git_buf *buf, const void *data, size_t len) { buf->ptr = __coverity_alloc__(len + 1); memmove(buf->ptr, data, len); buf->size = len + 1; return 0; } void clar__fail( const char *file, int line, const char *error, const char *description, int should_abort) { if (should_abort) __coverity_panic__(); } void clar__assert( int condition, const char *file, int line, const char *error, const char *description, int should_abort) { if (!condition && should_abort) __coverity_panic__(); }
0
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2/script/backport.sh
#!/bin/sh if test $# -eq 0 then echo "USAGE: $0 <#PR> [<#PR>...]" exit fi commits= for pr in $* do mergecommit=$(git rev-parse ":/Merge pull request #$pr" || exit 1) mergebase=$(git merge-base "$mergecommit"^1 "$mergecommit"^2 || exit 1) commits="$commits $(git rev-list --reverse "$mergecommit"^2 ^"$mergebase")" done echo "Cherry-picking the following commits:" git rev-list --no-walk --oneline $commits echo git cherry-pick $commits
0
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2/.vscode/launch.json
{ // Use IntelliSense to learn about possible attributes. // Hover to view descriptions of existing attributes. // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387 "version": "0.2.0", "configurations": [ { "name": "(gdb) Launch", "type": "cppdbg", "request": "launch", "program": "${workspaceFolder}/build/libgit2_clar", "args": [], "stopAtEntry": false, "cwd": "${fileDirname}", "environment": [], "externalConsole": false, "MIMode": "gdb", "setupCommands": [ { "description": "Enable pretty-printing for gdb", "text": "-enable-pretty-printing", "ignoreFailures": true } ] } ] }
0
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2/.vscode/tasks.json
{ // See https://go.microsoft.com/fwlink/?LinkId=733558 // for the documentation about the tasks.json format "version": "2.0.0", "tasks": [ { "label": "Build", "type": "shell", "command": "cd build && cmake --build . --parallel", "group": "build", "presentation": { "reveal": "always", "panel": "new" } }, { "label": "Run Tests", "type": "shell", "command": "build/libgit2_clar -v", "group": "test", "presentation": { "reveal": "always", "panel": "new" } } ] }