errors.c 2.41 KB
Newer Older
1
/*
schu committed
2
 * Copyright (C) 2009-2012 the libgit2 contributors
3
 *
Vicent Marti committed
4 5
 * This file is part of libgit2, distributed under the GNU GPL v2 with
 * a Linking Exception. For full terms see the included COPYING file.
6
 */
7
#include "common.h"
8
#include "global.h"
9
#include "posix.h"
10
#include "buffer.h"
11 12
#include <stdarg.h>

13 14 15 16
/********************************************
 * New error handling
 ********************************************/

17 18 19 20 21
static git_error g_git_oom_error = {
	"Out of memory",
	GITERR_NOMEMORY
};

22 23 24 25 26 27 28 29 30 31 32 33
static void set_error(int error_class, char *string)
{
	git_error *error = &GIT_GLOBAL->error_t;

	git__free(error->message);

	error->message = string;
	error->klass = error_class;

	GIT_GLOBAL->last_error = error;
}

34 35 36 37 38 39
void giterr_set_oom(void)
{
	GIT_GLOBAL->last_error = &g_git_oom_error;
}

void giterr_set(int error_class, const char *string, ...)
40
{
41
	git_buf buf = GIT_BUF_INIT;
42 43
	va_list arglist;

44 45 46 47 48 49 50 51 52 53
	int unix_error_code = 0;

#ifdef GIT_WIN32
	DWORD win32_error_code = 0;
#endif

	if (error_class == GITERR_OS) {
		unix_error_code = errno;
		errno = 0;

54
#ifdef GIT_WIN32
55 56
		win32_error_code = GetLastError();
		SetLastError(0);
57
#endif
58
	}
59

60
	va_start(arglist, string);
61
	git_buf_vprintf(&buf, string, arglist);
62 63
	va_end(arglist);

64
	/* automatically suffix strerror(errno) for GITERR_OS errors */
65
	if (error_class == GITERR_OS) {
66 67 68 69

		if (unix_error_code != 0) {
			git_buf_PUTS(&buf, ": ");
			git_buf_puts(&buf, strerror(unix_error_code));
70
		}
71

72
#ifdef GIT_WIN32
73
		else if (win32_error_code != 0) {
74
			LPVOID lpMsgBuf = NULL;
75 76 77 78 79

			FormatMessage(
				FORMAT_MESSAGE_ALLOCATE_BUFFER | 
				FORMAT_MESSAGE_FROM_SYSTEM |
				FORMAT_MESSAGE_IGNORE_INSERTS,
80
				NULL, win32_error_code, 0, (LPTSTR) &lpMsgBuf, 0, NULL);
81 82

			if (lpMsgBuf) {
83 84
				git_buf_PUTS(&buf, ": ");
				git_buf_puts(&buf, lpMsgBuf);
85 86 87 88
				LocalFree(lpMsgBuf);
			}
		}
#endif
89 90
	}

91 92
	if (!git_buf_oom(&buf))
		set_error(error_class, git_buf_detach(&buf));
93 94 95 96
}

void giterr_set_str(int error_class, const char *string)
{
97 98 99 100 101
	char *message;

	assert(string);

	message = git__strdup(string);
102

103 104
	if (message)
		set_error(error_class, message);
105 106
}

107 108 109 110 111 112 113
void giterr_set_regex(const regex_t *regex, int error_code)
{
	char error_buf[1024];
	regerror(error_code, regex, error_buf, sizeof(error_buf));
	giterr_set_str(GITERR_REGEX, error_buf);
}

114
void giterr_clear(void)
115
{
116
	GIT_GLOBAL->last_error = NULL;
117 118 119 120 121

	errno = 0;
#ifdef GIT_WIN32
	SetLastError(0);
#endif
122
}
123

124
const git_error *giterr_last(void)
125 126 127 128
{
	return GIT_GLOBAL->last_error;
}