1 /*
2  *    Copyright Andrej Mitrovic 2013, David Nadlinger 2014.
3  *  Distributed under the Boost Software License, Version 1.0.
4  *     (See accompanying file LICENSE_1_0.txt or copy at
5  *           http://www.boost.org/LICENSE_1_0.txt)
6  */
7 module git.util;
8 
9 /**
10     Contains utility functions for this package.
11 */
12 
13 import std.array;
14 import std.conv;
15 import std.exception;
16 import std.string;
17 
18 import git2.errors;
19 
20 import git.exception;
21 
22 /**
23     Require the result to be either 1 or 0. If it is, return the boolean value,
24     otherwise throw a GitException.
25 */
26 package bool requireBool(int result, string file = __FILE__, size_t line = __LINE__)
27 {
28     require(result == 0 || result == 1);
29     return result == 1;
30 }
31 
32 /**
33     Call this function when an error code is returned from a git function.
34     It will retrieve the last error and throw a GitException.
35 
36     $(RED Note:) assert or in blocks should be used to verify arguments (such as strings)
37     before calling Git functions since Git itself does not check pointers for null.
38     Passing null pointers to Git functions usually results in access violations.
39 */
40 package void require(bool state, string file = __FILE__, size_t line = __LINE__)
41 {
42     if (state)
43         return;
44 
45     const(git_error)* gitError = giterr_last();
46 
47     enforce(gitError !is null,
48         "Error: No Git error thrown, error condition check is likely invalid.");
49 
50     const msg = format("Git error (%s): %s.", cast(git_error_t)gitError.klass, to!string(gitError.message));
51 
52     giterr_clear();
53     throw new GitException(msg, file, line);
54 }
55 
56 ///
57 unittest
58 {
59     import git2.oid;
60     git_oid oid;
61     assertThrown!GitException(require(git_oid_fromstr(&oid, "foobar") == 0));
62 }
63 
64 /** Return a posix-native path, replacing backslashes with forward slashes. */
65 string toPosixPath(string input)
66 {
67     return input.replace(r"\", "/");
68 }
69 
70 ///
71 unittest
72 {
73     assert(r"foo/bar\doo".toPosixPath == r"foo/bar/doo");
74 }
75 
76 alias toSlice = to!(const(char)[]);
77 
78 /**
79     Converts the passed char slice to a C string, returning the null pointer for
80     empty strings.
81 
82     libgit2 generally only switches to the default for optional string
83     parameters if they are null, vs. just the empty string.
84 */
85 const(char)* gitStr(const(char)[] s)
86 {
87     import std.conv : toStringz;
88     return s.length ? s.toStringz : null;
89 }