Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -205,7 +205,9 @@ Operations are synchronous, `throws` (typed ``Libgit2Error``), and return
never authorized or accessed. Git's nonfatal relative-gitdir diagnostic is
returned by the live API or delivered after the scoped body through
`onDiagnostic`; GitKit prints nothing. Failure is atomic and writes stay
local. See [the contract and Git oracle results](docs/conditional-config.md).
local. An include chain deeper than git's ten levels throws
`ConfigIncludeDepthError` (`limit`, `includedPath`, `includingPath`), from
which a host can print git's `exceeded maximum include depth` message. See [the contract and Git oracle results](docs/conditional-config.md).
- **Operation configuration** — `Repository.withOperationConfiguration(_:_:)`
gives the same levels (`OperationConfiguration.Level.file` /
`.entries`) and command-line layers (`OperationConfiguration.layers`,
Expand Down
17 changes: 17 additions & 0 deletions Sources/CGitKit/include/gitkit_libgit2.h
Original file line number Diff line number Diff line change
Expand Up @@ -290,8 +290,25 @@ GIT_EXTERN(void) gitkit_config_scope_free(gitkit_config_scope *scope);
GIT_EXTERN(int) gitkit_config_scope_has_level(git_config_level_t level);
GIT_EXTERN(int) gitkit_config_scope_first_failure(
const gitkit_config_scope *scope, int *code, int *klass, const char **message);
/* For the failure _first_failure returns: 1 and its paths when it is an
* include-depth failure (see gitkit_config_include_depth_last), else 0. */
GIT_EXTERN(int) gitkit_config_scope_first_failure_include_depth(
const gitkit_config_scope *scope, int *limit, const char **included, const char **including);
GIT_EXTERN(void) gitkit_config_scope_mark_reported(int klass, const char *message);

/*
* GitKit addition, implemented in Sources/Clibgit2Patches/config_condition.c:
* the calling thread's newest "exceeded maximum include depth" failure (a
* GIT_ERROR_CONFIG error). Returns 1 and the depth limit, the resolved path
* of the file being included, the path of the file including it ("the
* command line" for a command-line include) and the libgit2 message it set,
* or 0 when there is none. The strings live until the next such failure on
* the thread or _clear. Used by GitKit's Swift layer; not a stable API.
*/
GIT_EXTERN(int) gitkit_config_include_depth_last(int *limit, const char **included,
const char **including, const char **message);
GIT_EXTERN(void) gitkit_config_include_depth_clear(void);

/*
* GitKit addition, implemented in Sources/Clibgit2Patches/worktree_patched.c:
* git_worktree_add(), which, when it fails after making the worktree's git
Expand Down
53 changes: 49 additions & 4 deletions Sources/Clibgit2Patches/config_condition.c
Original file line number Diff line number Diff line change
Expand Up @@ -309,6 +309,52 @@ int gitkit_condition_unexpanded(const char *path)
return -1;
}

/* The calling thread's newest include-depth failure, for the Swift layer to
* raise as a typed error when the libgit2 error it returns is this one. */
typedef struct {
char *included, *including, *message;
} gitkit_include_depth_record;
static GITKIT_TLS gitkit_include_depth_record depth_record;

void gitkit_config_include_depth_clear(void)
{
git__free(depth_record.included);
git__free(depth_record.including);
git__free(depth_record.message);
memset(&depth_record, 0, sizeof(depth_record));
}

int gitkit_condition_depth_exceeded(const char *included, const char *including)
{
const git_error *last;
/* Git names a command-line includer "the command line". */
if (!including)
including = "the command line";
git_error_set(GIT_ERROR_CONFIG, "exceeded maximum include depth (%d) while including '%s' from '%s'",
GITKIT_MAX_INCLUDE_DEPTH, included, including);
gitkit_config_include_depth_clear();
if ((last = git_error_last()) != NULL && last->message) {
depth_record.included = git__strdup(included);
depth_record.including = git__strdup(including);
depth_record.message = git__strdup(last->message);
if (!depth_record.included || !depth_record.including || !depth_record.message)
gitkit_config_include_depth_clear();
}
return -1;
}

int gitkit_config_include_depth_last(int *limit, const char **included,
const char **including, const char **message)
{
if (!depth_record.message)
return 0;
*limit = GITKIT_MAX_INCLUDE_DEPTH;
*included = depth_record.included;
*including = depth_record.including;
*message = depth_record.message;
return 1;
}

static int match_gitdir(int *matches, gitkit_condition_context *ctx, const char *condition,
const char *file, const char *value, int insensitive)
{
Expand Down Expand Up @@ -471,10 +517,9 @@ static int scan_file(url_scan *parent, const char *target, int conditional)
error = condition_read(&scan, parent->path, &content);
if (error == GIT_ENOTFOUND) { git_error_clear(); error = 0; }
else if (!error) {
if (scan.depth > 10) {
git_error_set(GIT_ERROR_CONFIG, "maximum config include depth reached");
error = -1;
} else error = scan_text(&scan, content.ptr, content.size);
if (scan.depth > GITKIT_MAX_INCLUDE_DEPTH)
error = gitkit_condition_depth_exceeded(path.ptr, parent->path);
else error = scan_text(&scan, content.ptr, content.size);
}
done:
git_str_dispose(&path);
Expand Down
5 changes: 2 additions & 3 deletions Sources/Clibgit2Patches/config_file_patched.c
Original file line number Diff line number Diff line change
Expand Up @@ -341,9 +341,8 @@ static int gitkit_read_include(config_file_parse_data *data, const char *target)
error = git_fs_path_set_error(errno, file->path, "stat");
goto done;
}
if (child.depth > 10) {
git_error_set(GIT_ERROR_CONFIG, "maximum config include depth reached");
error = -1;
if (child.depth > GITKIT_MAX_INCLUDE_DEPTH) {
error = gitkit_condition_depth_exceeded(file->path, data->file->path);
goto done;
}
if ((error = git_futils_readbuffer(&content, file->path)) < 0)
Expand Down
5 changes: 5 additions & 0 deletions Sources/Clibgit2Patches/gitkit_config_condition.h
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,11 @@ int gitkit_condition_path(git_str *out, const char *path, const char *from);
* fails as Git's expansion does. GitKit's Swift layer writes the same name. */
#define GITKIT_UNEXPANDED_PATH "gitkit-unexpanded-path"
int gitkit_condition_unexpanded(const char *path);
/* Git's MAX_INCLUDE_DEPTH. Raises the failure for an include past it, with
* the resolved target and the including file (NULL: the command line), and
* records both for gitkit_config_include_depth_last. Returns -1. */
#define GITKIT_MAX_INCLUDE_DEPTH 10
int gitkit_condition_depth_exceeded(const char *included, const char *including);
int gitkit_config_authorize(const git_repository *repo, const char *path, const char *from, int depth);
int gitkit_condition_build_begin(git_config *cfg, gitkit_condition_context *ctx);
void gitkit_condition_build_end(git_config *cfg);
Expand Down
45 changes: 44 additions & 1 deletion Sources/Clibgit2Patches/repository_patched.c
Original file line number Diff line number Diff line change
Expand Up @@ -131,6 +131,7 @@ typedef struct {
int klass;
char *message;
int reported; /* handed back by the call that failed */
char *included, *including; /* an include-depth failure's paths */
} gitkit_config_scope_failure;

typedef struct {
Expand Down Expand Up @@ -234,8 +235,11 @@ void gitkit_config_scope__release(gitkit_config_scope *scope)

for (i = 0; i < scope->levels_len; i++)
gitkit_scope_level_dispose(&scope->levels[i]);
for (i = 0; i < scope->failures_len; i++)
for (i = 0; i < scope->failures_len; i++) {
git__free(scope->failures[i].message);
git__free(scope->failures[i].included);
git__free(scope->failures[i].including);
}
git__free(scope->failures);
for (i = 0; i < scope->diagnostics_len; i++) {
git__free(scope->diagnostics[i].condition);
Expand Down Expand Up @@ -533,6 +537,28 @@ int gitkit_config_scope_first_failure(
return 0;
}

int gitkit_config_scope_first_failure_include_depth(
const gitkit_config_scope *scope, int *limit, const char **included, const char **including)
{
size_t i;

GIT_ASSERT_ARG(scope);

for (i = 0; i < scope->failures_len; i++) {
const gitkit_config_scope_failure *failure = &scope->failures[i];

if (failure->reported)
continue;
if (!failure->included || !failure->including)
return 0;
*limit = GITKIT_MAX_INCLUDE_DEPTH;
*included = failure->included;
*including = failure->including;
return 1;
}
return 0;
}

void gitkit_config_scope_mark_reported(int klass, const char *message)
{
gitkit_config_scope *scope = gitkit_current_scope;
Expand Down Expand Up @@ -570,6 +596,8 @@ void gitkit_config_scope__record(int code)
gitkit_config_scope *scope = gitkit_current_scope;
gitkit_config_scope_failure *grown;
const git_error *last;
const char *depth_message, *included, *including;
int limit;

if (!scope)
return;
Expand All @@ -590,11 +618,26 @@ void gitkit_config_scope__record(int code)
grown->klass = last ? last->klass : 0;
grown->message = git__strdup(last && last->message ? last->message : "unknown error");
grown->reported = 0;
grown->included = grown->including = NULL;

if (!grown->message) {
scope->failure_lost = 1;
return;
}
/* A later depth failure replaces the thread's record: keep its paths. */
if (last && last->klass == GIT_ERROR_CONFIG &&
gitkit_config_include_depth_last(&limit, &included, &including, &depth_message) &&
strcmp(depth_message, grown->message) == 0) {
grown->included = git__strdup(included);
grown->including = git__strdup(including);
if (!grown->included || !grown->including) {
git__free(grown->included);
git__free(grown->including);
git__free(grown->message);
scope->failure_lost = 1;
return;
}
}
scope->failures_len++;
}

Expand Down
61 changes: 61 additions & 0 deletions Sources/GitKit/ConfigIncludeDepthError.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
import Foundation
import CGitKit

/// A config include chain went deeper than git allows: following an
/// `[include]` or `[includeIf]` would read an eleventh nested file.
///
/// Thrown in place of the ``Libgit2Error`` libgit2 returns for it, whether
/// the config was being read or `hasconfig:remote.*.url:` was collecting
/// URLs. Git 2.54 reports the same case as
///
/// ```
/// fatal: exceeded maximum include depth (10) while including
/// <includedPath>
/// from
/// <includingPath>
/// This might be due to circular includes.
/// ```
///
/// and exits 128. Git checks that a target exists before it counts depth,
/// and so does GitKit: a missing target is empty, never this error.
public struct ConfigIncludeDepthError: Error, LocalizedError, Sendable, Equatable {
/// The deepest include git follows: 10.
public let limit: Int
/// The file whose include went past ``limit``, resolved as git prints
/// it (a relative target joined to its includer's directory).
public let includedPath: String
/// The file that names ``includedPath``. Git calls a command-line
/// includer `the command line`; with ``limit`` at 10 the includer is
/// always a file, so in practice this is a path.
public let includingPath: String

/// Memberwise init.
public init(limit: Int, includedPath: String, includingPath: String) {
self.limit = limit
self.includedPath = includedPath
self.includingPath = includingPath
}

/// Git's message without its `fatal: ` prefix.
public var errorDescription: String? {
"exceeded maximum include depth (\(limit)) while including\n\t\(includedPath)\nfrom\n\t\(includingPath)\n"
+ "This might be due to circular includes."
}

/// The typed error for `error` when it is the calling thread's newest
/// include-depth failure, which is then forgotten.
static func take(matching error: Libgit2Error) -> ConfigIncludeDepthError? {
guard error.klass == Int32(GIT_ERROR_CONFIG.rawValue) else { return nil }
var limit: Int32 = 0
var included: UnsafePointer<CChar>?
var including: UnsafePointer<CChar>?
var message: UnsafePointer<CChar>?
guard gitkit_config_include_depth_last(&limit, &included, &including, &message) == 1,
let included, let including, let message,
String(cString: message) == error.message else { return nil }
let typed = ConfigIncludeDepthError(limit: Int(limit), includedPath: String(cString: included),
includingPath: String(cString: including))
gitkit_config_include_depth_clear()
return typed
}
}
4 changes: 3 additions & 1 deletion Sources/GitKit/Libgit2Error.swift
Original file line number Diff line number Diff line change
Expand Up @@ -40,14 +40,16 @@ public struct Libgit2Error: Error, LocalizedError, Sendable {
}
}

/// Throws ``Libgit2Error`` (or a pending ``GitFilterError``) if `rc < 0`. Returns `rc` otherwise so the
/// Throws ``Libgit2Error`` (or a pending ``GitFilterError`` or the
/// ``ConfigIncludeDepthError`` it reports) if `rc < 0`. Returns `rc` otherwise so the
/// caller can use it (some libgit2 APIs return the count on success).
@discardableResult
func check(_ rc: Int32) throws -> Int32 {
if rc < 0 {
let error = Libgit2Error.last(code: rc)
OperationConfigurationScope.markReported(error)
if let filterError = PendingFilterError.take(matching: error) { throw filterError }
if let depthError = ConfigIncludeDepthError.take(matching: error) { throw depthError }
throw error
}
return rc
Expand Down
13 changes: 12 additions & 1 deletion Sources/GitKit/OperationConfiguration.swift
Original file line number Diff line number Diff line change
Expand Up @@ -267,11 +267,22 @@ final class OperationConfigurationScope {
precondition(rc == 0, "operation configuration scope popped out of order")
}

func firstFailure() -> Libgit2Error? {
/// The first failure not handed back, typed when it is an include-depth
/// failure: the scope keeps each one's paths, as later ones replace the
/// thread's record.
func firstFailure() -> Error? {
var code: Int32 = 0
var klass: Int32 = 0
var message: UnsafePointer<CChar>?
guard gitkit_config_scope_first_failure(pointer, &code, &klass, &message) == 1 else { return nil }
var limit: Int32 = 0
var included: UnsafePointer<CChar>?
var including: UnsafePointer<CChar>?
if gitkit_config_scope_first_failure_include_depth(pointer, &limit, &included, &including) == 1,
let included, let including {
return ConfigIncludeDepthError(limit: Int(limit), includedPath: String(cString: included),
includingPath: String(cString: including))
}
return Libgit2Error(code: code, klass: klass, message: message.map { String(cString: $0) } ?? "unknown error")
}

Expand Down
18 changes: 16 additions & 2 deletions Tests/GitKitPublicAPITests/ConditionalConfigConsumerTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -360,17 +360,31 @@ struct ConditionalConfigConsumerTests {
func includeDepth() throws {
defer { cleanUp() }
let repository = try Repository.initialize(at: root.appendingPathComponent("repo"), initialBranch: "main")
var included = try write("[test]\nvalue = deepest\n", "depth-10")
let deepest = try write("[test]\nvalue = deepest\n", "depth-10")
var included = deepest
for depth in (1...9).reversed() {
included = try write("[include]\npath = \(included.path)\n", "depth-\(depth)")
}
try repository.setCommandLineConfig(CommandLineConfig([.include(path: included.path)]))
#expect(try repository.configGet("test.value") == "deepest")
let extra = try write("[include]\npath = \(included.path)\n", "depth-0")
#expect(throws: Libgit2Error.self) {
// Git names the eleventh file and the tenth, which includes it.
let expected = ConfigIncludeDepthError(
limit: 10, includedPath: deepest.path,
includingPath: root.appendingPathComponent("depth-9").path)
#expect(throws: expected) {
try repository.setCommandLineConfig(CommandLineConfig([.include(path: extra.path)]))
}
#expect(try repository.configGet("test.value") == "deepest")
// The hasconfig URL pre-scan reads even a nonmatching target's chain.
#expect(throws: expected) {
try repository.setCommandLineConfig(CommandLineConfig([
.includeIf(condition: "hasconfig:remote.*.url:never", path: extra.path)]))
}
#expect(try repository.configGet("test.value") == "deepest")
#expect(expected.localizedDescription == "exceeded maximum include depth (10) while including\n\t"
+ "\(deepest.path)\nfrom\n\t\(root.appendingPathComponent("depth-9").path)\n"
+ "This might be due to circular includes.")
// Git checks existence before counting depth: a missing eleventh
// target is empty, not a depth failure, also during URL collection.
try Data("[test]\nvalue = deepest\n[include]\npath = absent\n".utf8)
Expand Down
11 changes: 11 additions & 0 deletions Tests/GitKitTests/GitFiltersTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,10 @@ struct GitFiltersTests {
return (dir, try Repository.open(at: dir))
}

private static func real(_ url: URL) -> String {
url.resolvingSymlinksInPath().standardizedFileURL.path
}

private func requireDriver(in dir: URL) throws {
try git(["config", "filter.\(name).required", "true"], in: dir)
}
Expand Down Expand Up @@ -292,8 +296,14 @@ struct GitFiltersTests {
try git(["rm", ".gitattributes"], in: dir)
let driver = name
let registeredName = name + "-registration"
let gitDirectory = Self.real(dir.appendingPathComponent(".git"))
let observations = Observations()
// `filter=*` matches every filtered file in the process, so a concurrent
// suite's checkout can reach this callback; pass its files through.
try GitFilters.register(name: registeredName, attributes: "filter=*", smudge: { source, input in
guard Self.real(source.gitDirectory) == gitDirectory else { return nil }
#expect(source.driver == driver)
observations.record(input.count)
return input
})
defer { try? GitFilters.unregister(name: registeredName) }
Expand All @@ -306,6 +316,7 @@ struct GitFiltersTests {
defer { git_buf_dispose(&result) }
try check(git_filter_list_apply_to_buffer(&result, filters, "hello\n", 6))
#expect(result.size == 6)
#expect(observations.chunks == [6])
}

@Test("The guard rejects missing required drivers, but permits optional ones")
Expand Down
Loading
Loading