diff --git a/.gitignore b/.gitignore index b193eb3f5..7caa37186 100644 --- a/.gitignore +++ b/.gitignore @@ -2,16 +2,6 @@ *.swp *~.nib -build/* -.build/* -build-iPhoneSimulator/* -build-iPhoneOS/* -objective-git.bridgesupport -ObjectiveGitFramework/build/* -ObjectiveGit-iOS.framework/* -External/libgit2*.a -External/libgit2-ios - *.pbxuser *.perspective *.perspectivev3 @@ -19,13 +9,10 @@ External/libgit2-ios *.mode1v3 *.mode2v3 -project.xcworkspace */xcuserdata/ *.xccheckout +*.xcscmblueprint -ObjectiveGitTests/fixtures/Fixtures/* - -External/ios-openssl/include -External/ios-openssl/lib +External/libgit2-mac.a +Carthage/Build -External/libssh2-ios diff --git a/.gitmodules b/.gitmodules index 9248e633f..0d7955b21 100644 --- a/.gitmodules +++ b/.gitmodules @@ -1,15 +1,21 @@ [submodule "libgit2"] path = External/libgit2 url = https://github.com/libgit2/libgit2.git -[submodule "Configuration"] - path = External/Configuration - url = https://github.com/jspahrsummers/xcconfigs.git [submodule "openssl"] path = External/openssl url = https://github.com/openssl/openssl.git [submodule "libssh2"] path = External/libssh2 - url = git://git.libssh2.org/libssh2.git -[submodule "External/Quick"] - path = External/Quick - url = https://github.com/github/Quick.git + url = https://github.com/libssh2/libssh2.git +[submodule "Carthage/Checkouts/Nimble"] + path = Carthage/Checkouts/Nimble + url = https://github.com/Quick/Nimble.git +[submodule "Carthage/Checkouts/Quick"] + path = Carthage/Checkouts/Quick + url = https://github.com/Quick/Quick.git +[submodule "Carthage/Checkouts/xcconfigs"] + path = Carthage/Checkouts/xcconfigs + url = https://github.com/jspahrsummers/xcconfigs.git +[submodule "Carthage/Checkouts/ZipArchive"] + path = Carthage/Checkouts/ZipArchive + url = https://github.com/ZipArchive/ZipArchive.git diff --git a/.travis.yml b/.travis.yml index a6638609f..52c7d6dcc 100644 --- a/.travis.yml +++ b/.travis.yml @@ -1,13 +1,28 @@ +# +# .travis.yml +# Objective-Git +# +# https://docs.travis-ci.com/user/reference/osx/ +# https://docs.travis-ci.com/user/build-stages/matrix-expansion/ +# +--- +os: osx +osx_image: xcode12.2 language: objective-c -install: -- brew install cmake + +matrix: + fast_finish: true + include: + - env: + - SCHEME="ObjectiveGit Mac" + - env: + - SCHEME="ObjectiveGit iOS" + +before_install: + - gem install xcpretty + - gem install xcpretty-travis-formatter +install: script/bootstrap script: script/cibuild + notifications: email: false - campfire: - on_success: always - on_failure: always - template: - - "Build %{build_url} of %{repository}: %{message}" - rooms: - secure: IxO/lskcwkcrvbgq9UsI4rjD7auSbbc52QdOcEzh5klXf6KkmIRSrJDUbsRGJ6GahlB0ELfgTcr0ycqsYhW5M9mNwzWR1cerbedA2HT0sOy7uvgGQwAY+iiikCsIMuYQJ1qvb6DrrpgyejQWXW5cOEVbNuoPV45DE0lsPUHcpyg= diff --git a/Cartfile b/Cartfile new file mode 100644 index 000000000..e69de29bb diff --git a/Cartfile.private b/Cartfile.private new file mode 100644 index 000000000..b021ce726 --- /dev/null +++ b/Cartfile.private @@ -0,0 +1,4 @@ +github "jspahrsummers/xcconfigs" "master" +github "Quick/Quick" ~> 2.1.0 +github "Quick/Nimble" ~> 8.0.1 +github "ZipArchive/ZipArchive" ~> 2.2.3 diff --git a/Cartfile.resolved b/Cartfile.resolved new file mode 100644 index 000000000..1b6153da6 --- /dev/null +++ b/Cartfile.resolved @@ -0,0 +1,4 @@ +github "Quick/Nimble" "v8.1.2" +github "Quick/Quick" "v2.2.1" +github "ZipArchive/ZipArchive" "v2.2.3" +github "jspahrsummers/xcconfigs" "4ced0ad5a971220917994a4edfa6abf9702e3818" diff --git a/Carthage/Checkouts/Nimble b/Carthage/Checkouts/Nimble new file mode 160000 index 000000000..7a46a5fc8 --- /dev/null +++ b/Carthage/Checkouts/Nimble @@ -0,0 +1 @@ +Subproject commit 7a46a5fc86cb917f69e3daf79fcb045283d8f008 diff --git a/Carthage/Checkouts/Quick b/Carthage/Checkouts/Quick new file mode 160000 index 000000000..09b3becb3 --- /dev/null +++ b/Carthage/Checkouts/Quick @@ -0,0 +1 @@ +Subproject commit 09b3becb37cb2163919a3842a4c5fa6ec7130792 diff --git a/Carthage/Checkouts/ZipArchive b/Carthage/Checkouts/ZipArchive new file mode 160000 index 000000000..f3379e6ef --- /dev/null +++ b/Carthage/Checkouts/ZipArchive @@ -0,0 +1 @@ +Subproject commit f3379e6efa93e657293573ad196302b94041e464 diff --git a/Carthage/Checkouts/xcconfigs b/Carthage/Checkouts/xcconfigs new file mode 160000 index 000000000..4ced0ad5a --- /dev/null +++ b/Carthage/Checkouts/xcconfigs @@ -0,0 +1 @@ +Subproject commit 4ced0ad5a971220917994a4edfa6abf9702e3818 diff --git a/English.lproj/InfoPlist.strings b/English.lproj/InfoPlist.strings deleted file mode 100644 index 88f65cf6e..000000000 --- a/English.lproj/InfoPlist.strings +++ /dev/null @@ -1,2 +0,0 @@ -/* Localized versions of Info.plist keys */ - diff --git a/External/Configuration b/External/Configuration deleted file mode 160000 index 6c7a02a43..000000000 --- a/External/Configuration +++ /dev/null @@ -1 +0,0 @@ -Subproject commit 6c7a02a43954c74d2be1d2fcf7bfd65a263e7c52 diff --git a/External/Quick b/External/Quick deleted file mode 160000 index ec6d0deaf..000000000 --- a/External/Quick +++ /dev/null @@ -1 +0,0 @@ -Subproject commit ec6d0deaf8b22efa7c6f97d42d1994b57eb871a0 diff --git a/External/libcrypto.a b/External/libcrypto.a deleted file mode 120000 index fe603c877..000000000 --- a/External/libcrypto.a +++ /dev/null @@ -1 +0,0 @@ -/usr/local/opt/openssl/lib/libcrypto.a \ No newline at end of file diff --git a/External/libextobjc/extobjc/EXTScope.h b/External/libextobjc/extobjc/EXTScope.h index c835438cd..5c68469f6 100644 --- a/External/libextobjc/extobjc/EXTScope.h +++ b/External/libextobjc/extobjc/EXTScope.h @@ -88,7 +88,7 @@ _Pragma("clang diagnostic pop") /*** implementation details follow ***/ -typedef void (^gt_ext_cleanupBlock_t)(); +typedef void (^gt_ext_cleanupBlock_t)(void); void gt_ext_executeCleanupBlock (__strong gt_ext_cleanupBlock_t *block); diff --git a/External/libgit2 b/External/libgit2 index 4bb6ffb6b..1a107fac0 160000 --- a/External/libgit2 +++ b/External/libgit2 @@ -1 +1 @@ -Subproject commit 4bb6ffb6bb8ad9d49eb173350be965183cd09c96 +Subproject commit 1a107fac0fc88a4d74b64ffc9ae2fd178ba631c0 diff --git a/External/libssh2 b/External/libssh2 index f1cfa55b6..f15b1e297 160000 --- a/External/libssh2 +++ b/External/libssh2 @@ -1 +1 @@ -Subproject commit f1cfa55b6064ba18fc0005713ed790da579361b5 +Subproject commit f15b1e297f72882214988101ccdc5e6ad30d7e6e diff --git a/External/libssl.a b/External/libssl.a deleted file mode 120000 index e321f3268..000000000 --- a/External/libssl.a +++ /dev/null @@ -1 +0,0 @@ -/usr/local/opt/openssl/lib/libssl.a \ No newline at end of file diff --git a/External/openssl b/External/openssl index 872e681c0..e71ebf275 160000 --- a/External/openssl +++ b/External/openssl @@ -1 +1 @@ -Subproject commit 872e681c00a713e840ebed77a4e05fa0e181f16f +Subproject commit e71ebf275da66dfd601c92e0e80a35114c32f6f8 diff --git a/Info.plist b/Info.plist index c61e7624f..d3de8eefb 100644 --- a/Info.plist +++ b/Info.plist @@ -7,7 +7,7 @@ CFBundleExecutable $(EXECUTABLE_NAME) CFBundleIdentifier - org.libgit2.$(PRODUCT_NAME:rfc1034identifier) + $(PRODUCT_BUNDLE_IDENTIFIER) CFBundleInfoDictionaryVersion 6.0 CFBundleName diff --git a/LICENSE b/LICENSE index 5da811ff5..f9769cde8 100644 --- a/LICENSE +++ b/LICENSE @@ -1,6 +1,6 @@ The MIT License -Copyright (c) 2012 libgit2 contributors +Copyright (c) 2016 libgit2 contributors Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal diff --git a/ObjectiveGit.modulemap b/ObjectiveGit.modulemap new file mode 100644 index 000000000..3ef32bc58 --- /dev/null +++ b/ObjectiveGit.modulemap @@ -0,0 +1,146 @@ +framework module ObjectiveGit { + umbrella header "ObjectiveGit.h" + + header "git2/attr.h" + header "git2/blob.h" + header "git2/blame.h" + header "git2/branch.h" + header "git2/buffer.h" + header "git2/checkout.h" + header "git2/cherrypick.h" + header "git2/clone.h" + header "git2/commit.h" + header "git2/common.h" + header "git2/config.h" + header "git2/describe.h" + header "git2/diff.h" + header "git2/errors.h" + header "git2/filter.h" + header "git2/graph.h" + header "git2/ignore.h" + header "git2/index.h" + header "git2/indexer.h" + header "git2/merge.h" + header "git2/message.h" + header "git2/net.h" + header "git2/notes.h" + header "git2/object.h" + header "git2/odb.h" + header "git2/odb_backend.h" + header "git2/oid.h" + header "git2/pack.h" + header "git2/patch.h" + header "git2/pathspec.h" + header "git2/refdb.h" + header "git2/reflog.h" + header "git2/refs.h" + header "git2/refspec.h" + header "git2/remote.h" + header "git2/repository.h" + header "git2/reset.h" + header "git2/revert.h" + header "git2/revparse.h" + header "git2/revwalk.h" + header "git2/signature.h" + header "git2/stash.h" + header "git2/status.h" + header "git2/submodule.h" + header "git2/tag.h" + header "git2/transport.h" + header "git2/tree.h" + header "git2/types.h" + header "git2/version.h" + header "git2/sys/commit.h" + header "git2/sys/config.h" + header "git2/sys/diff.h" + header "git2/sys/filter.h" + header "git2/sys/hashsig.h" + header "git2/sys/index.h" + header "git2/sys/mempack.h" + header "git2/sys/merge.h" + header "git2/sys/odb_backend.h" + header "git2/sys/refdb_backend.h" + header "git2/sys/reflog.h" + header "git2/sys/refs.h" + header "git2/sys/repository.h" + header "git2/sys/transport.h" + header "git2/sys/time.h" + header "git2/cred_helpers.h" + header "git2/sys/openssl.h" + header "git2/sys/stream.h" + header "git2/trace.h" + + exclude header "git2/inttypes.h" + exclude header "git2/stdint.h" + exclude header "git2/sys/git2/annotated_commit.h" + exclude header "git2/sys/git2/attr.h" + exclude header "git2/sys/git2/blame.h" + exclude header "git2/sys/git2/blob.h" + exclude header "git2/sys/git2/branch.h" + exclude header "git2/sys/git2/buffer.h" + exclude header "git2/sys/git2/checkout.h" + exclude header "git2/sys/git2/cherrypick.h" + exclude header "git2/sys/git2/clone.h" + exclude header "git2/sys/git2/commit.h" + exclude header "git2/sys/git2/cred_helpers.h" + exclude header "git2/sys/git2/describe.h" + exclude header "git2/sys/git2/errors.h" + exclude header "git2/sys/git2/global.h" + exclude header "git2/sys/git2/graph.h" + exclude header "git2/sys/git2/ignore.h" + exclude header "git2/sys/git2/index.h" + exclude header "git2/sys/git2/indexer.h" + exclude header "git2/sys/git2/inttypes.h" + exclude header "git2/sys/git2/merge.h" + exclude header "git2/sys/git2/message.h" + exclude header "git2/sys/git2/notes.h" + exclude header "git2/sys/git2/object.h" + exclude header "git2/sys/git2/odb_backend.h" + exclude header "git2/sys/git2/oidarray.h" + exclude header "git2/sys/git2/pack.h" + exclude header "git2/sys/git2/patch.h" + exclude header "git2/sys/git2/pathspec.h" + exclude header "git2/sys/git2/rebase.h" + exclude header "git2/sys/git2/refdb.h" + exclude header "git2/sys/git2/reflog.h" + exclude header "git2/sys/git2/refs.h" + exclude header "git2/sys/git2/refspec.h" + exclude header "git2/sys/git2/remote.h" + exclude header "git2/sys/git2/repository.h" + exclude header "git2/sys/git2/reset.h" + exclude header "git2/sys/git2/revert.h" + exclude header "git2/sys/git2/revparse.h" + exclude header "git2/sys/git2/revwalk.h" + exclude header "git2/sys/git2/signature.h" + exclude header "git2/sys/git2/stash.h" + exclude header "git2/sys/git2/stdint.h" + exclude header "git2/sys/git2/strarray.h" + exclude header "git2/sys/git2/submodule.h" + exclude header "git2/sys/git2/tag.h" + exclude header "git2/sys/git2/trace.h" + exclude header "git2/sys/git2/transaction.h" + exclude header "git2/sys/git2/transport.h" + exclude header "git2/sys/git2/tree.h" + exclude header "git2/sys/git2/version.h" + exclude header "git2/sys/git2/sys/commit.h" + exclude header "git2/sys/git2/sys/config.h" + exclude header "git2/sys/git2/sys/diff.h" + exclude header "git2/sys/git2/sys/filter.h" + exclude header "git2/sys/git2/sys/hashsig.h" + exclude header "git2/sys/git2/sys/index.h" + exclude header "git2/sys/git2/sys/mempack.h" + exclude header "git2/sys/git2/sys/merge.h" + exclude header "git2/sys/git2/sys/odb_backend.h" + exclude header "git2/sys/git2/sys/openssl.h" + exclude header "git2/sys/git2/sys/refdb_backend.h" + exclude header "git2/sys/git2/sys/reflog.h" + exclude header "git2/sys/git2/sys/refs.h" + exclude header "git2/sys/git2/sys/repository.h" + exclude header "git2/sys/git2/sys/stream.h" + exclude header "git2/sys/git2/sys/time.h" + exclude header "git2/sys/git2/sys/transport.h" + exclude header "git2/sys/git2/sys/worktree.h" + + export * + module * { export * } +} diff --git a/ObjectiveGit/Categories/NSData+Git.m b/ObjectiveGit/Categories/NSData+Git.m index 2f06dd9fc..6498dfbe0 100644 --- a/ObjectiveGit/Categories/NSData+Git.m +++ b/ObjectiveGit/Categories/NSData+Git.m @@ -17,7 +17,7 @@ - (BOOL)git_getOid:(git_oid *)oid error:(NSError **)error { if ([self length] != sizeof(git_oid)) { if (error != NULL) { *error = [NSError errorWithDomain:GTGitErrorDomain - code:GITERR_INVALID + code:GIT_ERROR_INVALID userInfo: [NSDictionary dictionaryWithObject:@"can't extract oid from data of incorrect length" forKey:NSLocalizedDescriptionKey]]; diff --git a/ObjectiveGit/Categories/NSError+Git.h b/ObjectiveGit/Categories/NSError+Git.h index bfe453dc0..4f7532f62 100644 --- a/ObjectiveGit/Categories/NSError+Git.h +++ b/ObjectiveGit/Categories/NSError+Git.h @@ -29,8 +29,12 @@ #import +/// The error domain used by Objective-Git extern NSString * const GTGitErrorDomain; +/// Error userinfo keys +extern NSString * const GTGitErrorOID; + @interface NSError (Git) /// Describes the given libgit2 error code, using any message provided by diff --git a/ObjectiveGit/Categories/NSError+Git.m b/ObjectiveGit/Categories/NSError+Git.m index cbc31509b..422b32d1f 100644 --- a/ObjectiveGit/Categories/NSError+Git.m +++ b/ObjectiveGit/Categories/NSError+Git.m @@ -31,6 +31,7 @@ #import "git2/errors.h" NSString * const GTGitErrorDomain = @"GTGitErrorDomain"; +NSString * const GTGitErrorOID = @"GTOID"; @implementation NSError (Git) @@ -97,10 +98,10 @@ + (NSError *)git_errorFor:(int)code { } + (NSString *)git_descriptionForErrorCode:(int)code { - const git_error *gitLastError = giterr_last(); + const git_error *gitLastError = git_error_last(); if (gitLastError != NULL) { return @(gitLastError->message); - } else if (code == GITERR_OS) { + } else if (code == GIT_ERROR_OS) { return @(strerror(errno)); } else { return nil; diff --git a/ObjectiveGit/GTBlame.h b/ObjectiveGit/GTBlame.h index ec931424f..12db9a5c2 100644 --- a/ObjectiveGit/GTBlame.h +++ b/ObjectiveGit/GTBlame.h @@ -12,14 +12,22 @@ @class GTBlameHunk; @class GTRepository; -/// A `GTBlame` provides authorship info, through `GTBlameHunk` for each line of a file. +NS_ASSUME_NONNULL_BEGIN + +/// A `GTBlame` provides authorship info, through `GTBlameHunk` for each line of a file. Analogous to `git_blame` in libgit2. @interface GTBlame : NSObject +- (instancetype)init NS_UNAVAILABLE; + /// Designated initializer. -- (instancetype)initWithGitBlame:(git_blame *)blame; +/// +/// blame - A git_blame to wrap. May not be NULL. +/// +/// Returns a blame, or nil if initialization failed. +- (instancetype _Nullable)initWithGitBlame:(git_blame *)blame NS_DESIGNATED_INITIALIZER; /// Get all the hunks in the blame. A convenience wrapper around `enumerateHunksUsingBlock:` -@property (nonatomic, strong, readonly) NSArray *hunks; +@property (nonatomic, strong, readonly) NSArray *hunks; /// The number of hunks in the blame. @property (nonatomic, readonly) NSUInteger hunkCount; @@ -29,12 +37,13 @@ /// index - The index to retrieve the hunk from. /// /// Returns a `GTBlameHunk` or nil if an error occurred. -- (GTBlameHunk *)hunkAtIndex:(NSUInteger)index; +- (GTBlameHunk * _Nullable)hunkAtIndex:(NSUInteger)index; /// Enumerate the hunks in the blame. /// /// block - A block invoked for every hunk in the blame. /// Setting stop to `YES` instantly stops the enumeration. +/// May not be NULL. /// - (void)enumerateHunksUsingBlock:(void (^)(GTBlameHunk *hunk, NSUInteger index, BOOL *stop))block; @@ -43,10 +52,11 @@ /// lineNumber - The (1 based) line number to find a hunk for. /// /// Returns a `GTBlameHunk` or nil if an error occurred. -- (GTBlameHunk *)hunkAtLineNumber:(NSUInteger)lineNumber; +- (GTBlameHunk * _Nullable)hunkAtLineNumber:(NSUInteger)lineNumber; /// The underlying `git_blame` object. - (git_blame *)git_blame __attribute__((objc_returns_inner_pointer)); @end +NS_ASSUME_NONNULL_END diff --git a/ObjectiveGit/GTBlame.m b/ObjectiveGit/GTBlame.m index c2dcb5e9a..c1dee263f 100644 --- a/ObjectiveGit/GTBlame.m +++ b/ObjectiveGit/GTBlame.m @@ -21,6 +21,11 @@ @interface GTBlame () @implementation GTBlame +- (instancetype)init { + NSAssert(NO, @"Call to an unavailable initializer."); + return nil; +} + - (instancetype)initWithGitBlame:(git_blame *)blame { NSParameterAssert(blame != NULL); diff --git a/ObjectiveGit/GTBlameHunk.h b/ObjectiveGit/GTBlameHunk.h index de3f1abb0..72e3f1764 100644 --- a/ObjectiveGit/GTBlameHunk.h +++ b/ObjectiveGit/GTBlameHunk.h @@ -12,20 +12,29 @@ @class GTOID; @class GTSignature; +NS_ASSUME_NONNULL_BEGIN + /// A `GTBlameHunk` is an object that provides authorship info for a set of lines in a `GTBlame`. @interface GTBlameHunk : NSObject -- (instancetype)initWithGitBlameHunk:(git_blame_hunk)hunk; +- (instancetype)init NS_UNAVAILABLE; + +/// Designated initializer. +/// +/// hunk - A git_blame_hunk to wrap. May not be NULL. +/// +/// Returns a blame hunk, or nil if initialization failed. +- (instancetype _Nullable)initWithGitBlameHunk:(git_blame_hunk)hunk NS_DESIGNATED_INITIALIZER; /// A NSRange where `location` is the (1 based) starting line number, /// and `length` is the number of lines in the hunk. @property (nonatomic, readonly) NSRange lines; /// The OID of the commit where this hunk was last changed. -@property (nonatomic, readonly, copy) GTOID *finalCommitOID; +@property (nonatomic, readonly, copy) GTOID * _Nullable finalCommitOID; /// The signature of the commit where this hunk was last changed. -@property (nonatomic, readonly) GTSignature *finalSignature; +@property (nonatomic, readonly) GTSignature * _Nullable finalSignature; /// The path of the file in the original commit. @property (nonatomic, readonly, copy) NSString *originalPath; @@ -38,3 +47,5 @@ @property (nonatomic, readonly) git_blame_hunk git_blame_hunk; @end + +NS_ASSUME_NONNULL_END diff --git a/ObjectiveGit/GTBlameHunk.m b/ObjectiveGit/GTBlameHunk.m index 4fc016c99..9c136fc70 100644 --- a/ObjectiveGit/GTBlameHunk.m +++ b/ObjectiveGit/GTBlameHunk.m @@ -12,6 +12,11 @@ @implementation GTBlameHunk +- (instancetype)init { + NSAssert(NO, @"Call to an unavailable initializer."); + return nil; +} + - (instancetype)initWithGitBlameHunk:(git_blame_hunk)hunk { self = [super init]; if (self == nil) return nil; @@ -34,7 +39,9 @@ - (GTSignature *)finalSignature { } - (NSString *)originalPath { - return @(self.git_blame_hunk.orig_path); + NSString *path = @(self.git_blame_hunk.orig_path); + NSAssert(path, @"string was nil"); + return path; } - (BOOL)isBoundary { diff --git a/ObjectiveGit/GTBlob.h b/ObjectiveGit/GTBlob.h index 005332f08..6865ee8a6 100644 --- a/ObjectiveGit/GTBlob.h +++ b/ObjectiveGit/GTBlob.h @@ -30,44 +30,81 @@ #import "GTObject.h" +NS_ASSUME_NONNULL_BEGIN @interface GTBlob : GTObject -/// Convenience class methods -+ (instancetype)blobWithString:(NSString *)string inRepository:(GTRepository *)repository error:(NSError **)error; -+ (instancetype)blobWithData:(NSData *)data inRepository:(GTRepository *)repository error:(NSError **)error; -+ (instancetype)blobWithFile:(NSURL *)file inRepository:(GTRepository *)repository error:(NSError **)error; +/// Creates a new blob from the given string. +/// +/// This writes data to the repository's object database. +/// +/// string - The string to add. This must not be nil. +/// repository - The repository to put the object in. This must not be nil. +/// error - Will be set if an error occurs. This may be nil. +/// +/// Return a newly created blob object, or nil if an error occurs. ++ (instancetype _Nullable)blobWithString:(NSString *)string inRepository:(GTRepository *)repository error:(NSError **)error; + +/// Creates a new blob from the given data. +/// +/// This writes data to the repository's object database. +/// +/// data - The data to add. This must not be nil. +/// repository - The repository to put the object in. This must not be nil. +/// error - Will be set if an error occurs. This may be nil. +/// +/// Return a newly created blob object, or nil if an error occurs. ++ (instancetype _Nullable)blobWithData:(NSData *)data inRepository:(GTRepository *)repository error:(NSError **)error; +/// Creates a new blob given an NSURL to a file. +/// +/// This copies the data from the file to the repository's object database. +/// +/// file - The NSURL of the file to add. This must not be nil. +/// repository - The repository to put the object in. This must not be nil. +/// error - Will be set if an error occurs. This may be nil. +/// +/// Return a newly created blob object, or nil if an error occurs. ++ (instancetype _Nullable)blobWithFile:(NSURL *)file inRepository:(GTRepository *)repository error:(NSError **)error; + +/// Creates a new blob from the given string. +/// /// Convenience wrapper around `-initWithData:inRepository:error` that converts the string to UTF8 data -- (instancetype)initWithString:(NSString *)string inRepository:(GTRepository *)repository error:(NSError **)error; +/// +/// string - The string to add. This must not be nil. +/// repository - The repository to put the object in. This must not be nil. +/// error - Will be set if an error occurs. This may be nil. +/// +/// Return a newly created blob object, or nil if an error occurs. +- (instancetype _Nullable)initWithString:(NSString *)string inRepository:(GTRepository *)repository error:(NSError **)error; /// Creates a new blob from the passed data. /// /// This writes data to the repository's object database. /// -/// data - The data to write. -/// repository - The repository to put the object in. -/// error - Will be set if an error occurs. +/// data - The data to write. This must not be nil. +/// repository - The repository to put the object in. This must not be nil. +/// error - Will be set if an error occurs. This may be nil. /// /// Returns a newly created blob object, or nil if an error occurs. -- (instancetype)initWithData:(NSData *)data inRepository:(GTRepository *)repository error:(NSError **)error; +- (instancetype _Nullable)initWithData:(NSData *)data inRepository:(GTRepository *)repository error:(NSError **)error; /// Creates a new blob from the specified file. /// /// This copies the data from the file to the repository's object database. /// -/// data - The file to copy contents from. -/// repository - The repository to put the object in. -/// error - Will be set if an error occurs. +/// file - The file to copy contents from. This must not be nil. +/// repository - The repository to put the object in. This must not be nil. +/// error - Will be set if an error occurs. This may be nil. /// /// Returns a newly created blob object, or nil if an error occurs. -- (instancetype)initWithFile:(NSURL *)file inRepository:(GTRepository *)repository error:(NSError **)error; +- (instancetype _Nullable)initWithFile:(NSURL *)file inRepository:(GTRepository *)repository error:(NSError **)error; /// The underlying `git_object` as a `git_blob` object. - (git_blob *)git_blob __attribute__((objc_returns_inner_pointer)); - (git_off_t)size; -- (NSString *)content; +- (NSString * _Nullable)content; - (NSData *)data; /// Attempts to apply the filter list for `path` to the blob. @@ -76,6 +113,8 @@ /// error - If not NULL, set to any error that occurs. /// /// Returns the filtered data, or nil if an error occurs. -- (NSData *)applyFiltersForPath:(NSString *)path error:(NSError **)error; +- (NSData * _Nullable)applyFiltersForPath:(NSString *)path error:(NSError **)error; @end + +NS_ASSUME_NONNULL_END diff --git a/ObjectiveGit/GTBlob.m b/ObjectiveGit/GTBlob.m index 807ee0998..a1634dcf5 100644 --- a/ObjectiveGit/GTBlob.m +++ b/ObjectiveGit/GTBlob.m @@ -40,30 +40,30 @@ @implementation GTBlob - (NSString *)description { - return [NSString stringWithFormat:@"<%@: %p> size: %zi, content: %@, data = %@", NSStringFromClass([self class]), self, [self size], [self content], [self data]]; + return [NSString stringWithFormat:@"<%@: %p> size: %lli, content: %@, data = %@", NSStringFromClass([self class]), self, [self size], [self content], [self data]]; } #pragma mark API -+ (id)blobWithString:(NSString *)string inRepository:(GTRepository *)repository error:(NSError **)error { ++ (instancetype)blobWithString:(NSString *)string inRepository:(GTRepository *)repository error:(NSError **)error { return [[self alloc] initWithString:string inRepository:repository error:error]; } -+ (id)blobWithData:(NSData *)data inRepository:(GTRepository *)repository error:(NSError **)error { ++ (instancetype)blobWithData:(NSData *)data inRepository:(GTRepository *)repository error:(NSError **)error { return [[self alloc] initWithData:data inRepository:repository error:error]; } -+ (id)blobWithFile:(NSURL *)file inRepository:(GTRepository *)repository error:(NSError **)error { ++ (instancetype)blobWithFile:(NSURL *)file inRepository:(GTRepository *)repository error:(NSError **)error { return [[self alloc] initWithFile:file inRepository:repository error:error]; } -- (id)initWithOid:(const git_oid *)oid inRepository:(GTRepository *)repository error:(NSError **)error { +- (instancetype)initWithOid:(const git_oid *)oid inRepository:(GTRepository *)repository error:(NSError **)error { NSParameterAssert(oid != NULL); NSParameterAssert(repository != nil); git_object *obj; - int gitError = git_object_lookup(&obj, repository.git_repository, oid, (git_otype) GTObjectTypeBlob); + int gitError = git_object_lookup(&obj, repository.git_repository, oid, (git_object_t) GTObjectTypeBlob); if (gitError < GIT_OK) { if (error != NULL) { *error = [NSError git_errorFor:gitError description:@"Failed to lookup blob"]; @@ -74,12 +74,12 @@ - (id)initWithOid:(const git_oid *)oid inRepository:(GTRepository *)repository e return [self initWithObj:obj inRepository:repository]; } -- (id)initWithString:(NSString *)string inRepository:(GTRepository *)repository error:(NSError **)error { +- (instancetype)initWithString:(NSString *)string inRepository:(GTRepository *)repository error:(NSError **)error { NSData *data = [string dataUsingEncoding:NSUTF8StringEncoding]; return [self initWithData:data inRepository:repository error:error]; } -- (id)initWithData:(NSData *)data inRepository:(GTRepository *)repository error:(NSError **)error { +- (instancetype)initWithData:(NSData *)data inRepository:(GTRepository *)repository error:(NSError **)error { NSParameterAssert(data != nil); NSParameterAssert(repository != nil); @@ -95,7 +95,7 @@ - (id)initWithData:(NSData *)data inRepository:(GTRepository *)repository error: return [self initWithOid:&oid inRepository:repository error:error]; } -- (id)initWithFile:(NSURL *)file inRepository:(GTRepository *)repository error:(NSError **)error { +- (instancetype)initWithFile:(NSURL *)file inRepository:(GTRepository *)repository error:(NSError **)error { NSParameterAssert(file != nil); NSParameterAssert(repository != nil); diff --git a/ObjectiveGit/GTBranch.h b/ObjectiveGit/GTBranch.h index d2d7a56c8..3b3be239d 100644 --- a/ObjectiveGit/GTBranch.h +++ b/ObjectiveGit/GTBranch.h @@ -35,32 +35,51 @@ typedef NS_ENUM(NSInteger, GTBranchType) { GTBranchTypeRemote = GIT_BRANCH_REMOTE, }; +NS_ASSUME_NONNULL_BEGIN + /// A git branch object. /// -/// Branches are considered to be equivalent iff both their `name` and `SHA` are +/// Branches are considered to be equivalent if both their `name` and `SHA` are /// equal. @interface GTBranch : NSObject -@property (nonatomic, readonly) NSString *name; -@property (nonatomic, readonly) NSString *shortName; -@property (nonatomic, readonly) NSString *SHA; -@property (nonatomic, readonly) NSString *remoteName; +@property (nonatomic, readonly) NSString * _Nullable name; +@property (nonatomic, readonly) NSString * _Nullable shortName; +@property (nonatomic, copy, readonly) GTOID * _Nullable OID; +@property (nonatomic, readonly) NSString * _Nullable remoteName; @property (nonatomic, readonly) GTBranchType branchType; @property (nonatomic, readonly, strong) GTRepository *repository; @property (nonatomic, readonly, strong) GTReference *reference; +@property (nonatomic, readonly, getter=isHEAD) BOOL HEAD; + (NSString *)localNamePrefix; + (NSString *)remoteNamePrefix; -- (id)initWithReference:(GTReference *)ref repository:(GTRepository *)repo; -+ (id)branchWithReference:(GTReference *)ref repository:(GTRepository *)repo; +- (instancetype)init NS_UNAVAILABLE; + +/// Designated initializer. +/// +/// ref - The branch reference to wrap. Must not be nil. +/// +/// Returns the initialized receiver. +- (instancetype _Nullable)initWithReference:(GTReference *)ref NS_DESIGNATED_INITIALIZER; + +/// Convenience class initializer. +/// +/// ref - The branch reference to wrap. Must not be nil. +/// +/// Returns an initialized instance. ++ (instancetype _Nullable)branchWithReference:(GTReference *)ref; /// Get the target commit for this branch /// /// error(out) - will be filled if an error occurs /// /// returns a GTCommit object or nil if an error occurred -- (GTCommit *)targetCommitAndReturnError:(NSError **)error; +- (GTCommit * _Nullable)targetCommitWithError:(NSError **)error; + +/// Renames the branch. Setting `force` to YES to delete another branch with the same name. +- (BOOL)rename:(NSString *)name force:(BOOL)force error:(NSError **)error; /// Count all commits in this branch /// @@ -69,7 +88,13 @@ typedef NS_ENUM(NSInteger, GTBranchType) { /// returns number of commits in the branch or NSNotFound if an error occurred - (NSUInteger)numberOfCommitsWithError:(NSError **)error; -- (NSArray *)uniqueCommitsRelativeToBranch:(GTBranch *)otherBranch error:(NSError **)error; +/// Get unique commits +/// +/// otherBranch - +/// error - If not NULL, set to any error that occurs. +/// +/// Returns a (possibly empty) array of GTCommits, or nil if an error occurs. +- (NSArray * _Nullable)uniqueCommitsRelativeToBranch:(GTBranch *)otherBranch error:(NSError **)error; /// Deletes the local branch and nils out the reference. - (BOOL)deleteWithError:(NSError **)error; @@ -77,7 +102,16 @@ typedef NS_ENUM(NSInteger, GTBranchType) { /// If the receiver is a local branch, looks up and returns its tracking branch. /// If the receiver is a remote branch, returns self. If no tracking branch was /// found, returns nil and sets `success` to YES. -- (GTBranch *)trackingBranchWithError:(NSError **)error success:(BOOL *)success; +- (GTBranch * _Nullable)trackingBranchWithError:(NSError **)error success:(BOOL * _Nullable)success; + +/// Update the tracking branch. +/// +/// trackingBranch - The tracking branch for the receiver. If nil, it unsets the +/// tracking branch. +/// error - The error if one occurred. +/// +/// Returns whether it was successful. +- (BOOL)updateTrackingBranch:(GTBranch * _Nullable)trackingBranch error:(NSError **)error; /// Reloads the branch's reference and creates a new branch based off that newly /// loaded reference. @@ -87,7 +121,7 @@ typedef NS_ENUM(NSInteger, GTBranchType) { /// error - The error if one occurred. /// /// Returns the reloaded branch, or nil if an error occurred. -- (GTBranch *)reloadedBranchWithError:(NSError **)error; +- (GTBranch * _Nullable)reloadedBranchWithError:(NSError **)error; /// Calculate the ahead/behind count from this branch to the given branch. /// @@ -101,3 +135,5 @@ typedef NS_ENUM(NSInteger, GTBranchType) { - (BOOL)calculateAhead:(size_t *)ahead behind:(size_t *)behind relativeTo:(GTBranch *)branch error:(NSError **)error; @end + +NS_ASSUME_NONNULL_END diff --git a/ObjectiveGit/GTBranch.m b/ObjectiveGit/GTBranch.m index 8516a424f..ec54cbd5d 100644 --- a/ObjectiveGit/GTBranch.m +++ b/ObjectiveGit/GTBranch.m @@ -24,12 +24,15 @@ // #import "GTBranch.h" -#import "GTReference.h" -#import "GTEnumerator.h" -#import "GTRepository.h" + #import "GTCommit.h" +#import "GTEnumerator.h" +#import "GTOID.h" +#import "GTReference.h" #import "GTRemote.h" +#import "GTRepository.h" #import "NSError+Git.h" +#import "NSData+Git.h" #import "git2/branch.h" #import "git2/errors.h" @@ -38,18 +41,18 @@ @implementation GTBranch - (NSString *)description { - return [NSString stringWithFormat:@"<%@: %p> name: %@, shortName: %@, sha: %@, remoteName: %@, repository: %@", NSStringFromClass([self class]), self, self.name, self.shortName, self.SHA, self.remoteName, self.repository]; + return [NSString stringWithFormat:@"<%@: %p> name: %@, shortName: %@, sha: %@, remoteName: %@, repository: %@", NSStringFromClass([self class]), self, self.name, self.shortName, self.OID, self.remoteName, self.repository]; } - (BOOL)isEqual:(GTBranch *)otherBranch { if (otherBranch == self) return YES; if (![otherBranch isKindOfClass:self.class]) return NO; - return [self.name isEqual:otherBranch.name] && [self.SHA isEqual:otherBranch.SHA]; + return [self.name isEqual:otherBranch.name] && [self.OID isEqual:otherBranch.OID]; } - (NSUInteger)hash { - return self.name.hash ^ self.SHA.hash; + return self.name.hash ^ self.OID.hash; } @@ -63,25 +66,32 @@ + (NSString *)remoteNamePrefix { return @"refs/remotes/"; } -+ (id)branchWithReference:(GTReference *)ref repository:(GTRepository *)repo { - return [[self alloc] initWithReference:ref repository:repo]; ++ (instancetype)branchWithReference:(GTReference *)ref { + return [[self alloc] initWithReference:ref]; } -- (id)initWithReference:(GTReference *)ref repository:(GTRepository *)repo { +- (instancetype)init { + NSAssert(NO, @"Call to an unavailable initializer."); + return nil; +} + +- (instancetype)initWithReference:(GTReference *)ref { NSParameterAssert(ref != nil); - NSParameterAssert(repo != nil); self = [super init]; if (self == nil) return nil; - _repository = repo; _reference = ref; return self; } - (NSString *)name { - return self.reference.name; + const char *charName; + int gitError = git_branch_name(&charName, self.reference.git_reference); + if (gitError != GIT_OK || charName == NULL) return nil; + + return @(charName); } - (NSString *)shortName { @@ -100,41 +110,44 @@ - (NSString *)shortName { return @(name); } -- (NSString *)SHA { - return self.reference.targetSHA; +- (GTOID *)OID { + return self.reference.targetOID; } - (NSString *)remoteName { - if (self.branchType == GTBranchTypeLocal) return nil; - - const char *name; - int gitError = git_branch_name(&name, self.reference.git_reference); + git_buf remote_name = GIT_BUF_INIT_CONST(0, NULL); + int gitError = git_branch_remote_name(&remote_name, self.repository.git_repository, self.reference.name.UTF8String); if (gitError != GIT_OK) return nil; - // Find out where the remote name ends. - const char *end = strchr(name, '/'); - if (end == NULL || end == name) return nil; - - return [[NSString alloc] initWithBytes:name length:end - name encoding:NSUTF8StringEncoding]; + NSData *data = [NSData git_dataWithBuffer:&remote_name]; + return [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]; } -- (GTCommit *)targetCommitAndReturnError:(NSError **)error { - if (self.SHA == nil) { +- (GTCommit *)targetCommitWithError:(NSError **)error { + GTOID *oid = self.OID; + if (oid == nil) { if (error != NULL) *error = GTReference.invalidReferenceError; return nil; } - return [self.repository lookUpObjectBySHA:self.SHA objectType:GTObjectTypeCommit error:error]; + return [self.repository lookUpObjectByOID:oid objectType:GTObjectTypeCommit error:error]; } - (NSUInteger)numberOfCommitsWithError:(NSError **)error { GTEnumerator *enumerator = [[GTEnumerator alloc] initWithRepository:self.repository error:error]; if (enumerator == nil) return NSNotFound; - if (![enumerator pushSHA:self.SHA error:error]) return NSNotFound; + GTOID *oid = self.OID; + if (oid == nil) return NSNotFound; + + if (![enumerator pushSHA:oid.SHA error:error]) return NSNotFound; return [enumerator countRemainingObjects:error]; } +- (GTRepository *)repository { + return self.reference.repository; +} + - (GTBranchType)branchType { if (self.reference.remote) { return GTBranchTypeRemote; @@ -143,23 +156,14 @@ - (GTBranchType)branchType { } } -- (NSArray *)uniqueCommitsRelativeToBranch:(GTBranch *)otherBranch error:(NSError **)error { - NSParameterAssert(otherBranch != nil); - - GTCommit *mergeBase = [self.repository mergeBaseBetweenFirstOID:self.reference.OID secondOID:otherBranch.reference.OID error:error]; - if (mergeBase == nil) return nil; - - GTEnumerator *enumerator = [[GTEnumerator alloc] initWithRepository:self.repository error:error]; - if (enumerator == nil) return nil; - - [enumerator resetWithOptions:GTEnumeratorOptionsTimeSort]; - - BOOL success = [enumerator pushSHA:self.SHA error:error]; - if (!success) return nil; - - success = [enumerator hideSHA:mergeBase.SHA error:error]; - if (!success) return nil; +- (BOOL)isHEAD { + return (git_branch_is_head(self.reference.git_reference) ? YES : NO); +} +- (NSArray *)uniqueCommitsRelativeToBranch:(GTBranch *)otherBranch error:(NSError **)error { + GTOID *oid = self.OID; + GTOID *otherOID = otherBranch.OID; + GTEnumerator *enumerator = [self.repository enumeratorForUniqueCommitsFromOID:oid relativeToOID:otherOID error:error]; return [enumerator allObjectsWithError:error]; } @@ -173,9 +177,29 @@ - (BOOL)deleteWithError:(NSError **)error { return YES; } +- (BOOL)rename:(NSString *)name force:(BOOL)force error:(NSError **)error { + git_reference *git_ref; + int gitError = git_branch_move(&git_ref, self.reference.git_reference, name.UTF8String, (force ? 1 : 0)); + if (gitError != GIT_OK) { + if (error) *error = [NSError git_errorFor:gitError description:@"Rename branch failed"]; + return NO; + } + + GTReference *renamedRef = [[GTReference alloc] initWithGitReference:git_ref repository:self.repository]; + NSAssert(renamedRef, @"Unable to allocate renamed ref"); + _reference = renamedRef; + + return YES; +} + - (GTBranch *)trackingBranchWithError:(NSError **)error success:(BOOL *)success { + BOOL underSuccess = NO; + if (success == NULL) { + success = &underSuccess; + } + if (self.branchType == GTBranchTypeRemote) { - if (success != NULL) *success = YES; + *success = YES; return self; } @@ -184,48 +208,60 @@ - (GTBranch *)trackingBranchWithError:(NSError **)error success:(BOOL *)success // GIT_ENOTFOUND means no tracking branch found. if (gitError == GIT_ENOTFOUND) { - if (success != NULL) *success = YES; + *success = YES; return nil; } if (gitError != GIT_OK) { - if (success != NULL) *success = NO; + *success = NO; if (error != NULL) *error = [NSError git_errorFor:gitError description:@"Failed to create reference to tracking branch from %@", self]; return nil; } if (trackingRef == NULL) { - if (success != NULL) *success = NO; + *success = NO; if (error != NULL) *error = [NSError git_errorFor:gitError description:@"Got a NULL remote ref for %@", self]; return nil; } - if (success != NULL) *success = YES; + GTReference *upsteamRef = [[GTReference alloc] initWithGitReference:trackingRef repository:self.repository]; + if (upsteamRef == nil) { + *success = NO; + if (error != NULL) *error = [NSError git_errorFor:GIT_ERROR description:@"Failed to allocate upstream ref"]; + return nil; + } + + *success = YES; + + return [[self class] branchWithReference:upsteamRef]; +} + +- (BOOL)updateTrackingBranch:(GTBranch *)trackingBranch error:(NSError **)error { + int result = GIT_ENOTFOUND; + if (trackingBranch.branchType == GTBranchTypeRemote) { + result = git_branch_set_upstream(self.reference.git_reference, [trackingBranch.name stringByReplacingOccurrencesOfString:[GTBranch remoteNamePrefix] withString:@""].UTF8String); + } else { + result = git_branch_set_upstream(self.reference.git_reference, trackingBranch.shortName.UTF8String); + } + if (result != GIT_OK) { + if (error != NULL) *error = [NSError git_errorFor:result description:@"Failed to update tracking branch for %@", self]; + return NO; + } - return [[self class] branchWithReference:[[GTReference alloc] initWithGitReference:trackingRef repository:self.repository] repository:self.repository]; + return YES; } - (GTBranch *)reloadedBranchWithError:(NSError **)error { GTReference *reloadedRef = [self.reference reloadedReferenceWithError:error]; if (reloadedRef == nil) return nil; - return [[self.class alloc] initWithReference:reloadedRef repository:self.repository]; + return [[self.class alloc] initWithReference:reloadedRef]; } - (BOOL)calculateAhead:(size_t *)ahead behind:(size_t *)behind relativeTo:(GTBranch *)branch error:(NSError **)error { - if (branch == nil) { - *ahead = 0; - *behind = 0; - return YES; - } - - int errorCode = git_graph_ahead_behind(ahead, behind, self.repository.git_repository, self.reference.git_oid, branch.reference.git_oid); - if (errorCode != GIT_OK && error != NULL) { - *error = [NSError git_errorFor:errorCode description:@"Failed to calculate ahead/behind count of %@ relative to %@", self, branch]; - return NO; - } - - return YES; + GTOID *oid = self.OID; + GTOID *branchOID = branch.OID; + return [self.repository calculateAhead:ahead behind:behind ofOID:oid relativeToOID:branchOID error:error]; } @end diff --git a/ObjectiveGit/GTCheckoutOptions.h b/ObjectiveGit/GTCheckoutOptions.h new file mode 100644 index 000000000..f8e6277d9 --- /dev/null +++ b/ObjectiveGit/GTCheckoutOptions.h @@ -0,0 +1,103 @@ +// +// GTCheckoutOptions.h +// ObjectiveGitFramework +// +// Created by Etienne on 10/04/2015. +// Copyright (c) 2015 GitHub, Inc. All rights reserved. +// + +#import +#import "git2/checkout.h" + +@class GTDiffFile; + +NS_ASSUME_NONNULL_BEGIN + +/// Checkout strategies used by the various -checkout... methods +/// See git_checkout_strategy_t +typedef NS_OPTIONS(NSInteger, GTCheckoutStrategyType) { + GTCheckoutStrategyNone = GIT_CHECKOUT_NONE, + GTCheckoutStrategySafe = GIT_CHECKOUT_SAFE, + GTCheckoutStrategyForce = GIT_CHECKOUT_FORCE, + GTCheckoutStrategyRecreateMissing = GIT_CHECKOUT_RECREATE_MISSING, + GTCheckoutStrategyAllowConflicts = GIT_CHECKOUT_ALLOW_CONFLICTS, + GTCheckoutStrategyRemoveUntracked = GIT_CHECKOUT_REMOVE_UNTRACKED, + GTCheckoutStrategyRemoveIgnored = GIT_CHECKOUT_REMOVE_IGNORED, + GTCheckoutStrategyUpdateOnly = GIT_CHECKOUT_UPDATE_ONLY, + GTCheckoutStrategyDontUpdateIndex = GIT_CHECKOUT_DONT_UPDATE_INDEX, + GTCheckoutStrategyNoRefresh = GIT_CHECKOUT_NO_REFRESH, + GTCheckoutStrategySkipUnmerged = GIT_CHECKOUT_SKIP_UNMERGED, + GTCheckoutStrategyUseOurs = GIT_CHECKOUT_USE_OURS, + GTCheckoutStrategyUseTheirs = GIT_CHECKOUT_USE_THEIRS, + GTCheckoutStrategyDisablePathspecMatch = GIT_CHECKOUT_DISABLE_PATHSPEC_MATCH, + GTCheckoutStrategySkipLockedDirectories = GIT_CHECKOUT_SKIP_LOCKED_DIRECTORIES, + GTCheckoutStrategyDoNotOverwriteIgnored = GIT_CHECKOUT_DONT_OVERWRITE_IGNORED, + GTCheckoutStrategyConflictStyleMerge = GIT_CHECKOUT_CONFLICT_STYLE_MERGE, + GTCheckoutStrategyCoflictStyleDiff3 = GIT_CHECKOUT_CONFLICT_STYLE_DIFF3, + GTCheckoutStrategyDoNotRemoveExisting = GIT_CHECKOUT_DONT_REMOVE_EXISTING, + GTCheckoutStrategyDoNotWriteIndex = GIT_CHECKOUT_DONT_WRITE_INDEX, +}; + +/// Checkout notification flags used by the various -checkout... methods +/// See git_checkout_notify_t +typedef NS_OPTIONS(NSInteger, GTCheckoutNotifyFlags) { + GTCheckoutNotifyNone = GIT_CHECKOUT_NOTIFY_NONE, + GTCheckoutNotifyConflict = GIT_CHECKOUT_NOTIFY_CONFLICT, + GTCheckoutNotifyDirty = GIT_CHECKOUT_NOTIFY_DIRTY, + GTCheckoutNotifyUpdated = GIT_CHECKOUT_NOTIFY_UPDATED, + GTCheckoutNotifyUntracked = GIT_CHECKOUT_NOTIFY_UNTRACKED, + GTCheckoutNotifyIgnored = GIT_CHECKOUT_NOTIFY_IGNORED, + + GTCheckoutNotifyAll = GIT_CHECKOUT_NOTIFY_ALL, +}; + +@interface GTCheckoutOptions : NSObject + +/// Create a checkout options object. +/// +/// Since there are many places where we can checkout data, this object allow us +/// to centralize all the various behaviors that checkout allow. +/// +/// @param strategy The checkout strategy to use. +/// @param notifyFlags The checkout events that will be notified via `notifyBlock`. +/// @param progressBlock A block that will be called for each checkout step. +/// @param notifyBlock A block that will be called for each event, @see `notifyFlags`. +/// +/// @return A newly-initialized GTCheckoutOptions object. ++ (instancetype)checkoutOptionsWithStrategy:(GTCheckoutStrategyType)strategy notifyFlags:(GTCheckoutNotifyFlags)notifyFlags progressBlock:(void (^ _Nullable)(NSString *path, NSUInteger completedSteps, NSUInteger totalSteps))progressBlock notifyBlock:(int (^ _Nullable)(GTCheckoutNotifyFlags why, NSString *path, GTDiffFile *baseline, GTDiffFile *target, GTDiffFile *workdir))notifyBlock; + +/// Create a checkout options object. +/// @see +checkoutOptionsWithStrategy:notifyFlags:progressBlock:notifyBlock: ++ (instancetype)checkoutOptionsWithStrategy:(GTCheckoutStrategyType)strategy notifyFlags:(GTCheckoutNotifyFlags)notifyFlags notifyBlock:(int (^)(GTCheckoutNotifyFlags why, NSString *path, GTDiffFile *baseline, GTDiffFile *target, GTDiffFile *workdir))notifyBlock; + +/// Create a checkout options object. +/// @see +checkoutOptionsWithStrategy:notifyFlags:progressBlock:notifyBlock: ++ (instancetype)checkoutOptionsWithStrategy:(GTCheckoutStrategyType)strategy progressBlock:(void (^)(NSString *path, NSUInteger completedSteps, NSUInteger totalSteps))progressBlock; + +/// Create a checkout options object. +/// @see +checkoutOptionsWithStrategy:notifyFlags:progressBlock:notifyBlock: ++ (instancetype)checkoutOptionsWithStrategy:(GTCheckoutStrategyType)strategy; + +/// Get the underlying git_checkout_options struct. +/// +/// @return <#return value description#> +- (git_checkout_options *)git_checkoutOptions NS_RETURNS_INNER_POINTER; + +/// The checkout strategy to use. +@property (assign) GTCheckoutStrategyType strategy; + +/// The checkout progress block that was passed in. +@property (copy, nullable) void (^progressBlock)(NSString *path, NSUInteger completedSteps, NSUInteger totalSteps); + +/// The notification flags currently enabled. +@property (assign) GTCheckoutNotifyFlags notifyFlags; + +/// The checkout notification block that was passed in. +@property (copy, nullable) int (^notifyBlock)(GTCheckoutNotifyFlags why, NSString *path, GTDiffFile *baseline, GTDiffFile *target, GTDiffFile *workdir); + +/// An array of strings used to restrict what will be checked out. +@property (copy) NSArray *pathSpecs; + +@end + +NS_ASSUME_NONNULL_END diff --git a/ObjectiveGit/GTCheckoutOptions.m b/ObjectiveGit/GTCheckoutOptions.m new file mode 100644 index 000000000..354e330c6 --- /dev/null +++ b/ObjectiveGit/GTCheckoutOptions.m @@ -0,0 +1,100 @@ +// +// GTCheckoutOptions.m +// ObjectiveGitFramework +// +// Created by Etienne on 10/04/2015. +// Copyright (c) 2015 GitHub, Inc. All rights reserved. +// + +#import "GTCheckoutOptions.h" +#import "GTDiffFile.h" +#import "NSError+Git.h" +#import "NSArray+StringArray.h" +#import "git2.h" + +// The type of block set in progressBlock for progress reporting +typedef void (^GTCheckoutProgressBlock)(NSString *path, NSUInteger completedSteps, NSUInteger totalSteps); + +// The type of block set in notifyBlock for notification reporting +typedef int (^GTCheckoutNotifyBlock)(GTCheckoutNotifyFlags why, NSString *path, GTDiffFile * _Nullable baseline, GTDiffFile * _Nullable target, GTDiffFile * _Nullable workdir); + + +@interface GTCheckoutOptions () { + git_checkout_options _git_checkoutOptions; +} +@end + +@implementation GTCheckoutOptions + ++ (instancetype)checkoutOptionsWithStrategy:(GTCheckoutStrategyType)strategy notifyFlags:(GTCheckoutNotifyFlags)notifyFlags progressBlock:(GTCheckoutProgressBlock _Nullable)progressBlock notifyBlock:( GTCheckoutNotifyBlock _Nullable)notifyBlock { + GTCheckoutOptions *options = [self checkoutOptionsWithStrategy:strategy]; + options.notifyFlags = notifyFlags; + options.notifyBlock = notifyBlock; + options.progressBlock = progressBlock; + return options; +} + ++ (instancetype)checkoutOptionsWithStrategy:(GTCheckoutStrategyType)strategy progressBlock:(GTCheckoutProgressBlock)progressBlock { + NSParameterAssert(progressBlock != nil); + GTCheckoutOptions *options = [self checkoutOptionsWithStrategy:strategy]; + options.progressBlock = progressBlock; + return options; +} + ++ (instancetype)checkoutOptionsWithStrategy:(GTCheckoutStrategyType)strategy notifyFlags:(GTCheckoutNotifyFlags)notifyFlags notifyBlock:(GTCheckoutNotifyBlock)notifyBlock { + NSParameterAssert(notifyBlock != nil); + return [self checkoutOptionsWithStrategy:strategy notifyFlags:notifyFlags progressBlock:nil notifyBlock:notifyBlock]; +} + ++ (instancetype)checkoutOptionsWithStrategy:(GTCheckoutStrategyType)strategy { + GTCheckoutOptions *options = [[self alloc] init]; + options.strategy = strategy; + return options; +} + +- (instancetype)init { + self = [super init]; + if (self == nil) return nil; + + _git_checkoutOptions.version = GIT_CHECKOUT_OPTIONS_VERSION; + + return self; +} + +static void GTCheckoutProgressCallback(const char *path, size_t completedSteps, size_t totalSteps, void *payload) { + if (payload == NULL) return; + void (^block)(NSString *, NSUInteger, NSUInteger) = (__bridge id)payload; + NSString *nsPath = (path != NULL ? @(path) : nil); + block(nsPath, completedSteps, totalSteps); +} + +static int GTCheckoutNotifyCallback(git_checkout_notify_t why, const char *path, const git_diff_file *baseline, const git_diff_file *target, const git_diff_file *workdir, void *payload) { + if (payload == NULL) return 0; + GTCheckoutNotifyBlock block = (__bridge id)payload; + NSString *nsPath = (path != NULL ? @(path) : nil); + GTDiffFile *gtBaseline = (baseline != NULL ? [[GTDiffFile alloc] initWithGitDiffFile:*baseline] : nil); + GTDiffFile *gtTarget = (target != NULL ? [[GTDiffFile alloc] initWithGitDiffFile:*target] : nil); + GTDiffFile *gtWorkdir = (workdir != NULL ? [[GTDiffFile alloc] initWithGitDiffFile:*workdir] : nil); + return block((GTCheckoutNotifyFlags)why, nsPath, gtBaseline, gtTarget, gtWorkdir); +} + +- (git_checkout_options *)git_checkoutOptions { + _git_checkoutOptions.checkout_strategy = self.strategy; + + if (self.progressBlock != nil) { + _git_checkoutOptions.progress_cb = GTCheckoutProgressCallback; + _git_checkoutOptions.progress_payload = (__bridge void *)self.progressBlock; + } + + if (self.notifyBlock != nil) { + _git_checkoutOptions.notify_cb = GTCheckoutNotifyCallback; + _git_checkoutOptions.notify_flags = self.notifyFlags; + _git_checkoutOptions.notify_payload = (__bridge void *)self.notifyBlock; + } + + _git_checkoutOptions.paths = self.pathSpecs.git_strarray; + + return &_git_checkoutOptions; +} + +@end diff --git a/ObjectiveGit/GTCommit.h b/ObjectiveGit/GTCommit.h index 79b4fdc64..c9a666b76 100644 --- a/ObjectiveGit/GTCommit.h +++ b/ObjectiveGit/GTCommit.h @@ -33,18 +33,23 @@ @class GTSignature; @class GTTree; @class GTOID; +@class GTIndex; + +NS_ASSUME_NONNULL_BEGIN @interface GTCommit : GTObject {} -@property (nonatomic, readonly, strong) GTSignature *author; -@property (nonatomic, readonly, strong) GTSignature *committer; -@property (nonatomic, readonly, copy) NSArray *parents; -@property (nonatomic, readonly) NSString *message; +@property (nonatomic, readonly, strong) GTOID *OID; +@property (nonatomic, readonly, strong) GTSignature * _Nullable author; +@property (nonatomic, readonly, strong) GTSignature * _Nullable committer; +@property (nonatomic, readonly, copy) NSArray *parents; +@property (nonatomic, readonly, copy) NSArray *parentOIDs; +@property (nonatomic, readonly) NSString * _Nullable message; @property (nonatomic, readonly) NSString *messageDetails; @property (nonatomic, readonly) NSString *messageSummary; @property (nonatomic, readonly) NSDate *commitDate; @property (nonatomic, readonly) NSTimeZone *commitTimeZone; -@property (nonatomic, readonly) GTTree *tree; +@property (nonatomic, readonly) GTTree * _Nullable tree; /// Is this a merge commit? @property (nonatomic, readonly, assign, getter = isMerge) BOOL merge; @@ -52,4 +57,17 @@ /// The underlying `git_object` as a `git_commit` object. - (git_commit *)git_commit __attribute__((objc_returns_inner_pointer)); +/// Merges the given commit into the receiver in memory and produces the result as +/// an index. +/// +/// otherCommit - The commit with which the receiver should be merged with. Cannot be +/// nil. +/// error - The error if one occurred. +/// +/// Returns an index which represents the result of the merge, or nil if an error +/// occurred. +- (GTIndex * _Nullable)merge:(GTCommit *)otherCommit error:(NSError **)error; + @end + +NS_ASSUME_NONNULL_END diff --git a/ObjectiveGit/GTCommit.m b/ObjectiveGit/GTCommit.m index 635134c6f..495877a22 100644 --- a/ObjectiveGit/GTCommit.m +++ b/ObjectiveGit/GTCommit.m @@ -35,9 +35,11 @@ #import "NSString+Git.h" #import "NSDate+GTTimeAdditions.h" #import "GTOID.h" +#import "GTIndex.h" #import "git2/commit.h" #import "git2/errors.h" +#import "git2/merge.h" @implementation GTCommit @@ -51,6 +53,10 @@ - (git_commit *)git_commit { #pragma mark API +- (GTOID *)OID { + return [GTOID oidWithGitOid:git_commit_id(self.git_commit)]; +} + - (NSString *)message { const char *s = git_commit_message(self.git_commit); if(s == NULL) return nil; @@ -115,6 +121,19 @@ - (BOOL)isMerge { return git_commit_parentcount(self.git_commit) > 1; } +- (NSArray *)parentOIDs { + unsigned numberOfParents = git_commit_parentcount(self.git_commit); + NSMutableArray *parents = [NSMutableArray arrayWithCapacity:numberOfParents]; + + for (unsigned i = 0; i < numberOfParents; i++) { + const git_oid *parent = git_commit_parent_id(self.git_commit, i); + + [parents addObject:[GTOID oidWithGitOid:parent]]; + } + + return parents; +} + - (NSArray *)parents { unsigned numberOfParents = git_commit_parentcount(self.git_commit); NSMutableArray *parents = [NSMutableArray arrayWithCapacity:numberOfParents]; @@ -130,4 +149,20 @@ - (NSArray *)parents { return parents; } +#pragma mark Merging + +- (GTIndex *)merge:(GTCommit *)otherCommit error:(NSError **)error { + NSParameterAssert(otherCommit != nil); + + git_index *index; + + int result = git_merge_commits(&index, self.repository.git_repository, self.git_commit, otherCommit.git_commit, NULL); + if (result != GIT_OK || index == NULL) { + if (error != NULL) *error = [NSError git_errorFor:result description:@"Failed to merge commit %@ with commit %@", self.SHA, otherCommit.SHA]; + return nil; + } + + return [[GTIndex alloc] initWithGitIndex:index repository:self.repository]; +} + @end diff --git a/ObjectiveGit/GTConfiguration+Private.h b/ObjectiveGit/GTConfiguration+Private.h index cb24b03ba..03b6f4f12 100644 --- a/ObjectiveGit/GTConfiguration+Private.h +++ b/ObjectiveGit/GTConfiguration+Private.h @@ -12,12 +12,12 @@ @interface GTConfiguration () -/// Initializes the receiver. +/// Designated initializer. /// /// config - The libgit2 config. Cannot be NULL. /// repository - The repository in which the config resides. May be nil. /// /// Returns the initialized object. -- (id)initWithGitConfig:(git_config *)config repository:(GTRepository *)repository; +- (instancetype _Nullable)initWithGitConfig:(git_config * _Nonnull)config repository:(GTRepository * _Nullable)repository NS_DESIGNATED_INITIALIZER; @end diff --git a/ObjectiveGit/GTConfiguration.h b/ObjectiveGit/GTConfiguration.h index ef7b15aa8..6c4df90a4 100644 --- a/ObjectiveGit/GTConfiguration.h +++ b/ObjectiveGit/GTConfiguration.h @@ -9,27 +9,32 @@ #import #import "git2/types.h" +@class GTRemote; @class GTRepository; @class GTSignature; +NS_ASSUME_NONNULL_BEGIN + @interface GTConfiguration : NSObject -@property (nonatomic, readonly, strong) GTRepository *repository; -@property (nonatomic, readonly, copy) NSArray *configurationKeys; +@property (nonatomic, readonly, strong) GTRepository * _Nullable repository; +@property (nonatomic, readonly, copy) NSArray *configurationKeys; /// The GTRemotes in the config. If the configuration isn't associated with any /// repository, this will always be nil. -@property (nonatomic, readonly, copy) NSArray *remotes; +@property (nonatomic, readonly, copy) NSArray * _Nullable remotes; + +- (instancetype)init NS_UNAVAILABLE; /// Creates and returns a configuration which includes the global, XDG, and /// system configurations. -+ (instancetype)defaultConfiguration; ++ (instancetype _Nullable)defaultConfiguration; /// The underlying `git_config` object. - (git_config *)git_config __attribute__((objc_returns_inner_pointer)); - (void)setString:(NSString *)s forKey:(NSString *)key; -- (NSString *)stringForKey:(NSString *)key; +- (NSString * _Nullable)stringForKey:(NSString *)key; - (void)setBool:(BOOL)b forKey:(NSString *)key; - (BOOL)boolForKey:(NSString *)key; @@ -42,12 +47,6 @@ - (BOOL)deleteValueForKey:(NSString *)key error:(NSError **)error; -/// Reloads the configuration from the files on disk if they have changed since -/// it was originally loaded. -/// -/// error - The error if one occurred. -/// -/// Returns whether the refresh was successful. -- (BOOL)refresh:(NSError **)error; - @end + +NS_ASSUME_NONNULL_END diff --git a/ObjectiveGit/GTConfiguration.m b/ObjectiveGit/GTConfiguration.m index 9dbe0864e..acd46cd74 100644 --- a/ObjectiveGit/GTConfiguration.m +++ b/ObjectiveGit/GTConfiguration.m @@ -10,11 +10,13 @@ #import "GTConfiguration+Private.h" #import "GTRepository.h" #import "GTRemote.h" -#import "NSError+Git.h" #import "GTSignature.h" +#import "NSData+Git.h" +#import "NSError+Git.h" #import "git2/config.h" #import "git2/errors.h" +#import "git2/buffer.h" @interface GTConfiguration () @property (nonatomic, readonly, assign) git_config *git_config; @@ -31,7 +33,12 @@ - (void)dealloc { } } -- (id)initWithGitConfig:(git_config *)config repository:(GTRepository *)repository { +- (instancetype)init { + NSAssert(NO, @"Call to an unavailable initializer."); + return nil; +} + +- (instancetype)initWithGitConfig:(git_config *)config repository:(GTRepository *)repository { NSParameterAssert(config != NULL); self = [super init]; @@ -58,11 +65,10 @@ - (void)setString:(NSString *)s forKey:(NSString *)key { } - (NSString *)stringForKey:(NSString *)key { - const char *string = NULL; - git_config_get_string(&string, self.git_config, key.UTF8String); - if (string == NULL) return nil; + git_buf buffer = {}; + if (git_config_get_string_buf(&buffer, self.git_config, key.UTF8String) != 0) return nil; - return [NSString stringWithUTF8String:string]; + return [[NSString alloc] initWithData:[NSData git_dataWithBuffer:&buffer] encoding:NSUTF8StringEncoding]; } - (void)setBool:(BOOL)b forKey:(NSString *)key { @@ -106,7 +112,10 @@ - (BOOL)deleteValueForKey:(NSString *)key error:(NSError **)error { static int configCallback(const git_config_entry *entry, void *payload) { NSMutableArray *configurationKeysArray = (__bridge NSMutableArray *)payload; - [configurationKeysArray addObject:@(entry->name)]; + NSString *name = @(entry->name); + NSCAssert(name, @"string was nil"); + + [configurationKeysArray addObject:name]; return 0; } @@ -128,10 +137,12 @@ - (NSArray *)remotes { NSMutableArray *remotes = [NSMutableArray arrayWithCapacity:names.count]; for (size_t i = 0; i < names.count; i++) { const char *name = names.strings[i]; - git_remote *remote = NULL; + git_remote *git_remote = NULL; - if (git_remote_load(&remote, repository.git_repository, name) == 0) { - [remotes addObject:[[GTRemote alloc] initWithGitRemote:remote inRepository:repository]]; + if (git_remote_lookup(&git_remote, repository.git_repository, name) == 0) { + GTRemote *remote = [[GTRemote alloc] initWithGitRemote:git_remote inRepository:repository]; + if (remote) + [remotes addObject:remote]; } } @@ -140,17 +151,4 @@ - (NSArray *)remotes { return remotes; } -#pragma mark Refresh - -- (BOOL)refresh:(NSError **)error { - int success = git_config_refresh(self.git_config); - if (success != GIT_OK) { - if (error != NULL) *error = [NSError git_errorFor:success description:@"Couldn't reload the configuration from disk."]; - - return NO; - } - - return YES; -} - @end diff --git a/ObjectiveGit/GTCredential.h b/ObjectiveGit/GTCredential.h index 9ff74ed0b..560a8ba18 100644 --- a/ObjectiveGit/GTCredential.h +++ b/ObjectiveGit/GTCredential.h @@ -17,6 +17,8 @@ typedef NS_ENUM(NSInteger, GTCredentialType) { GTCredentialTypeSSHCustom = GIT_CREDTYPE_SSH_CUSTOM, }; +NS_ASSUME_NONNULL_BEGIN + @class GTCredential; /// The GTCredentialProvider acts as a proxy for GTCredential requests. @@ -29,7 +31,8 @@ typedef NS_ENUM(NSInteger, GTCredentialType) { /// Creates a provider from a block. /// /// credentialBlock - a block that will be called when credentials are requested. -+ (instancetype)providerWithBlock:(GTCredential *(^)(GTCredentialType type, NSString *URL, NSString *userName))credentialBlock; +/// Must not be nil. ++ (instancetype)providerWithBlock:(GTCredential * _Nullable(^)(GTCredentialType type, NSString *URL, NSString *userName))credentialBlock; /// Default credential provider method. /// @@ -43,7 +46,7 @@ typedef NS_ENUM(NSInteger, GTCredentialType) { /// type - the credential types allowed by the operation. /// URL - the URL the operation is authenticating against. /// userName - the user name provided by the operation. Can be nil, and might be ignored. -- (GTCredential *)credentialForType:(GTCredentialType)type URL:(NSString *)URL userName:(NSString *)userName; +- (GTCredential * _Nullable)credentialForType:(GTCredentialType)type URL:(NSString * _Nullable)URL userName:(NSString * _Nullable)userName; @end /// The GTCredential class is used to provide authentication data. @@ -57,21 +60,35 @@ typedef NS_ENUM(NSInteger, GTCredentialType) { /// error - If not NULL, set to any errors that occur. /// /// Return a new GTCredential instance, or nil if an error occurred -+ (instancetype)credentialWithUserName:(NSString *)userName password:(NSString *)password error:(NSError **)error; ++ (instancetype _Nullable)credentialWithUserName:(NSString *)userName password:(NSString *)password error:(NSError **)error; /// Create a credential object from a SSH keyfile /// -/// userName - The username to authenticate as. +/// userName - The username to authenticate as. Must not be nil. /// publicKeyURL - The URL to the public key for that user. /// Can be omitted to reconstruct the public key from the private key. -/// privateKeyURL - The URL to the private key for that user. +/// privateKeyURL - The URL to the private key for that user. Must not be nil. /// passphrase - The passPhrase for the private key. Optional if the private key has no password. /// error - If not NULL, set to any errors that occur. /// /// Return a new GTCredential instance, or nil if an error occurred -+ (instancetype)credentialWithUserName:(NSString *)userName publicKeyURL:(NSURL *)publicKeyURL privateKeyURL:(NSURL *)privateKeyURL passphrase:(NSString *)passphrase error:(NSError **)error; ++ (instancetype _Nullable)credentialWithUserName:(NSString *)userName publicKeyURL:(NSURL * _Nullable)publicKeyURL privateKeyURL:(NSURL *)privateKeyURL passphrase:(NSString * _Nullable)passphrase error:(NSError **)error; + +/// Create a credential object from a SSH keyfile data string +/// +/// userName - The username to authenticate as. +/// publicKeyString - The string containing the public key for that user. +/// Can be omitted to reconstruct the public key from the private key. +/// privateKeyString - The URL to the private key for that user. +/// passphrase - The passPhrase for the private key. Optional if the private key has no password. +/// error - If not NULL, set to any errors that occur. +/// +/// Return a new GTCredential instance, or nil if an error occurred ++ (instancetype _Nullable)credentialWithUserName:(NSString *)userName publicKeyString:(NSString * _Nullable)publicKeyString privateKeyString:(NSString *)privateKeyString passphrase:(NSString * _Nullable)passphrase error:(NSError **)error; /// The underlying `git_cred` object. - (git_cred *)git_cred __attribute__((objc_returns_inner_pointer)); @end + +NS_ASSUME_NONNULL_END diff --git a/ObjectiveGit/GTCredential.m b/ObjectiveGit/GTCredential.m index a53e2bf44..1d3894b44 100644 --- a/ObjectiveGit/GTCredential.m +++ b/ObjectiveGit/GTCredential.m @@ -19,6 +19,7 @@ @interface GTCredentialProvider () @end @implementation GTCredentialProvider + + (instancetype)providerWithBlock:(GTCredentialProviderBlock)credentialBlock { NSParameterAssert(credentialBlock != nil); @@ -70,6 +71,19 @@ + (instancetype)credentialWithUserName:(NSString *)userName publicKeyURL:(NSURL return [[self alloc] initWithGitCred:cred]; } ++ (instancetype)credentialWithUserName:(NSString *)userName publicKeyString:(NSString *)publicKeyString privateKeyString:(NSString *)privateKeyString passphrase:(NSString *)passphrase error:(NSError **)error { + NSParameterAssert(privateKeyString != nil); + + git_cred *cred; + int gitError = git_cred_ssh_key_memory_new(&cred, userName.UTF8String, publicKeyString.UTF8String, privateKeyString.UTF8String, passphrase.UTF8String); + if (gitError != GIT_OK) { + if (error) *error = [NSError git_errorFor:gitError description:@"Failed to create credentials object" failureReason:@"There was an error creating a credential object for username %@ with the provided public/private key pair.\nPublic key: %@", userName, publicKeyString]; + return nil; + } + + return [[self alloc] initWithGitCred:cred]; +} + - (instancetype)initWithGitCred:(git_cred *)cred { NSParameterAssert(cred != nil); self = [self init]; @@ -91,16 +105,16 @@ int GTCredentialAcquireCallback(git_cred **git_cred, const char *url, const char GTCredentialProvider *provider = info->credProvider; if (provider == nil) { - giterr_set_str(GIT_EUSER, "No GTCredentialProvider set, but authentication was requested."); + git_error_set_str(GIT_EUSER, "No GTCredentialProvider set, but authentication was requested."); return GIT_ERROR; } - NSString *URL = (url != NULL ? @(url) : nil); + NSString *URL = (url != NULL ? @(url) : @""); NSString *userName = (username_from_url != NULL ? @(username_from_url) : nil); GTCredential *cred = [provider credentialForType:(GTCredentialType)allowed_types URL:URL userName:userName]; if (cred == nil) { - giterr_set_str(GIT_EUSER, "GTCredentialProvider failed to provide credentials."); + git_error_set_str(GIT_EUSER, "GTCredentialProvider failed to provide credentials."); return GIT_ERROR; } diff --git a/ObjectiveGit/GTDiff+Private.h b/ObjectiveGit/GTDiff+Private.h index fe19f3375..bcf640921 100644 --- a/ObjectiveGit/GTDiff+Private.h +++ b/ObjectiveGit/GTDiff+Private.h @@ -14,6 +14,6 @@ /// provides a pointer to that structure to the given `block`. /// /// Returns the result of invoking `block`. -+ (int)handleParsedOptionsDictionary:(NSDictionary *)dictionary usingBlock:(int (^)(git_diff_options *optionsStruct))block; ++ (int)handleParsedOptionsDictionary:(NSDictionary * _Nullable)dictionary usingBlock:(int (^ _Nonnull)(git_diff_options * _Null_unspecified optionsStruct))block; @end diff --git a/ObjectiveGit/GTDiff.h b/ObjectiveGit/GTDiff.h index f5ce14f47..7264b4432 100644 --- a/ObjectiveGit/GTDiff.h +++ b/ObjectiveGit/GTDiff.h @@ -13,6 +13,9 @@ @class GTDiffDelta; @class GTRepository; @class GTTree; +@class GTIndex; + +NS_ASSUME_NONNULL_BEGIN /// An `NSNumber` wrapped `GTDiffOptionsFlags` representing any flags you wish to /// pass into the initialisation. @@ -190,13 +193,47 @@ typedef NS_OPTIONS(NSInteger, GTDiffFindOptionsFlags) { /// newTree - The "right" side of the diff. May be nil to represent an empty /// tree. /// repository - The repository to be used for the diff. Cannot be nil. -/// options - A dictionary containing any of the above options key constants, or +/// options - A dictionary containing any of the GTDiffOptions key constants, or +/// nil to use the defaults. +/// error - Populated with an `NSError` object on error, if information is +/// available. +/// +/// Returns a newly created `GTDiff` object or nil on error. ++ (instancetype _Nullable)diffOldTree:(GTTree * _Nullable)oldTree withNewTree:(GTTree * _Nullable)newTree inRepository:(GTRepository *)repository options:(NSDictionary * _Nullable)options error:(NSError **)error; + +/// Create a diff between `GTTree` and `GTIndex`. +/// +/// Both instances must be from the same repository, or an exception will be thrown. +/// +/// oldTree - The "left" side of the diff. May be nil to represent an empty +/// tree. +/// newIndex - The "right" side of the diff. May be nil to represent an empty +/// index. +/// repository - The repository to be used for the diff. Cannot be nil. +/// options - A dictionary containing any of the GTDiffOptions key constants, or +/// nil to use the defaults. +/// error - Populated with an `NSError` object on error, if information is +/// available. +/// +/// Returns a newly created `GTDiff` object or nil on error. ++ (instancetype _Nullable)diffOldTree:(GTTree * _Nullable)oldTree withNewIndex:(GTIndex * _Nullable)newIndex inRepository:(GTRepository *)repository options:(NSDictionary * _Nullable)options error:(NSError **)error; + +/// Create a diff between two `GTIndex`es. +/// +/// Both instances must be from the same repository, or an exception will be thrown. +/// +/// oldIndex - The "left" side of the diff. May be nil to represent an empty +/// index. +/// newIndex - The "right" side of the diff. May be nil to represent an empty +/// index. +/// repository - The repository to be used for the diff. Cannot be nil. +/// options - A dictionary containing any of the GTDiffOptions key constants, or /// nil to use the defaults. /// error - Populated with an `NSError` object on error, if information is /// available. /// /// Returns a newly created `GTDiff` object or nil on error. -+ (instancetype)diffOldTree:(GTTree *)oldTree withNewTree:(GTTree *)newTree inRepository:(GTRepository *)repository options:(NSDictionary *)options error:(NSError **)error; ++ (instancetype _Nullable)diffOldIndex:(GTIndex * _Nullable)oldIndex withNewIndex:(GTIndex * _Nullable)newIndex inRepository:(GTRepository *)repository options:(NSDictionary * _Nullable)options error:(NSError **)error; /// Create a diff between a repository's current index. /// @@ -210,52 +247,54 @@ typedef NS_OPTIONS(NSInteger, GTDiffFindOptionsFlags) { /// repository. The left side of the diff. May be nil to represent an /// empty tree. /// repository - The repository to be used for the diff. -/// options - A dictionary containing any of the above options key constants, or +/// options - A dictionary containing any of the GTDiffOptions key constants, or /// nil to use the defaults. /// error - Populated with an `NSError` object on error, if information is /// available. /// /// Returns a newly created `GTDiff` object or nil on error. -+ (instancetype)diffIndexFromTree:(GTTree *)tree inRepository:(GTRepository *)repository options:(NSDictionary *)options error:(NSError **)error; ++ (instancetype _Nullable)diffIndexFromTree:(GTTree * _Nullable)tree inRepository:(GTRepository * _Nullable)repository options:(NSDictionary * _Nullable)options error:(NSError **)error; /// Create a diff between the index and working directory in a given repository. /// /// This matches the `git diff` command. /// -/// repository - The repository to be used for the diff. -/// options - A dictionary containing any of the above options key constants, +/// repository - The repository to be used for the diff. May not be nil. +/// options - A dictionary containing any of the GTDiffOptions key constants, /// or nil to use the defaults. /// error - Populated with an `NSError` object on error, if information is /// available. /// /// Returns a newly created `GTDiff` object or nil on error. -+ (instancetype)diffIndexToWorkingDirectoryInRepository:(GTRepository *)repository options:(NSDictionary *)options error:(NSError **)error; ++ (instancetype _Nullable)diffIndexToWorkingDirectoryInRepository:(GTRepository *)repository options:(NSDictionary * _Nullable)options error:(NSError **)error; /// Create a diff between a repository's working directory and a tree. /// /// tree - The tree to be diffed. The tree will be the left side of the diff. /// May be nil to represent an empty tree. -/// repository - The repository to be used for the diff. -/// options - A dictionary containing any of the above options key constants, or +/// repository - The repository to be used for the diff. May not be nil. +/// options - A dictionary containing any of the GTDiffOptions key constants, or /// nil to use the defaults. /// error - Populated with an `NSError` object on error, if information is /// available. /// /// Returns a newly created `GTDiff` object or nil on error. -+ (instancetype)diffWorkingDirectoryFromTree:(GTTree *)tree inRepository:(GTRepository *)repository options:(NSDictionary *)options error:(NSError **)error; ++ (instancetype _Nullable)diffWorkingDirectoryFromTree:(GTTree * _Nullable)tree inRepository:(GTRepository *)repository options:(NSDictionary * _Nullable)options error:(NSError **)error; /// Create a diff between the working directory and HEAD. /// /// If the repository does not have a HEAD commit yet, this will create a diff of /// the working directory as if everything would be part of the initial commit. /// -/// repository - The repository to be used for the diff. -/// options - A dictionary containing any of the above options key constants, +/// repository - The repository to be used for the diff. May not be nil. +/// options - A dictionary containing any of the GTDiffOptions key constants, /// or nil to use the defaults. /// error - Populated if an error occurs. /// /// Returns a newly created GTDiff, or nil if an error occurred. -+ (instancetype)diffWorkingDirectoryToHEADInRepository:(GTRepository *)repository options:(NSDictionary *)options error:(NSError **)error; ++ (instancetype _Nullable)diffWorkingDirectoryToHEADInRepository:(GTRepository *)repository options:(NSDictionary * _Nullable)options error:(NSError **)error; + +- (instancetype)init NS_UNAVAILABLE; /// Designated initialiser. /// @@ -263,13 +302,13 @@ typedef NS_OPTIONS(NSInteger, GTDiffFindOptionsFlags) { /// repository - The repository in which the diff lives. Cannot be nil. /// /// Returns the initialized object. -- (instancetype)initWithGitDiff:(git_diff *)diff repository:(GTRepository *)repository; +- (instancetype _Nullable)initWithGitDiff:(git_diff *)diff repository:(GTRepository *)repository NS_DESIGNATED_INITIALIZER; /// The libgit2 diff object. - (git_diff *)git_diff __attribute__((objc_returns_inner_pointer)); /// The number of deltas of the given type that are contained in the diff. -- (NSUInteger)numberOfDeltasWithType:(GTDiffDeltaType)deltaType; +- (NSUInteger)numberOfDeltasWithType:(GTDeltaType)deltaType; /// Enumerate the deltas in a diff. /// @@ -281,14 +320,14 @@ typedef NS_OPTIONS(NSInteger, GTDiffFindOptionsFlags) { /// Also note that this method blocks during the enumeration. /// /// block - A block to be executed for each delta. Setting `stop` to `YES` -/// immediately stops the enumeration. +/// immediately stops the enumeration. May not be nil. - (void)enumerateDeltasUsingBlock:(void (^)(GTDiffDelta *delta, BOOL *stop))block; /// Modify the diff list to combine similar changes using the given options. /// -/// options - A dictionary containing any of the above find options key constants +/// options - A dictionary containing any of the GTDiffFindOptions key constants /// or nil to use the defaults. -- (void)findSimilarWithOptions:(NSDictionary *)options; +- (void)findSimilarWithOptions:(NSDictionary * _Nullable)options; /// Merge a diff with another diff. /// @@ -299,3 +338,5 @@ typedef NS_OPTIONS(NSInteger, GTDiffFindOptionsFlags) { - (BOOL)mergeDiffWithDiff:(GTDiff *)diff error:(NSError **)error; @end + +NS_ASSUME_NONNULL_END diff --git a/ObjectiveGit/GTDiff.m b/ObjectiveGit/GTDiff.m index 15ae44143..b3de61898 100644 --- a/ObjectiveGit/GTDiff.m +++ b/ObjectiveGit/GTDiff.m @@ -11,6 +11,7 @@ #import "GTCommit.h" #import "GTRepository.h" #import "GTTree.h" +#import "GTIndex.h" #import "NSArray+StringArray.h" #import "NSError+Git.h" @@ -94,6 +95,37 @@ + (instancetype)diffOldTree:(GTTree *)oldTree withNewTree:(GTTree *)newTree inRe return [[self alloc] initWithGitDiff:diff repository:repository]; } ++ (instancetype)diffOldTree:(GTTree *)oldTree withNewIndex:(GTIndex *)newIndex inRepository:(GTRepository *)repository options:(NSDictionary *)options error:(NSError **)error { + NSParameterAssert(repository != nil); + + __block git_diff *diff; + int status = [self handleParsedOptionsDictionary:options usingBlock:^(git_diff_options *optionsStruct) { + return git_diff_tree_to_index(&diff, repository.git_repository, oldTree.git_tree, newIndex.git_index, optionsStruct); + }]; + if (status != GIT_OK) { + if (error != NULL) *error = [NSError git_errorFor:status description:@"Failed to create diff between %@ and %@", oldTree.SHA, newIndex]; + return nil; + } + + return [[self alloc] initWithGitDiff:diff repository:repository]; +} + ++ (instancetype)diffOldIndex:(GTIndex *)oldIndex withNewIndex:(GTIndex *)newIndex inRepository:(GTRepository *)repository options:(NSDictionary *)options error:(NSError **)error +{ + NSParameterAssert(repository != nil); + + __block git_diff *diff; + int status = [self handleParsedOptionsDictionary:options usingBlock:^(git_diff_options *optionsStruct) { + return git_diff_index_to_index(&diff, repository.git_repository, oldIndex.git_index, newIndex.git_index, optionsStruct); + }]; + if (status != GIT_OK) { + if (error != NULL) *error = [NSError git_errorFor:status description:@"Failed to create diff between %@ and %@", oldIndex, newIndex]; + return nil; + } + + return [[self alloc] initWithGitDiff:diff repository:repository]; +} + + (instancetype)diffIndexFromTree:(GTTree *)tree inRepository:(GTRepository *)repository options:(NSDictionary *)options error:(NSError **)error { NSParameterAssert(repository != nil); NSParameterAssert(tree == nil || [tree.repository isEqual:repository]); @@ -156,6 +188,11 @@ + (instancetype)diffWorkingDirectoryToHEADInRepository:(GTRepository *)repositor return HEADIndexDiff; } +- (instancetype)init { + NSAssert(NO, @"Call to an unavailable initializer."); + return nil; +} + - (instancetype)initWithGitDiff:(git_diff *)diff repository:(GTRepository *)repository { NSParameterAssert(diff != NULL); NSParameterAssert(repository != nil); @@ -197,7 +234,7 @@ - (NSUInteger)deltaCount { return git_diff_num_deltas(self.git_diff); } -- (NSUInteger)numberOfDeltasWithType:(GTDiffDeltaType)deltaType { +- (NSUInteger)numberOfDeltasWithType:(GTDeltaType)deltaType { return git_diff_num_deltas_of_type(self.git_diff, (git_delta_t)deltaType); } diff --git a/ObjectiveGit/GTDiffDelta.h b/ObjectiveGit/GTDiffDelta.h index fa619a4b0..35b8969b3 100644 --- a/ObjectiveGit/GTDiffDelta.h +++ b/ObjectiveGit/GTDiffDelta.h @@ -17,33 +17,38 @@ /// The type of change that this delta represents. /// -/// GTDiffFileDeltaUnmodified - No Change. -/// GTDiffFileDeltaAdded - The file was added to the index. -/// GTDiffFileDeltaDeleted - The file was removed from the working directory. -/// GTDiffFileDeltaModified - The file was modified. -/// GTDiffFileDeltaRenamed - The file has been renamed. -/// GTDiffFileDeltaCopied - The file was duplicated. -/// GTDiffFileDeltaIgnored - The file was ignored by git. -/// GTDiffFileDeltaUntracked - The file has been added to the working directory +/// GTDeltaTypeUnmodified - No Change. +/// GTDeltaTypeAdded - The file was added to the index. +/// GTDeltaTypeDeleted - The file was removed from the working directory. +/// GTDeltaTypeModified - The file was modified. +/// GTDeltaTypeRenamed - The file has been renamed. +/// GTDeltaTypeCopied - The file was duplicated. +/// GTDeltaTypeIgnored - The file was ignored by git. +/// GTDeltaTypeUntracked - The file has been added to the working directory /// and is therefore currently untracked. -/// GTDiffFileDeltaTypeChange - The file has changed from a blob to either a +/// GTDeltaTypeTypeChange - The file has changed from a blob to either a /// submodule, symlink or directory. Or vice versa. -typedef NS_ENUM(NSInteger, GTDiffDeltaType) { - GTDiffFileDeltaUnmodified = GIT_DELTA_UNMODIFIED, - GTDiffFileDeltaAdded = GIT_DELTA_ADDED, - GTDiffFileDeltaDeleted = GIT_DELTA_DELETED, - GTDiffFileDeltaModified = GIT_DELTA_MODIFIED, - GTDiffFileDeltaRenamed = GIT_DELTA_RENAMED, - GTDiffFileDeltaCopied = GIT_DELTA_COPIED, - GTDiffFileDeltaIgnored = GIT_DELTA_IGNORED, - GTDiffFileDeltaUntracked = GIT_DELTA_UNTRACKED, - GTDiffFileDeltaTypeChange = GIT_DELTA_TYPECHANGE, +/// GTDeltaTypeConflicted - The file is conflicted in the working directory. +typedef NS_ENUM(NSInteger, GTDeltaType) { + GTDeltaTypeUnmodified = GIT_DELTA_UNMODIFIED, + GTDeltaTypeAdded = GIT_DELTA_ADDED, + GTDeltaTypeDeleted = GIT_DELTA_DELETED, + GTDeltaTypeModified = GIT_DELTA_MODIFIED, + GTDeltaTypeRenamed = GIT_DELTA_RENAMED, + GTDeltaTypeCopied = GIT_DELTA_COPIED, + GTDeltaTypeIgnored = GIT_DELTA_IGNORED, + GTDeltaTypeUntracked = GIT_DELTA_UNTRACKED, + GTDeltaTypeTypeChange = GIT_DELTA_TYPECHANGE, + GTDeltaTypeUnreadable = GIT_DELTA_UNREADABLE, + GTDeltaTypeConflicted = GIT_DELTA_CONFLICTED, }; +NS_ASSUME_NONNULL_BEGIN + /// A class representing a single change within a diff. /// /// The change may not be simply a change of text within a given file, it could -/// be that the file was renamed, or added to the index. See `GTDiffDeltaType` +/// be that the file was renamed, or added to the index. See `GTDeltaType` /// for the types of change represented. @interface GTDiffDelta : NSObject @@ -58,15 +63,17 @@ typedef NS_ENUM(NSInteger, GTDiffDeltaType) { @property (nonatomic, assign, readonly) GTDiffFileFlag flags; /// The file to the "left" of the diff. -@property (nonatomic, readonly, copy) GTDiffFile *oldFile; +@property (nonatomic, readonly, copy) GTDiffFile * _Nullable oldFile; /// The file to the "right" of the diff. -@property (nonatomic, readonly, copy) GTDiffFile *newFile __attribute__((ns_returns_not_retained)); +@property (nonatomic, readonly, copy) GTDiffFile * _Nullable newFile __attribute__((ns_returns_not_retained)); /// The type of change that this delta represents. /// /// Think "status" as in `git status`. -@property (nonatomic, readonly) GTDiffDeltaType type; +@property (nonatomic, readonly) GTDeltaType type; + +@property (nonatomic, readonly, assign) double similarity; /// Diffs the given blob and data buffer. /// @@ -81,7 +88,7 @@ typedef NS_ENUM(NSInteger, GTDiffDeltaType) { /// error - If not NULL, set to any error that occurs. /// /// Returns a diff delta, or nil if an error occurs. -+ (instancetype)diffDeltaFromBlob:(GTBlob *)oldBlob forPath:(NSString *)oldBlobPath toBlob:(GTBlob *)newBlob forPath:(NSString *)newBlobPath options:(NSDictionary *)options error:(NSError **)error; ++ (instancetype _Nullable)diffDeltaFromBlob:(GTBlob * _Nullable)oldBlob forPath:(NSString * _Nullable)oldBlobPath toBlob:(GTBlob * _Nullable)newBlob forPath:(NSString * _Nullable)newBlobPath options:(NSDictionary * _Nullable)options error:(NSError **)error; /// Diffs the given blob and data buffer. /// @@ -96,7 +103,7 @@ typedef NS_ENUM(NSInteger, GTDiffDeltaType) { /// error - If not NULL, set to any error that occurs. /// /// Returns a diff delta, or nil if an error occurs. -+ (instancetype)diffDeltaFromBlob:(GTBlob *)blob forPath:(NSString *)blobPath toData:(NSData *)data forPath:(NSString *)dataPath options:(NSDictionary *)options error:(NSError **)error; ++ (instancetype _Nullable)diffDeltaFromBlob:(GTBlob * _Nullable)blob forPath:(NSString * _Nullable)blobPath toData:(NSData * _Nullable)data forPath:(NSString * _Nullable)dataPath options:(NSDictionary * _Nullable)options error:(NSError **)error; /// Diffs the given data buffers. /// @@ -111,10 +118,17 @@ typedef NS_ENUM(NSInteger, GTDiffDeltaType) { /// error - If not NULL, set to any error that occurs. /// /// Returns a diff delta, or nil if an error occurs. -+ (instancetype)diffDeltaFromData:(NSData *)oldData forPath:(NSString *)oldDataPath toData:(NSData *)newData forPath:(NSString *)newDataPath options:(NSDictionary *)options error:(NSError **)error; ++ (instancetype _Nullable)diffDeltaFromData:(NSData * _Nullable)oldData forPath:(NSString * _Nullable)oldDataPath toData:(NSData * _Nullable)newData forPath:(NSString * _Nullable)newDataPath options:(NSDictionary * _Nullable)options error:(NSError **)error; + +- (instancetype)init NS_UNAVAILABLE; /// Initializes the receiver to wrap the delta at the given index. -- (instancetype)initWithDiff:(GTDiff *)diff deltaIndex:(NSUInteger)deltaIndex; +/// +/// diff - The diff which contains the delta to wrap. Must not be nil. +/// deltaIndex - The index of the delta within the diff. +/// +/// Returns a diff delta, or nil if an error occurs. +- (instancetype _Nullable)initWithDiff:(GTDiff *)diff deltaIndex:(NSUInteger)deltaIndex; /// Creates a patch from a text delta. /// @@ -123,6 +137,8 @@ typedef NS_ENUM(NSInteger, GTDiffDeltaType) { /// error - If not NULL, set to any error that occurs. /// /// Returns a new patch, or nil if an error occurs. -- (GTDiffPatch *)generatePatch:(NSError **)error; +- (GTDiffPatch * _Nullable)generatePatch:(NSError **)error; @end + +NS_ASSUME_NONNULL_END diff --git a/ObjectiveGit/GTDiffDelta.m b/ObjectiveGit/GTDiffDelta.m index b1f374bf7..28358f14f 100644 --- a/ObjectiveGit/GTDiffDelta.m +++ b/ObjectiveGit/GTDiffDelta.m @@ -32,7 +32,7 @@ @interface GTDiffDelta () /// the given diff delta. Must not be nil. /// /// This is the designated initializer for this class. -- (instancetype)initWithGitDiffDeltaBlock:(git_diff_delta (^)(void))deltaAccessor patchGeneratorBlock:(int (^)(git_patch **patch))patchGenerator; +- (instancetype)initWithGitDiffDeltaBlock:(git_diff_delta (^)(void))deltaAccessor patchGeneratorBlock:(int (^)(git_patch **patch))patchGenerator NS_DESIGNATED_INITIALIZER; @end @@ -56,8 +56,12 @@ - (GTDiffFile *)newFile { return [[GTDiffFile alloc] initWithGitDiffFile:self.git_diff_delta.new_file]; } -- (GTDiffDeltaType)type { - return (GTDiffDeltaType)self.git_diff_delta.status; +- (GTDeltaType)type { + return (GTDeltaType)self.git_diff_delta.status; +} + +- (double)similarity { + return (double)(self.git_diff_delta.similarity / 100.0); } #pragma mark Lifecycle @@ -73,7 +77,7 @@ + (instancetype)diffDeltaFromBlob:(GTBlob *)oldBlob forPath:(NSString *)oldBlobP __block git_diff_delta diffDelta; int returnValue = [GTDiff handleParsedOptionsDictionary:options usingBlock:^(git_diff_options *optionsStruct) { - return git_diff_blobs(oldBlob.git_blob, oldBlobPath.UTF8String, newBlob.git_blob, newBlobPath.UTF8String, optionsStruct, >DiffDeltaCallback, NULL, NULL, &diffDelta); + return git_diff_blobs(oldBlob.git_blob, oldBlobPath.UTF8String, newBlob.git_blob, newBlobPath.UTF8String, optionsStruct, >DiffDeltaCallback, NULL, NULL, NULL, &diffDelta); }]; if (returnValue != GIT_OK) { @@ -94,7 +98,7 @@ + (instancetype)diffDeltaFromBlob:(GTBlob *)blob forPath:(NSString *)blobPath to __block git_diff_delta diffDelta; int returnValue = [GTDiff handleParsedOptionsDictionary:options usingBlock:^(git_diff_options *optionsStruct) { - return git_diff_blob_to_buffer(blob.git_blob, blobPath.UTF8String, data.bytes, data.length, dataPath.UTF8String, optionsStruct, >DiffDeltaCallback, NULL, NULL, &diffDelta); + return git_diff_blob_to_buffer(blob.git_blob, blobPath.UTF8String, data.bytes, data.length, dataPath.UTF8String, optionsStruct, >DiffDeltaCallback, NULL, NULL, NULL, &diffDelta); }]; if (returnValue != GIT_OK) { @@ -115,7 +119,7 @@ + (instancetype)diffDeltaFromData:(NSData *)oldData forPath:(NSString *)oldDataP __block git_diff_delta diffDelta; int returnValue = [GTDiff handleParsedOptionsDictionary:options usingBlock:^(git_diff_options *optionsStruct) { - return git_diff_buffers(oldData.bytes, oldData.length, oldDataPath.UTF8String, newData.bytes, newData.length, newDataPath.UTF8String, optionsStruct, >DiffDeltaCallback, NULL, NULL, &diffDelta); + return git_diff_buffers(oldData.bytes, oldData.length, oldDataPath.UTF8String, newData.bytes, newData.length, newDataPath.UTF8String, optionsStruct, >DiffDeltaCallback, NULL, NULL, NULL, &diffDelta); }]; if (returnValue != GIT_OK) { @@ -132,6 +136,11 @@ + (instancetype)diffDeltaFromData:(NSData *)oldData forPath:(NSString *)oldDataP }]; } +- (instancetype)init { + NSAssert(NO, @"Call to an unavailable initializer."); + return nil; +} + - (instancetype)initWithDiff:(GTDiff *)diff deltaIndex:(NSUInteger)deltaIndex { NSCParameterAssert(diff != nil); diff --git a/ObjectiveGit/GTDiffFile.h b/ObjectiveGit/GTDiffFile.h index a89904d45..e88935ffb 100644 --- a/ObjectiveGit/GTDiffFile.h +++ b/ObjectiveGit/GTDiffFile.h @@ -25,6 +25,8 @@ typedef NS_OPTIONS(NSInteger, GTDiffFileFlag) { @class GTOID; +NS_ASSUME_NONNULL_BEGIN + /// A class representing a file on one side of a diff. @interface GTDiffFile : NSObject @@ -41,16 +43,20 @@ typedef NS_OPTIONS(NSInteger, GTDiffFileFlag) { @property (nonatomic, readonly) mode_t mode; /// The OID for the file. -@property (nonatomic, readonly, copy) GTOID *OID; +@property (nonatomic, readonly, copy) GTOID * _Nullable OID; /// The git_diff_file represented by the receiver. @property (nonatomic, readonly) git_diff_file git_diff_file; -/// Initializes the receiver with the provided libgit2 object. +- (instancetype)init NS_UNAVAILABLE; + +/// Initializes the receiver with the provided libgit2 object. Designated initializer. /// /// file - The git_diff_file wrapped by the receiver. /// /// Returns an initialized GTDiffFile. -- (instancetype)initWithGitDiffFile:(git_diff_file)file; +- (instancetype _Nullable)initWithGitDiffFile:(git_diff_file)file NS_DESIGNATED_INITIALIZER; @end + +NS_ASSUME_NONNULL_END diff --git a/ObjectiveGit/GTDiffFile.m b/ObjectiveGit/GTDiffFile.m index 1478b6cbe..24b3c7b11 100644 --- a/ObjectiveGit/GTDiffFile.m +++ b/ObjectiveGit/GTDiffFile.m @@ -11,14 +11,20 @@ @implementation GTDiffFile +- (instancetype)init { + NSAssert(NO, @"Call to an unavailable initializer."); + return nil; +} + - (instancetype)initWithGitDiffFile:(git_diff_file)file { NSParameterAssert(file.path != NULL); self = [super init]; if (self == nil) return nil; - _path = @(file.path); - if (_path == nil) return nil; + NSString *path = @(file.path); + if (path == nil) return nil; + _path = path; _git_diff_file = file; _size = (NSUInteger)file.size; diff --git a/ObjectiveGit/GTDiffHunk.h b/ObjectiveGit/GTDiffHunk.h index feb4d2915..164185e58 100644 --- a/ObjectiveGit/GTDiffHunk.h +++ b/ObjectiveGit/GTDiffHunk.h @@ -11,6 +11,8 @@ @class GTDiffLine; @class GTDiffPatch; +NS_ASSUME_NONNULL_BEGIN + /// A class representing a hunk within a diff patch. @interface GTDiffHunk : NSObject @@ -20,11 +22,30 @@ /// The number of lines represented in the hunk. @property (nonatomic, readonly) NSUInteger lineCount; +/// The starting line number in the old file +@property (nonatomic, readonly) NSUInteger oldStart; + +/// The number of lines in the old file +@property (nonatomic, readonly) NSUInteger oldLines; + +/// The starting line number in the new file +@property (nonatomic, readonly) NSUInteger newStart; + +/// The number of lines in the new file +@property (nonatomic, readonly) NSUInteger newLines; + +- (instancetype)init NS_UNAVAILABLE; + /// Designated initialiser. /// /// The contents of a hunk are lazily loaded, therefore we initialise the object /// simply with the patch it originates from and which hunk index it represents. -- (instancetype)initWithPatch:(GTDiffPatch *)patch hunkIndex:(NSUInteger)hunkIndex; +/// +/// patch - The patch the hunk originates from. Must not be nil. +/// hunkIndex - The hunk's index within the patch. +/// +/// Returns the initialized instance. +- (instancetype _Nullable)initWithPatch:(GTDiffPatch *)patch hunkIndex:(NSUInteger)hunkIndex NS_DESIGNATED_INITIALIZER; /// Perfoms the given block on each line in the hunk. /// @@ -32,9 +53,12 @@ /// /// error - A pointer to an NSError that will be set if one occurs. /// block - A block to execute on each line. Setting `stop` to `NO` will -/// immediately stop the enumeration and return from the method. +/// immediately stop the enumeration and return from the method. Must not +/// be nil. /// Return YES if the enumeration was successful, NO otherwise (and an error will /// be set in `error`). - (BOOL)enumerateLinesInHunk:(NSError **)error usingBlock:(void (^)(GTDiffLine *line, BOOL *stop))block; @end + +NS_ASSUME_NONNULL_END diff --git a/ObjectiveGit/GTDiffHunk.m b/ObjectiveGit/GTDiffHunk.m index 51cabae78..0b822903f 100644 --- a/ObjectiveGit/GTDiffHunk.m +++ b/ObjectiveGit/GTDiffHunk.m @@ -25,6 +25,11 @@ @interface GTDiffHunk () @implementation GTDiffHunk +- (instancetype)init { + NSAssert(NO, @"Call to an unavailable initializer."); + return nil; +} + - (instancetype)initWithPatch:(GTDiffPatch *)patch hunkIndex:(NSUInteger)hunkIndex { NSParameterAssert(patch != nil); @@ -35,10 +40,16 @@ - (instancetype)initWithPatch:(GTDiffPatch *)patch hunkIndex:(NSUInteger)hunkInd int result = git_patch_get_hunk(&_git_hunk, &gitLineCount, patch.git_patch, hunkIndex); if (result != GIT_OK) return nil; _lineCount = gitLineCount; + _oldStart = self.git_hunk->old_start; + _oldLines = self.git_hunk->old_lines; + _newStart = self.git_hunk->new_start; + _newLines = self.git_hunk->new_lines; _patch = patch; _hunkIndex = hunkIndex; - _header = [[[NSString alloc] initWithBytes:self.git_hunk->header length:self.git_hunk->header_len encoding:NSUTF8StringEncoding] stringByTrimmingCharactersInSet:NSCharacterSet.newlineCharacterSet]; + NSString *hunkHeader = [[[NSString alloc] initWithBytes:self.git_hunk->header length:self.git_hunk->header_len encoding:NSUTF8StringEncoding] stringByTrimmingCharactersInSet:NSCharacterSet.newlineCharacterSet]; + NSAssert(hunkHeader != nil, @"Failed to build hunk header"); + _header = hunkHeader; return self; } diff --git a/ObjectiveGit/GTDiffLine.h b/ObjectiveGit/GTDiffLine.h index eaf2dcee8..26dc1949f 100644 --- a/ObjectiveGit/GTDiffLine.h +++ b/ObjectiveGit/GTDiffLine.h @@ -21,6 +21,8 @@ typedef NS_ENUM(char, GTDiffLineOrigin) { GTDiffLineOriginDeleteEOFNewLine = GIT_DIFF_LINE_DEL_EOFNL, }; +NS_ASSUME_NONNULL_BEGIN + /// Represents an individual line in a diff hunk. @interface GTDiffLine : NSObject @@ -43,7 +45,15 @@ typedef NS_ENUM(char, GTDiffLineOrigin) { /// The number of newlines appearing in `-content`. @property (nonatomic, readonly) NSInteger lineCount; +- (instancetype)init NS_UNAVAILABLE; + /// Designated initialiser. -- (instancetype)initWithGitLine:(const git_diff_line *)line; +/// +/// line - The diff line to wrap. May not be NULL. +/// +/// Returns a diff line, or nil if an error occurs. +- (instancetype _Nullable)initWithGitLine:(const git_diff_line *)line NS_DESIGNATED_INITIALIZER; @end + +NS_ASSUME_NONNULL_END diff --git a/ObjectiveGit/GTDiffLine.m b/ObjectiveGit/GTDiffLine.m index 36df18c6e..1d20211cd 100644 --- a/ObjectiveGit/GTDiffLine.m +++ b/ObjectiveGit/GTDiffLine.m @@ -10,6 +10,11 @@ @implementation GTDiffLine +- (instancetype)init { + NSAssert(NO, @"Call to an unavailable initializer."); + return nil; +} + - (instancetype)initWithGitLine:(const git_diff_line *)line { self = [super init]; if (self == nil) return nil; diff --git a/ObjectiveGit/GTDiffPatch.h b/ObjectiveGit/GTDiffPatch.h index f2f372e36..a76b6de9e 100644 --- a/ObjectiveGit/GTDiffPatch.h +++ b/ObjectiveGit/GTDiffPatch.h @@ -12,6 +12,8 @@ @class GTDiffHunk; @class GTDiffDelta; +NS_ASSUME_NONNULL_BEGIN + /// Represents one or more text changes to a single file within a diff. @interface GTDiffPatch : NSObject @@ -30,13 +32,15 @@ /// The number of hunks in this patch. @property (nonatomic, readonly) NSUInteger hunkCount; -/// Initializes the receiver to wrap the given patch. +- (instancetype)init NS_UNAVAILABLE; + +/// Initializes the receiver to wrap the given patch. Designated initializer. /// /// patch - The patch object to wrap and take ownership of. This will /// automatically be freed when the receiver is deallocated. Must not be /// NULL. /// delta - The diff delta corresponding to this patch. Must not be nil. -- (instancetype)initWithGitPatch:(git_patch *)patch delta:(GTDiffDelta *)delta; +- (instancetype _Nullable)initWithGitPatch:(git_patch *)patch delta:(GTDiffDelta *)delta NS_DESIGNATED_INITIALIZER; /// Returns the underlying patch object. - (git_patch *)git_patch __attribute__((objc_returns_inner_pointer)); @@ -50,16 +54,21 @@ /// Returns the raw size of the delta, in bytes. - (NSUInteger)sizeWithContext:(BOOL)includeContext hunkHeaders:(BOOL)includeHunkHeaders fileHeaders:(BOOL)includeFileHeaders; +/// Returns the raw patch data. +- (NSData *)patchData; + /// Enumerate the hunks contained in the patch. /// /// This enumeration is synchronous, and will block the calling thread while /// generating hunk content. /// /// block - A block to be executed for each hunk. Setting `stop` to `YES` -/// will stop the enumeration after the block returns. +/// will stop the enumeration after the block returns. May not be nil. /// /// Returns whether enumeration was successful, or terminated early. If `NO`, an /// error occurred during enumeration. - (BOOL)enumerateHunksUsingBlock:(void (^)(GTDiffHunk *hunk, BOOL *stop))block; @end + +NS_ASSUME_NONNULL_END diff --git a/ObjectiveGit/GTDiffPatch.m b/ObjectiveGit/GTDiffPatch.m index 2136e3add..715db5a13 100644 --- a/ObjectiveGit/GTDiffPatch.m +++ b/ObjectiveGit/GTDiffPatch.m @@ -20,6 +20,11 @@ @implementation GTDiffPatch #pragma mark Lifecycle +- (instancetype)init { + NSAssert(NO, @"Call to an unavailable initializer."); + return nil; +} + - (instancetype)initWithGitPatch:(git_patch *)patch delta:(GTDiffDelta *)delta { NSParameterAssert(patch != NULL); NSParameterAssert(delta != nil); @@ -59,6 +64,16 @@ - (NSUInteger)sizeWithContext:(BOOL)includeContext hunkHeaders:(BOOL)includeHunk return git_patch_size(self.git_patch, includeContext, includeHunkHeaders, includeFileHeaders); } +- (NSData *)patchData { + git_buf buf = GIT_BUF_INIT_CONST(0, NULL); + git_patch_to_buf(&buf, self.git_patch); + + NSData *buffer = [[NSData alloc] initWithBytes:buf.ptr length:buf.size]; + git_buf_dispose(&buf); + + return buffer; +} + #pragma mark Hunks - (BOOL)enumerateHunksUsingBlock:(void (^)(GTDiffHunk *hunk, BOOL *stop))block { diff --git a/ObjectiveGit/GTEnumerator.h b/ObjectiveGit/GTEnumerator.h index 8f877485a..4d8b27201 100644 --- a/ObjectiveGit/GTEnumerator.h +++ b/ObjectiveGit/GTEnumerator.h @@ -49,6 +49,8 @@ typedef NS_OPTIONS(unsigned int, GTEnumeratorOptions) { @class GTRepository; @class GTCommit; +NS_ASSUME_NONNULL_BEGIN + /// Enumerates the commits in a repository. @interface GTEnumerator : NSEnumerator @@ -60,13 +62,18 @@ typedef NS_OPTIONS(unsigned int, GTEnumeratorOptions) { /// To set new options, use -resetWithOptions:. @property (nonatomic, assign, readonly) GTEnumeratorOptions options; -/// Initializes the receiver to enumerate the commits in the given repository. +- (instancetype)init NS_UNAVAILABLE; + +/// The underlying `git_revwalk` from libgit2. +- (git_revwalk *)git_revwalk __attribute__((objc_returns_inner_pointer)); + +/// Initializes the receiver to enumerate the commits in the given repository. Designated initializer. /// /// repo - The repository to enumerate the commits of. This must not be nil. /// error - If not NULL, set to any error that occurs. /// /// Returns an initialized enumerator, or nil if an error occurs. -- (id)initWithRepository:(GTRepository *)repo error:(NSError **)error; +- (id _Nullable)initWithRepository:(GTRepository *)repo error:(NSError **)error NS_DESIGNATED_INITIALIZER; /// Marks a commit to start traversal from. /// @@ -85,6 +92,21 @@ typedef NS_OPTIONS(unsigned int, GTEnumeratorOptions) { /// Returns whether pushing matching references was successful. - (BOOL)pushGlob:(NSString *)refGlob error:(NSError **)error; +/// Push HEAD reference. +/// +/// error - If not NULL, this will be set to any error that occurs. +/// +/// Returns whether pushing the HEAD reference was successful. +- (BOOL)pushHEAD:(NSError **)error; + +/// Push a reference by name. +/// +/// refName - The reference name to push. Must not be nil. +/// error - If not NULL, this will be set to any error that occurs. +/// +/// Returns whether pushing the reference name was successful. +- (BOOL)pushReferenceName:(NSString *)refName error:(NSError **)error; + /// Hides the specified commit and all of its ancestors when enumerating. /// /// sha - The SHA of a commit in the receiver's repository. This must not be @@ -102,6 +124,22 @@ typedef NS_OPTIONS(unsigned int, GTEnumeratorOptions) { /// Returns whether marking matching references for hiding was successful. - (BOOL)hideGlob:(NSString *)refGlob error:(NSError **)error; +/// Hide HEAD reference. +/// +/// error - If not NULL, this will be set to any error that occurs. +/// +/// Returns whether marking HEAD for hiding was successful. +- (BOOL)hideHEAD:(NSError **)error; + + +/// Hide a reference by name. +/// +/// refName - The reference name to hide. Must not be nil. +/// error - If not NULL, this will be set to any error that occurs. +/// +/// Returns whether hiding the reference name was successful. +- (BOOL)hideReferenceName:(NSString *)refName error:(NSError **)error; + /// Resets the receiver, putting it back into a clean state for reuse, and /// replacing the receiver's `options`. - (void)resetWithOptions:(GTEnumeratorOptions)options; @@ -111,7 +149,17 @@ typedef NS_OPTIONS(unsigned int, GTEnumeratorOptions) { /// error - If not NULL, set to any error that occurs during traversal. /// /// Returns a (possibly empty) array of GTCommits, or nil if an error occurs. -- (NSArray *)allObjectsWithError:(NSError **)error; +- (NSArray * _Nullable)allObjectsWithError:(NSError **)error; + +/// Get the next OID. +/// +/// success - If not NULL, this will be set to whether getting the next object +/// was successful. This will be YES if the receiver is exhausted, so +/// it can be used to interpret the meaning of a nil return value. +/// error - If not NULL, set to any error that occurs during traversal. +/// +/// Returns nil if an error occurs or the enumeration is done. +- (GTOID * _Nullable)nextOIDWithSuccess:(BOOL * _Nullable)success error:(NSError **)error; /// Gets the next commit. /// @@ -121,7 +169,7 @@ typedef NS_OPTIONS(unsigned int, GTEnumeratorOptions) { /// error - If not NULL, set to any error that occurs during traversal. /// /// Returns nil if an error occurs or the receiver is exhausted. -- (GTCommit *)nextObjectWithSuccess:(BOOL *)success error:(NSError **)error; +- (GTCommit * _Nullable)nextObjectWithSuccess:(BOOL * _Nullable)success error:(NSError **)error; /// Counts the number of commits that were not enumerated, completely exhausting /// the receiver. @@ -132,3 +180,5 @@ typedef NS_OPTIONS(unsigned int, GTEnumeratorOptions) { - (NSUInteger)countRemainingObjects:(NSError **)error; @end + +NS_ASSUME_NONNULL_END diff --git a/ObjectiveGit/GTEnumerator.m b/ObjectiveGit/GTEnumerator.m index 9783cdc7b..b684d4e3e 100644 --- a/ObjectiveGit/GTEnumerator.m +++ b/ObjectiveGit/GTEnumerator.m @@ -48,7 +48,16 @@ @implementation GTEnumerator #pragma mark Lifecycle -- (id)initWithRepository:(GTRepository *)repo error:(NSError **)error { +- (instancetype)init { + NSAssert(NO, @"Call to an unavailable initializer."); + return nil; +} + +- (git_revwalk *)git_revwalk { + return self.walk; +} + +- (instancetype)initWithRepository:(GTRepository *)repo error:(NSError **)error { NSParameterAssert(repo != nil); self = [super init]; @@ -102,6 +111,26 @@ - (BOOL)pushGlob:(NSString *)refGlob error:(NSError **)error { return YES; } +- (BOOL)pushHEAD:(NSError **)error { + int gitError = git_revwalk_push_head(self.walk); + if (gitError != GIT_OK) { + if (error != NULL) *error = [NSError git_errorFor:gitError description:@"Failed to push HEAD onto rev walker."]; + return NO; + } + return YES; +} + +- (BOOL)pushReferenceName:(NSString *)refName error:(NSError **)error { + NSParameterAssert(refName != nil); + + int gitError = git_revwalk_push_ref(self.walk, refName.UTF8String); + if (gitError != 0) { + if (error) *error = [NSError git_errorFor:gitError description:@"Failed to push reference %@", refName]; + return NO; + } + return YES; +} + - (BOOL)hideSHA:(NSString *)sha error:(NSError **)error { NSParameterAssert(sha != nil); @@ -122,13 +151,33 @@ - (BOOL)hideGlob:(NSString *)refGlob error:(NSError **)error { int gitError = git_revwalk_hide_glob(self.walk, refGlob.UTF8String); if (gitError != GIT_OK) { - if (error != NULL) *error = [NSError git_errorFor:gitError description:@"Failed to push glob %@ onto rev walker.", refGlob]; + if (error != NULL) *error = [NSError git_errorFor:gitError description:@"Failed to hide glob %@ in rev walker.", refGlob]; return NO; } return YES; } +- (BOOL)hideHEAD:(NSError **)error { + int gitError = git_revwalk_hide_head(self.walk); + if (gitError != GIT_OK) { + if (error != NULL) *error = [NSError git_errorFor:gitError description:@"Failed to hide HEAD onto rev walker."]; + return NO; + } + return YES; +} + +- (BOOL)hideReferenceName:(NSString *)refName error:(NSError **)error { + NSParameterAssert(refName != nil); + + int gitError = git_revwalk_hide_ref(self.walk, refName.UTF8String); + if (gitError != 0) { + if (error) *error = [NSError git_errorFor:gitError description:@"Failed to hide reference %@", refName]; + return NO; + } + return YES; +} + #pragma mark Resetting - (void)resetWithOptions:(GTEnumeratorOptions)options { @@ -140,16 +189,34 @@ - (void)resetWithOptions:(GTEnumeratorOptions)options { #pragma mark Enumerating -- (GTCommit *)nextObjectWithSuccess:(BOOL *)success error:(NSError **)error { +- (GTOID *)nextOIDWithSuccess:(BOOL *)success error:(NSError **)error { git_oid oid; + int gitError = git_revwalk_next(&oid, self.walk); if (gitError == GIT_ITEROVER) { if (success != NULL) *success = YES; return nil; } + if (gitError != GIT_OK) { + if (success != NULL) *success = NO; + if (error != NULL) *error = [NSError git_errorFor:gitError description:@"Enumeration failed"]; + return nil; + } + + if (success != NULL) *success = YES; + return [GTOID oidWithGitOid:&oid]; +} + +- (GTCommit *)nextObjectWithSuccess:(BOOL *)success error:(NSError **)error { + GTOID *oid = [self nextOIDWithSuccess:success error:error]; + if (oid == nil) { + // We don't care whether the iteration completed, or an error occurred, + // there's nothing to lookup. + return nil; + } // Ignore error if we can't lookup object and just return nil. - GTCommit *commit = [self.repository lookUpObjectByGitOid:&oid objectType:GTObjectTypeCommit error:error]; + GTCommit *commit = [self.repository lookUpObjectByOID:oid objectType:GTObjectTypeCommit error:error]; if (success != NULL) *success = (commit != nil); return commit; } @@ -192,7 +259,8 @@ - (NSUInteger)countRemainingObjects:(NSError **)error { #pragma mark NSEnumerator - (NSArray *)allObjects { - return [self allObjectsWithError:NULL]; + NSArray *objects = [self allObjectsWithError:NULL]; + return objects ? objects : [NSArray array]; } - (id)nextObject { diff --git a/ObjectiveGit/GTFetchHeadEntry.h b/ObjectiveGit/GTFetchHeadEntry.h index 3a926c862..fd6fa466f 100644 --- a/ObjectiveGit/GTFetchHeadEntry.h +++ b/ObjectiveGit/GTFetchHeadEntry.h @@ -12,6 +12,8 @@ @class GTOID; @class GTReference; +NS_ASSUME_NONNULL_BEGIN + /// A class representing an entry on the FETCH_HEAD file, as returned by the callback of git_repository_fetchhead_foreach. @interface GTFetchHeadEntry : NSObject @@ -27,12 +29,18 @@ /// Flag indicating if we need to merge this entry or not. @property (nonatomic, getter = isMerge, readonly) BOOL merge; -/// Initializes a GTFetchHeadEntry. +- (instancetype)init NS_UNAVAILABLE; + +/// Initializes a GTFetchHeadEntry. Designated initializer. /// /// reference - Reference on the repository. Cannot be nil. /// remoteURLString - URL String where this was originally fetched from. Cannot be nil. /// targetOID - Target OID. Cannot be nil. /// merge - Indicates if this is pending a merge. -- (instancetype)initWithReference:(GTReference *)reference remoteURLString:(NSString *)remoteURLString targetOID:(GTOID *)targetOID isMerge:(BOOL)merge; +/// +/// Returns an initialized fetch head entry, or nil if an error occurred. +- (instancetype _Nullable)initWithReference:(GTReference *)reference remoteURLString:(NSString *)remoteURLString targetOID:(GTOID *)targetOID isMerge:(BOOL)merge NS_DESIGNATED_INITIALIZER; @end + +NS_ASSUME_NONNULL_END diff --git a/ObjectiveGit/GTFetchHeadEntry.m b/ObjectiveGit/GTFetchHeadEntry.m index 04a75c28a..ac8e1d235 100644 --- a/ObjectiveGit/GTFetchHeadEntry.m +++ b/ObjectiveGit/GTFetchHeadEntry.m @@ -11,6 +11,11 @@ @implementation GTFetchHeadEntry +- (instancetype)init { + NSAssert(NO, @"Call to an unavailable initializer."); + return nil; +} + - (instancetype)initWithReference:(GTReference *)reference remoteURLString:(NSString *)remoteURLString targetOID:(GTOID *)targetOID isMerge:(BOOL)merge { NSParameterAssert(reference != nil); NSParameterAssert(remoteURLString != nil); diff --git a/ObjectiveGit/GTFilter.h b/ObjectiveGit/GTFilter.h index 8205b04f4..51b2e7196 100644 --- a/ObjectiveGit/GTFilter.h +++ b/ObjectiveGit/GTFilter.h @@ -11,6 +11,8 @@ @class GTRepository; @class GTFilterSource; +NS_ASSUME_NONNULL_BEGIN + /// The error domain for errors originating from GTFilter. extern NSString * const GTFilterErrorDomain; @@ -32,28 +34,32 @@ extern const NSInteger GTFilterErrorNameAlreadyRegistered; /// The check block. Determines whether the `applyBlock` should be run for given /// source. -@property (nonatomic, copy) BOOL (^checkBlock)(void **payload, GTFilterSource *source, const char **attr_values); +@property (nonatomic, copy) BOOL (^checkBlock)(void * _Null_unspecified * _Null_unspecified payload, GTFilterSource *source, const char * _Null_unspecified * _Null_unspecified attr_values); /// The cleanup block. Called after the `applyBlock` to given the filter a /// chance to clean up the `payload`. @property (nonatomic, copy) void (^cleanupBlock)(void *payload); -/// Initializes the object with the given name and attributes. +- (instancetype)init NS_UNAVAILABLE; + +/// Initializes the object with the given name and attributes. Designated initializer. /// /// name - The name for the filter. Cannot be nil. /// attributes - The attributes to which this filter applies. May be nil. /// applyBlock - The block to use to apply the filter. Cannot be nil. /// /// Returns the initialized object. -- (id)initWithName:(NSString *)name attributes:(NSString *)attributes applyBlock:(NSData * (^)(void **payload, NSData *from, GTFilterSource *source, BOOL *applied))applyBlock; +- (instancetype _Nullable)initWithName:(NSString *)name attributes:(NSString * _Nullable)attributes applyBlock:(NSData * (^)(void * _Null_unspecified * _Null_unspecified payload, NSData *from, GTFilterSource *source, BOOL *applied))applyBlock NS_DESIGNATED_INITIALIZER; /// Look up a filter based on its name. /// /// Note that this will only find filters registered through /// -registerWithName:priority:error:. /// +/// name - The name of the filter to retrieve. Must not be nil. +/// /// Returns the filter, or nil if none was found. -+ (GTFilter *)filterForName:(NSString *)name; ++ (GTFilter * _Nullable)filterForName:(NSString *)name; /// Registers the filter with the given priority. /// @@ -73,3 +79,5 @@ extern const NSInteger GTFilterErrorNameAlreadyRegistered; - (BOOL)unregister:(NSError **)error; @end + +NS_ASSUME_NONNULL_END diff --git a/ObjectiveGit/GTFilter.m b/ObjectiveGit/GTFilter.m index 74a90c8ed..69c185ca7 100644 --- a/ObjectiveGit/GTFilter.m +++ b/ObjectiveGit/GTFilter.m @@ -42,7 +42,12 @@ + (void)initialize { GTFiltersGitFilterToRegisteredFilters = [[NSMutableDictionary alloc] init]; } -- (id)initWithName:(NSString *)name attributes:(NSString *)attributes applyBlock:(NSData * (^)(void **payload, NSData *from, GTFilterSource *source, BOOL *applied))applyBlock { +- (instancetype)init { + NSAssert(NO, @"Call to an unavailable initializer."); + return nil; +} + +- (instancetype)initWithName:(NSString *)name attributes:(NSString *)attributes applyBlock:(NSData * (^)(void **payload, NSData *from, GTFilterSource *source, BOOL *applied))applyBlock { NSParameterAssert(name != nil); NSParameterAssert(applyBlock != NULL); @@ -91,7 +96,9 @@ static void GTFilterShutdown(git_filter *filter) { static int GTFilterCheck(git_filter *filter, void **payload, const git_filter_source *src, const char **attr_values) { GTFilter *self = GTFiltersGitFilterToRegisteredFilters[[NSValue valueWithPointer:filter]]; - BOOL accept = self.checkBlock(payload, [[GTFilterSource alloc] initWithGitFilterSource:src], attr_values); + GTFilterSource *source = [[GTFilterSource alloc] initWithGitFilterSource:src]; + NSCAssert(source != nil, @"Unexpected nil filter source"); + BOOL accept = self.checkBlock(payload, source, attr_values); return accept ? 0 : GIT_PASSTHROUGH; } diff --git a/ObjectiveGit/GTFilterList.h b/ObjectiveGit/GTFilterList.h index 0473d3f2e..6ddf3ca98 100644 --- a/ObjectiveGit/GTFilterList.h +++ b/ObjectiveGit/GTFilterList.h @@ -14,19 +14,25 @@ /// The options for loading a filter list. See libgit2 for more information. typedef NS_OPTIONS(NSInteger, GTFilterListOptions) { - GTFilterListOptionsDefault = GIT_FILTER_OPT_DEFAULT, - GTFilterListOptionsAllowUnsafe = GIT_FILTER_OPT_ALLOW_UNSAFE, + GTFilterListOptionsDefault = GIT_FILTER_DEFAULT, + GTFilterListOptionsAllowUnsafe = GIT_FILTER_ALLOW_UNSAFE, }; +NS_ASSUME_NONNULL_BEGIN + /// An opaque list of filters that apply to a given path. @interface GTFilterList : NSObject -/// Initializes the receiver to wrap the given `git_filter_list`. +- (instancetype)init NS_UNAVAILABLE; + +/// Initializes the receiver to wrap the given `git_filter_list`. Designated initializer. /// /// filterList - The filter list to wrap and take ownership of. This filter list /// will be automatically disposed when the receiver deallocates. /// Must not be NULL. -- (instancetype)initWithGitFilterList:(git_filter_list *)filterList; +/// +/// Returns an initialized filter list, or nil if an error occurred. +- (instancetype _Nullable)initWithGitFilterList:(git_filter_list *)filterList NS_DESIGNATED_INITIALIZER; /// Returns the underlying `git_filter_list`. - (git_filter_list *)git_filter_list __attribute__((objc_returns_inner_pointer)); @@ -37,7 +43,7 @@ typedef NS_OPTIONS(NSInteger, GTFilterListOptions) { /// error - If not NULL, set to any error that occurs. /// /// Returns the filtered data, or nil if an error occurs. -- (NSData *)applyToData:(NSData *)inputData error:(NSError **)error; +- (NSData * _Nullable)applyToData:(NSData *)inputData error:(NSError **)error; /// Attempts to apply the filter list to a file in the given repository. /// @@ -47,7 +53,7 @@ typedef NS_OPTIONS(NSInteger, GTFilterListOptions) { /// error - If not NULL, set to any error that occurs. /// /// Returns the filtered data, or nil if an error occurs. -- (NSData *)applyToPath:(NSString *)relativePath inRepository:(GTRepository *)repository error:(NSError **)error; +- (NSData * _Nullable)applyToPath:(NSString *)relativePath inRepository:(GTRepository *)repository error:(NSError **)error; /// Attempts to apply the filter list to a blob. /// @@ -55,6 +61,8 @@ typedef NS_OPTIONS(NSInteger, GTFilterListOptions) { /// error - If not NULL, set to any error that occurs. /// /// Returns the filtered data, or nil if an error occurs. -- (NSData *)applyToBlob:(GTBlob *)blob error:(NSError **)error; +- (NSData * _Nullable)applyToBlob:(GTBlob *)blob error:(NSError **)error; @end + +NS_ASSUME_NONNULL_END diff --git a/ObjectiveGit/GTFilterList.m b/ObjectiveGit/GTFilterList.m index ffa37669c..1780293a4 100644 --- a/ObjectiveGit/GTFilterList.m +++ b/ObjectiveGit/GTFilterList.m @@ -25,6 +25,11 @@ @implementation GTFilterList #pragma mark Lifecycle +- (instancetype)init { + NSAssert(NO, @"Call to an unavailable initializer."); + return nil; +} + - (instancetype)initWithGitFilterList:(git_filter_list *)filterList { NSParameterAssert(filterList != NULL); @@ -65,7 +70,11 @@ - (NSData *)applyToPath:(NSString *)relativePath inRepository:(GTRepository *)re NSParameterAssert(repository != nil); git_buf output = GIT_BUF_INIT_CONST(0, NULL); - int gitError = git_filter_list_apply_to_file(&output, self.git_filter_list, repository.git_repository, relativePath.UTF8String); + // fixme: This is a workaround for an issue where `git_filter_list_apply_to_file` + // will not resolve relative paths against the worktree. It should be reverted when + // libgit2 has been updated to resolve that. + NSString *absolutePath = relativePath.absolutePath ? relativePath : [repository.fileURL URLByAppendingPathComponent:relativePath].path; + int gitError = git_filter_list_apply_to_file(&output, self.git_filter_list, repository.git_repository, absolutePath.UTF8String); if (gitError != GIT_OK) { if (error != NULL) *error = [NSError git_errorFor:gitError description:@"Failed to apply filter list to %@", relativePath]; diff --git a/ObjectiveGit/GTFilterSource.h b/ObjectiveGit/GTFilterSource.h index c99cf4c66..e168846d0 100644 --- a/ObjectiveGit/GTFilterSource.h +++ b/ObjectiveGit/GTFilterSource.h @@ -22,6 +22,8 @@ typedef NS_ENUM(NSInteger, GTFilterSourceMode) { GTFilterSourceModeClean = GIT_FILTER_CLEAN, }; +NS_ASSUME_NONNULL_BEGIN + /// A source item for a filter. @interface GTFilterSource : NSObject @@ -33,16 +35,20 @@ typedef NS_ENUM(NSInteger, GTFilterSourceMode) { /// The OID of the source. Will be nil if the source doesn't exist in the object /// database. -@property (nonatomic, readonly, strong) GTOID *OID; +@property (nonatomic, readonly, strong) GTOID * _Nullable OID; /// The filter mode. @property (nonatomic, readonly, assign) GTFilterSourceMode mode; -/// Intializes the receiver with the given filter source. +- (instancetype)init NS_UNAVAILABLE; + +/// Intializes the receiver with the given filter source. Designated initializer. /// /// source - The filter source. Cannot be NULL. /// /// Returns the initialized object. -- (id)initWithGitFilterSource:(const git_filter_source *)source; +- (instancetype _Nullable)initWithGitFilterSource:(const git_filter_source *)source NS_DESIGNATED_INITIALIZER; @end + +NS_ASSUME_NONNULL_END diff --git a/ObjectiveGit/GTFilterSource.m b/ObjectiveGit/GTFilterSource.m index 2dfd0b4ed..65878319f 100644 --- a/ObjectiveGit/GTFilterSource.m +++ b/ObjectiveGit/GTFilterSource.m @@ -16,16 +16,24 @@ @implementation GTFilterSource #pragma mark Lifecycle -- (id)initWithGitFilterSource:(const git_filter_source *)source { +- (instancetype)init { + NSAssert(NO, @"Call to an unavailable initializer."); + return nil; +} + +- (instancetype)initWithGitFilterSource:(const git_filter_source *)source { NSParameterAssert(source != NULL); self = [super init]; if (self == nil) return nil; - const char *path = git_repository_workdir(git_filter_source_repo(source)); - _repositoryURL = [NSURL fileURLWithPath:@(path)]; - - _path = @(git_filter_source_path(source)); + NSString *path = @(git_repository_workdir(git_filter_source_repo(source))); + NSAssert(path, @"workdir was nil"); + _repositoryURL = [NSURL fileURLWithPath:path]; + + path = @(git_filter_source_path(source)); + NSAssert(path, @"path was nil"); + _path = path; const git_oid *gitOid = git_filter_source_id(source); if (gitOid != NULL) _OID = [[GTOID alloc] initWithGitOid:gitOid]; diff --git a/ObjectiveGit/GTIndex.h b/ObjectiveGit/GTIndex.h index 1ba255c36..d0df6e4ec 100644 --- a/ObjectiveGit/GTIndex.h +++ b/ObjectiveGit/GTIndex.h @@ -34,20 +34,22 @@ @class GTRepository; @class GTTree; +NS_ASSUME_NONNULL_BEGIN + @interface GTIndex : NSObject /// The repository in which the index resides. This may be nil if the index was /// created with -initWithFileURL:error:. -@property (nonatomic, readonly, strong) GTRepository *repository; +@property (nonatomic, readonly, strong) GTRepository * _Nullable repository; -/// The file URL for the index if it exists on disk. -@property (nonatomic, readonly, copy) NSURL *fileURL; +/// The file URL for the index if it exists on disk; nil otherwise. +@property (nonatomic, readonly, copy) NSURL * _Nullable fileURL; /// The number of entries in the index. @property (nonatomic, readonly) NSUInteger entryCount; /// The GTIndexEntries in the index. -@property (nonatomic, readonly, copy) NSArray *entries; +@property (nonatomic, readonly, copy) NSArray *entries; /// Whether the index contains conflicted files. @property (nonatomic, readonly) BOOL hasConflicts; @@ -58,7 +60,7 @@ /// error - If not NULL, set to any error that occurs. /// /// Returns the newly created index, or nil if an error occurred. -+ (instancetype)inMemoryIndexWithRepository:(GTRepository *)repository error:(NSError **)error; ++ (instancetype _Nullable)inMemoryIndexWithRepository:(GTRepository *)repository error:(NSError **)error; /// Loads the index at the given file URL. /// @@ -67,16 +69,18 @@ /// error - If not NULL, set to any error that occurs. /// /// Returns the loaded index, or nil if an error occurred. -+ (instancetype)indexWithFileURL:(NSURL *)fileURL repository:(GTRepository *)repository error:(NSError **)error; ++ (instancetype _Nullable)indexWithFileURL:(NSURL *)fileURL repository:(GTRepository *)repository error:(NSError **)error; + +- (instancetype)init NS_UNAVAILABLE; -/// Initializes the receiver with the given libgit2 index. +/// Initializes the receiver with the given libgit2 index. Designated initializer. /// /// index - The libgit2 index from which the index should be created. Cannot /// be NULL. /// repository - The repository in which the index resides. Cannot be nil. /// /// Returns the initialized index. -- (instancetype)initWithGitIndex:(git_index *)index repository:(GTRepository *)repository; +- (instancetype)initWithGitIndex:(git_index *)index repository:(GTRepository *)repository NS_DESIGNATED_INITIALIZER; /// The underlying `git_index` object. - (git_index *)git_index __attribute__((objc_returns_inner_pointer)); @@ -101,24 +105,24 @@ /// index - The index of the entry to get. Must be within 0 and self.entryCount. /// /// Returns a new GTIndexEntry, or nil if an error occurred. -- (GTIndexEntry *)entryAtIndex:(NSUInteger)index; +- (GTIndexEntry * _Nullable)entryAtIndex:(NSUInteger)index; -/// Get the entry with the given name. -- (GTIndexEntry *)entryWithName:(NSString *)name; +/// Get the entry with the given path, or nil if an error occurred. +- (GTIndexEntry * _Nullable)entryWithPath:(NSString *)path; /// Get the entry with the given name. /// -/// name - The name of the entry to get. Cannot be nil. +/// path - The path of the entry to get. Cannot be nil. /// error - The error if one occurred. /// /// Returns a new GTIndexEntry, or nil if an error occurred. -- (GTIndexEntry *)entryWithName:(NSString *)name error:(NSError **)error; +- (GTIndexEntry * _Nullable)entryWithPath:(NSString *)path error:(NSError **)error; /// Add an entry to the index. /// /// Note that this *cannot* add submodules. See -[GTSubmodule addToIndex:]. /// -/// entry - The entry to add. +/// entry - The entry to add. Must not be nil. /// error - The error if one occurred. /// /// Returns YES if successful, NO otherwise. @@ -135,6 +139,14 @@ /// Returns YES if successful, NO otherwise. - (BOOL)addFile:(NSString *)file error:(NSError **)error; +/// Add an entry (with the provided data and name) to the index. +/// Will fail if the receiver's repository is nil. +/// +/// data - The content of the entry to add. Cannot be nil. +/// path - The path of the entry to add. Cannot be nil. +/// error - The error if one occurred. +- (BOOL)addData:(NSData *)data withPath:(NSString *)path error:(NSError **)error; + /// Reads the contents of the given tree into the index. /// /// tree - The tree to add to the index. This must not be nil. @@ -143,6 +155,13 @@ /// Returns whether reading the tree was successful. - (BOOL)addContentsOfTree:(GTTree *)tree error:(NSError **)error; +/// Add all the content of the working directory to the index. Like `git add -A` +/// +/// error - If not NULL, set to any error that occurs. +/// +/// Returns whether the operation was successful +- (BOOL)addAll:(NSError **)error; + /// Remove an entry (by relative path) from the index. /// Will fail if the receiver's repository is nil. /// @@ -167,7 +186,7 @@ /// error - The error if one occurred. /// /// Returns a new GTTree, or nil if an error occurred. -- (GTTree *)writeTree:(NSError **)error; +- (GTTree * _Nullable)writeTree:(NSError **)error; /// Write the index to the given repository as a tree. /// Will fail if the receiver's index has conflicts. @@ -176,7 +195,7 @@ /// error - The error if one occurred. /// /// Returns a new GTTree or nil if an error occurred. -- (GTTree *)writeTreeToRepository:(GTRepository *)repository error:(NSError **)error; +- (GTTree * _Nullable)writeTreeToRepository:(GTRepository *)repository error:(NSError **)error; /// Enumerate through any conflicts in the index, running the provided block each /// time. @@ -197,15 +216,24 @@ /// /// pathspecs - An `NSString` array of path patterns. (E.g: *.c) /// If nil is passed in, all index entries will be updated. -/// block - A block run each time a pathspec is matched; before the index is updated. -/// The `matchedPathspec` parameter is a string indicating what the pathspec (from `pathspecs`) matched. -/// If you pass in NULL in to the `pathspecs` parameter this parameter will be empty. -/// The `path` parameter is a repository relative path to the file about to be updated. +/// block - A block run each time a pathspec is matched; before the index is +/// updated. The `matchedPathspec` parameter is a string indicating +/// what the pathspec (from `pathspecs`) matched. If you pass in NULL +/// in to the `pathspecs` parameter this parameter will be empty. +/// The `path` parameter is a repository relative path to the file +/// about to be updated. /// The `stop` parameter can be set to `YES` to abort the operation. /// Return `YES` to update the given path, or `NO` to skip it. May be nil. /// error - When something goes wrong, this parameter is set. Optional. /// /// Returns `YES` in the event that everything has gone smoothly. Otherwise, `NO`. -- (BOOL)updatePathspecs:(NSArray *)pathspecs error:(NSError **)error passingTest:(BOOL (^)(NSString *matchedPathspec, NSString *path, BOOL *stop))block; +- (BOOL)updatePathspecs:(NSArray * _Nullable)pathspecs error:(NSError **)error passingTest:(BOOL (^ _Nullable)(NSString *matchedPathspec, NSString *path, BOOL *stop))block; + +#pragma mark Deprecations +- (GTIndexEntry * _Nullable)entryWithName:(NSString *)name __deprecated_msg("use entryWithPath: instead."); +- (GTIndexEntry * _Nullable)entryWithName:(NSString *)name error:(NSError **)error __deprecated_msg("use entryWithPath:error: instead."); + @end + +NS_ASSUME_NONNULL_END diff --git a/ObjectiveGit/GTIndex.m b/ObjectiveGit/GTIndex.m index 940980f14..8ee64fde6 100644 --- a/ObjectiveGit/GTIndex.m +++ b/ObjectiveGit/GTIndex.m @@ -36,6 +36,7 @@ #import "GTRepository+Private.h" #import "GTRepository.h" #import "GTTree.h" +#import "GTBlob.h" #import "NSArray+StringArray.h" #import "NSError+Git.h" @@ -76,6 +77,7 @@ - (void)dealloc { + (instancetype)inMemoryIndexWithRepository:(GTRepository *)repository error:(NSError **)error { git_index *index = NULL; + int status = git_index_new(&index); if (status != GIT_OK) { if (error != NULL) *error = [NSError git_errorFor:status description:@"Failed to initialize in-memory index"]; @@ -85,6 +87,11 @@ + (instancetype)inMemoryIndexWithRepository:(GTRepository *)repository error:(NS return [[self alloc] initWithGitIndex:index repository:repository]; } +- (instancetype)init { + NSAssert(NO, @"Call to an unavailable initializer."); + return nil; +} + + (instancetype)indexWithFileURL:(NSURL *)fileURL repository:(GTRepository *)repository error:(NSError **)error { NSParameterAssert(fileURL != nil); NSParameterAssert(fileURL.isFileURL); @@ -141,18 +148,18 @@ - (GTIndexEntry *)entryAtIndex:(NSUInteger)index { const git_index_entry *entry = git_index_get_byindex(self.git_index, (unsigned int)index); if (entry == NULL) return nil; - return [[GTIndexEntry alloc] initWithGitIndexEntry:entry]; + return [[GTIndexEntry alloc] initWithGitIndexEntry:entry index:self error:NULL]; } -- (GTIndexEntry *)entryWithName:(NSString *)name { - return [self entryWithName:name error:NULL]; +- (GTIndexEntry *)entryWithPath:(NSString *)path { + return [self entryWithPath:path error:NULL]; } -- (GTIndexEntry *)entryWithName:(NSString *)name error:(NSError **)error { +- (GTIndexEntry *)entryWithPath:(NSString *)path error:(NSError **)error { size_t pos = 0; - int gitError = git_index_find(&pos, self.git_index, name.UTF8String); + int gitError = git_index_find(&pos, self.git_index, path.UTF8String); if (gitError != GIT_OK) { - if (error != NULL) *error = [NSError git_errorFor:gitError description:@"%@ not found in index", name]; + if (error != NULL) *error = [NSError git_errorFor:gitError description:@"%@ not found in index", path]; return NULL; } return [self entryAtIndex:pos]; @@ -180,6 +187,25 @@ - (BOOL)addFile:(NSString *)file error:(NSError **)error { return YES; } +- (BOOL)addData:(NSData *)data withPath:(NSString *)path error:(NSError **)error { + NSParameterAssert(data != nil); + NSParameterAssert(path != nil); + + git_index_entry entry; + memset(&entry, 0x0, sizeof(git_index_entry)); + entry.path = [path cStringUsingEncoding:NSUTF8StringEncoding]; + entry.mode = GIT_FILEMODE_BLOB; + + int status = git_index_add_frombuffer(self.git_index, &entry, [data bytes], [data length]); + + if (status != GIT_OK) { + if (error != NULL) *error = [NSError git_errorFor:status description:@"Failed to add data with name %@ into index.", path]; + return NO; + } + + return YES; +} + - (BOOL)addContentsOfTree:(GTTree *)tree error:(NSError **)error { NSParameterAssert(tree != nil); @@ -192,6 +218,16 @@ - (BOOL)addContentsOfTree:(GTTree *)tree error:(NSError **)error { return YES; } +- (BOOL)addAll:(NSError **)error { + int status = git_index_add_all(self.git_index, nil, GIT_INDEX_ADD_CHECK_PATHSPEC, nil, nil); + if (status != GIT_OK) { + if (error != NULL) *error = [NSError git_errorFor:status description:@"Failed to add all the contents of the working tree to the index"]; + return NO; + } + + return YES; +} + - (BOOL)removeFile:(NSString *)file error:(NSError **)error { NSString *unicodeString = [self composedUnicodeStringWithString:file]; @@ -242,7 +278,9 @@ - (GTTree *)writeTreeToRepository:(GTRepository *)repository error:(NSError **)e - (NSArray *)entries { NSMutableArray *entries = [NSMutableArray arrayWithCapacity:self.entryCount]; for (NSUInteger i = 0; i < self.entryCount; i++) { - [entries addObject:[self entryAtIndex:i]]; + GTIndexEntry *entry = [self entryAtIndex:i]; + if (entry) + [entries addObject:entry]; } return entries; @@ -359,4 +397,13 @@ - (NSString *)composedUnicodeStringWithString:(NSString *)string { return (shouldPrecompose ? [string precomposedStringWithCanonicalMapping] : [string decomposedStringWithCanonicalMapping]); } +#pragma mark Deprecations + +- (GTIndexEntry *)entryWithName:(NSString *)name { + return [self entryWithPath:name]; +} + +- (GTIndexEntry *)entryWithName:(NSString *)name error:(NSError **)error { + return [self entryWithPath:name error:error]; +} @end diff --git a/ObjectiveGit/GTIndexEntry.h b/ObjectiveGit/GTIndexEntry.h index b60713edf..16b89a588 100644 --- a/ObjectiveGit/GTIndexEntry.h +++ b/ObjectiveGit/GTIndexEntry.h @@ -29,6 +29,9 @@ #import #include "git2/index.h" +#import "GTObject.h" + +@class GTIndex; typedef NS_ENUM(NSInteger, GTIndexEntryStatus) { GTIndexEntryStatusUpdated = 0, @@ -38,8 +41,28 @@ typedef NS_ENUM(NSInteger, GTIndexEntryStatus) { GTIndexEntryStatusUpToDate, }; +NS_ASSUME_NONNULL_BEGIN + @interface GTIndexEntry : NSObject +- (instancetype)init NS_UNAVAILABLE; + +/// Initializes the receiver with the given libgit2 index entry. +/// +/// entry - The libgit2 index entry. Cannot be NULL. +/// index - The index this entry belongs to. +/// error - will be filled if an error occurs +/// +/// Returns the initialized object. +- (instancetype)initWithGitIndexEntry:(const git_index_entry *)entry index:(GTIndex * _Nullable)index error:(NSError **)error NS_DESIGNATED_INITIALIZER; +- (instancetype)initWithGitIndexEntry:(const git_index_entry *)entry; + +/// The underlying `git_index_entry` object. +- (const git_index_entry *)git_index_entry __attribute__((objc_returns_inner_pointer)); + +/// The entry's index. This may be nil if nil is passed in to -initWithGitIndexEntry: +@property (nonatomic, strong, readonly) GTIndex * _Nullable index; + /// The repository-relative path for the entry. @property (nonatomic, readonly, copy) NSString *path; @@ -49,14 +72,23 @@ typedef NS_ENUM(NSInteger, GTIndexEntryStatus) { /// What is the entry's status? @property (nonatomic, readonly) GTIndexEntryStatus status; -/// Initializes the receiver with the given libgit2 index entry. +/// The OID of the entry. +@property (nonatomic, strong, readonly) GTOID *OID; + +/// Convert the entry into an GTObject /// -/// entry - The libgit2 index entry. Cannot be NULL. +/// error - will be filled if an error occurs /// -/// Returns the initialized object. -- (id)initWithGitIndexEntry:(const git_index_entry *)entry; +/// Returns this entry as a GTObject or nil if an error occurred. +- (nullable GTObject *)GTObject:(NSError **)error; -/// The underlying `git_index_entry` object. -- (const git_index_entry *)git_index_entry __attribute__((objc_returns_inner_pointer)); +@end + +@interface GTObject (GTIndexEntry) + ++ (instancetype _Nullable)objectWithIndexEntry:(GTIndexEntry *)indexEntry error:(NSError **)error; +- (instancetype _Nullable)initWithIndexEntry:(GTIndexEntry *)indexEntry error:(NSError **)error; @end + +NS_ASSUME_NONNULL_END diff --git a/ObjectiveGit/GTIndexEntry.m b/ObjectiveGit/GTIndexEntry.m index 0360755da..c687d0060 100644 --- a/ObjectiveGit/GTIndexEntry.m +++ b/ObjectiveGit/GTIndexEntry.m @@ -30,6 +30,11 @@ #import "GTIndexEntry.h" #import "NSError+Git.h" #import "NSString+Git.h" +#import "GTOID.h" +#import "GTRepository.h" +#import "GTIndex.h" + +#import "git2.h" @interface GTIndexEntry () @property (nonatomic, assign, readonly) const git_index_entry *git_index_entry; @@ -40,26 +45,38 @@ @implementation GTIndexEntry #pragma mark NSObject - (NSString *)description { - return [NSString stringWithFormat:@"<%@: %p> path: %@", self.class, self, self.path]; + return [NSString stringWithFormat:@"<%@: %p> path: %@", self.class, self, self.path]; } #pragma mark Lifecycle -- (id)initWithGitIndexEntry:(const git_index_entry *)entry { +- (instancetype)init { + NSAssert(NO, @"Call to an unavailable initializer."); + return nil; +} + +- (instancetype)initWithGitIndexEntry:(const git_index_entry *)entry index:(GTIndex *)index error:(NSError **)error { NSParameterAssert(entry != NULL); self = [super init]; if (self == nil) return nil; _git_index_entry = entry; - + _index = index; + return self; } +- (instancetype)initWithGitIndexEntry:(const git_index_entry *)entry { + return [self initWithGitIndexEntry:entry index:nil error:NULL]; +} + #pragma mark Properties - (NSString *)path { - return @(self.git_index_entry->path); + NSString *path = @(self.git_index_entry->path); + NSAssert(path, @"path is nil"); + return path; } - (int)flags { @@ -71,19 +88,56 @@ - (BOOL)isStaged { } - (GTIndexEntryStatus)status { - if ((self.flags & GIT_IDXENTRY_UPDATE) != 0) { + if ((self.flags & (GIT_IDXENTRY_UPDATE << 16)) != 0) { return GTIndexEntryStatusUpdated; - } else if ((self.flags & GIT_IDXENTRY_UPTODATE) != 0) { + } else if ((self.flags & (GIT_IDXENTRY_UPTODATE << 16)) != 0) { return GTIndexEntryStatusUpToDate; - } else if ((self.flags & GIT_IDXENTRY_CONFLICTED) != 0) { + } else if ((self.flags & (GIT_IDXENTRY_CONFLICTED << 16)) != 0) { return GTIndexEntryStatusConflicted; - } else if ((self.flags & GIT_IDXENTRY_ADDED) != 0) { + } else if ((self.flags & (GIT_IDXENTRY_ADDED << 16)) != 0) { return GTIndexEntryStatusAdded; - } else if ((self.flags & GIT_IDXENTRY_REMOVE) != 0) { + } else if ((self.flags & (GIT_IDXENTRY_REMOVE << 16)) != 0) { return GTIndexEntryStatusRemoved; } - + return GTIndexEntryStatusUpToDate; } +- (GTOID *)OID { + return [GTOID oidWithGitOid:&self.git_index_entry->id]; +} + +#pragma mark API + +- (GTRepository *)repository { + return self.index.repository; +} + +- (GTObject *)GTObject:(NSError **)error { + return [GTObject objectWithIndexEntry:self error:error]; +} + +@end + +@implementation GTObject (GTIndexEntry) + ++ (instancetype)objectWithIndexEntry:(GTIndexEntry *)indexEntry error:(NSError **)error { + return [[self alloc] initWithIndexEntry:indexEntry error:error]; +} + +- (instancetype)initWithIndexEntry:(GTIndexEntry *)indexEntry error:(NSError **)error { + git_object *obj; + int gitError = git_object_lookup(&obj, indexEntry.repository.git_repository, indexEntry.OID.git_oid, (git_object_t)GTObjectTypeAny); + + if (gitError < GIT_OK) { + if (error != NULL) { + *error = [NSError git_errorFor:gitError description:@"Failed to get object for index entry."]; + } + + return nil; + } + + return [self initWithObj:obj inRepository:indexEntry.repository]; +} + @end diff --git a/ObjectiveGit/GTNote.h b/ObjectiveGit/GTNote.h new file mode 100644 index 000000000..008b78a5a --- /dev/null +++ b/ObjectiveGit/GTNote.h @@ -0,0 +1,91 @@ +// +// GTNote.h +// ObjectiveGitFramework +// +// Created by Slava Karpenko on 5/16/2016. +// +// The MIT License +// +// Copyright (c) 2016 Wildbit LLC +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. +// + +#import +#import "git2/oid.h" + +@class GTSignature; +@class GTRepository; +@class GTOID; +@class GTObject; + +NS_ASSUME_NONNULL_BEGIN + +@interface GTNote : NSObject {} + +/// The author of the note. +@property (nonatomic, readonly, strong) GTSignature * _Nullable author; + +/// The committer of the note. +@property (nonatomic, readonly, strong) GTSignature * _Nullable committer; + +/// Content of the note. +@property (nonatomic, readonly, strong) NSString *note; + +@property (nonatomic, readonly, strong) GTOID *targetOID; + +/// The underlying `git_note` object. +- (git_note *)git_note __attribute__((objc_returns_inner_pointer)); + +/// Create a note with target OID in the given repository. +/// +/// oid - OID of the target to attach to +/// repository - Repository containing the target OID refers to +/// referenceName - Name for the notes reference in the repo, or nil for default ("refs/notes/commits") +/// error - Will be filled with a NSError object in case of error. +/// May be NULL. +/// +/// Returns initialized GTNote instance or nil on failure (error will be populated, if passed). +- (instancetype _Nullable)initWithTargetOID:(GTOID *)oid repository:(GTRepository *)repository referenceName:(NSString * _Nullable)referenceName error:(NSError **)error; + +/// Create a note with target libgit2 oid in the given repository. +/// +/// oid - git_oid of the target to attach to +/// repository - Repository containing the target OID refers to +/// referenceName - Name for the notes reference in the repo, or NULL for default ("refs/notes/commits") +/// +/// Returns initialized GTNote instance or nil on failure. +- (instancetype _Nullable)initWithTargetGitOID:(git_oid *)oid repository:(git_repository *)repository referenceName:(const char * _Nullable)referenceName error:(NSError **)error NS_DESIGNATED_INITIALIZER; + +- (instancetype)init NS_UNAVAILABLE; + + +/// Return a default reference name (that is used if you pass nil to any referenceName parameter) +/// +/// repository - Repository for which to get the default notes reference name. +/// error - Will be filled with a git error code in case of error. +/// May be NULL. +/// +/// Returns default reference name (usually "refs/notes/commits"). ++ (NSString * _Nullable)defaultReferenceNameForRepository:(GTRepository *)repository error:(NSError **)error; + +@end + +NS_ASSUME_NONNULL_END + diff --git a/ObjectiveGit/GTNote.m b/ObjectiveGit/GTNote.m new file mode 100644 index 000000000..b87039de1 --- /dev/null +++ b/ObjectiveGit/GTNote.m @@ -0,0 +1,105 @@ +// +// GTNote.m +// ObjectiveGitFramework +// +// Created by Slava Karpenko on 16.05.16. +// Copyright © 2016 Wildbit LLC. All rights reserved. +// + +#import "GTNote.h" +#import "NSError+Git.h" +#import "GTSignature.h" +#import "GTReference.h" +#import "GTRepository.h" +#import "NSString+Git.h" +#import "GTOID.h" + +#import "git2/errors.h" +#import "git2/notes.h" + +@interface GTNote () +{ + git_note *_note; +} + +@end +@implementation GTNote + +- (NSString *)description { + return [NSString stringWithFormat:@"<%@: %p>", NSStringFromClass([self class]), self]; +} + +#pragma mark API + +- (void)dealloc { + if (_note != NULL) { + git_note_free(_note); + } +} + +- (git_note *)git_note { + return _note; +} + +- (NSString *)note { + NSString *message = @(git_note_message(self.git_note)); + NSAssert(message, @"message is nil"); + return message; +} + +- (GTSignature *)author { + return [[GTSignature alloc] initWithGitSignature:git_note_author(self.git_note)]; +} + +- (GTSignature *)committer { + return [[GTSignature alloc] initWithGitSignature:git_note_committer(self.git_note)]; +} + +- (GTOID *)targetOID { + return [GTOID oidWithGitOid:git_note_id(self.git_note)]; +} + +- (instancetype)initWithTargetOID:(GTOID *)oid repository:(GTRepository *)repository referenceName:(NSString *)referenceName error:(NSError **)error { + return [self initWithTargetGitOID:(git_oid *)oid.git_oid repository:repository.git_repository referenceName:referenceName.UTF8String error:error]; +} + +- (instancetype)initWithTargetGitOID:(git_oid *)oid repository:(git_repository *)repository referenceName:(const char *)referenceName error:(NSError **)error { + self = [super init]; + if (self == nil) return nil; + + int gitErr = git_note_read(&_note, repository, referenceName, oid); + + if (gitErr != GIT_OK) { + if (error != NULL) *error = [NSError git_errorFor:gitErr description:@"Unable to read note"]; + return nil; + } + + return self; +} + +- (instancetype)init { + NSAssert(NO, @"Call to an unavailable initializer."); + return nil; +} + ++ (NSString *)defaultReferenceNameForRepository:(GTRepository *)repository error:(NSError **)error { + NSString *noteRef = nil; + + git_buf default_ref_name = { 0 }; + int gitErr = git_note_default_ref(&default_ref_name, repository.git_repository); + if (gitErr != GIT_OK) { + if (error != NULL) *error = [NSError git_errorFor:gitErr description:@"Unable to get default git notes reference name"]; + return nil; + } + + if (default_ref_name.ptr != NULL) { + noteRef = @(default_ref_name.ptr); + } else { + if (error != NULL) *error = [NSError git_errorFor:GIT_ERROR description:@"Unable to get default git notes reference name"]; + } + + git_buf_dispose(&default_ref_name); + + return noteRef; +} +@end diff --git a/ObjectiveGit/GTOID.h b/ObjectiveGit/GTOID.h index ac402f2c2..ab0590ee7 100644 --- a/ObjectiveGit/GTOID.h +++ b/ObjectiveGit/GTOID.h @@ -10,6 +10,8 @@ #import "git2/oid.h" #import "GTObject.h" +NS_ASSUME_NONNULL_BEGIN + /// Represents an object ID. @interface GTOID : NSObject @@ -20,19 +22,21 @@ /// inserted into the ODB yet. @property (nonatomic, readonly, assign, getter = isZero) BOOL zero; -/// Initializes the receiver with the given git_oid. +- (instancetype)init NS_UNAVAILABLE; + +/// Initializes the receiver with the given git_oid. Designated initializer. /// /// git_oid - The underlying git_oid. Cannot be NULL. /// /// Returns the initialized receiver. -- (id)initWithGitOid:(const git_oid *)git_oid; +- (instancetype)initWithGitOid:(const git_oid *)git_oid NS_DESIGNATED_INITIALIZER; /// Initializes the receiver by converting the given SHA to an OID. /// /// SHA - The to convert to an OID. Cannot be nil. /// /// Returns the initialized receiver. -- (id)initWithSHA:(NSString *)SHA; +- (instancetype _Nullable)initWithSHA:(NSString *)SHA; /// Initializes the receiver by converting the given SHA to an OID /// optionally returning a NSError instance on failure. @@ -41,14 +45,14 @@ /// error - Will be filled with an error object in if the SHA cannot be parsed /// /// Returns the initialized receiver or nil if an error occured. -- (id)initWithSHA:(NSString *)SHA error:(NSError **)error; +- (instancetype _Nullable)initWithSHA:(NSString *)SHA error:(NSError **)error; /// Initializes the receiver by converting the given SHA C string to an OID. /// /// string - The C string to convert. Cannot be NULL. /// /// Returns the initialized receiver. -- (id)initWithSHACString:(const char *)string; +- (instancetype _Nullable)initWithSHACString:(const char *)string; /// Initializes the receiver by converting the given SHA C string to an OID /// optionally returning a NSError instance on failure. @@ -57,16 +61,16 @@ /// error - Will be filled with an error object in if the SHA cannot be parsed /// /// Returns the initialized receiver. -- (id)initWithSHACString:(const char *)string error:(NSError **)error; +- (instancetype _Nullable)initWithSHACString:(const char *)string error:(NSError **)error NS_DESIGNATED_INITIALIZER; /// Creates a new instance with the given git_oid using initWithGitOid: + (instancetype)oidWithGitOid:(const git_oid *)git_oid; /// Creates a new instance from the given SHA string using initWithSHAString: -+ (instancetype)oidWithSHA:(NSString *)SHA; ++ (instancetype _Nullable)oidWithSHA:(NSString *)SHA; /// Creates a new instance from the given SHA C string using initWithSHACString: -+ (instancetype)oidWithSHACString:(const char *)SHA; ++ (instancetype _Nullable)oidWithSHACString:(const char *)SHA; /// Returns the underlying git_oid struct. - (const git_oid *)git_oid __attribute__((objc_returns_inner_pointer)); @@ -81,6 +85,8 @@ /// type - The type of the git object. /// /// Returns a new OID, or nil if an error occurred. -+ (instancetype)OIDByHashingData:(NSData *)data type:(GTObjectType)type error:(NSError **)error; ++ (instancetype _Nullable)OIDByHashingData:(NSData *)data type:(GTObjectType)type error:(NSError **)error; @end + +NS_ASSUME_NONNULL_END diff --git a/ObjectiveGit/GTOID.m b/ObjectiveGit/GTOID.m index a906c7065..8010c2885 100644 --- a/ObjectiveGit/GTOID.m +++ b/ObjectiveGit/GTOID.m @@ -27,19 +27,22 @@ - (const git_oid *)git_oid { } - (NSString *)SHA { - char *SHA = malloc(GIT_OID_HEXSZ); - if (SHA == NULL) return nil; - - git_oid_fmt(SHA, self.git_oid); - - NSString *str = [[NSString alloc] initWithBytesNoCopy:SHA length:GIT_OID_HEXSZ encoding:NSUTF8StringEncoding freeWhenDone:YES]; - if (str == nil) free(SHA); + char *SHA = git_oid_tostr_s(self.git_oid); + NSString *str = [[NSString alloc] initWithBytes:SHA + length:GIT_OID_HEXSZ + encoding:NSUTF8StringEncoding]; + NSAssert(str != nil, @"Failed to create SHA string"); return str; } #pragma mark Lifecycle -- (id)initWithGitOid:(const git_oid *)oid { +- (instancetype)init { + NSAssert(NO, @"Call to an unavailable initializer."); + return nil; +} + +- (instancetype)initWithGitOid:(const git_oid *)oid { NSParameterAssert(oid != NULL); self = [super init]; @@ -50,16 +53,18 @@ - (id)initWithGitOid:(const git_oid *)oid { return self; } -- (id)initWithSHA:(NSString *)SHA error:(NSError **)error { +- (instancetype)initWithSHA:(NSString *)SHA error:(NSError **)error { NSParameterAssert(SHA != nil); - return [self initWithSHACString:SHA.UTF8String error:error]; + const char *SHACString = SHA.UTF8String; + NSAssert(SHACString, @"Unexpected nil SHA"); + return [self initWithSHACString:SHACString error:error]; } -- (id)initWithSHA:(NSString *)SHA { +- (instancetype)initWithSHA:(NSString *)SHA { return [self initWithSHA:SHA error:NULL]; } -- (id)initWithSHACString:(const char *)string error:(NSError **)error { +- (instancetype)initWithSHACString:(const char *)string error:(NSError **)error { NSParameterAssert(string != NULL); self = [super init]; @@ -76,7 +81,7 @@ - (id)initWithSHACString:(const char *)string error:(NSError **)error { return self; } -- (id)initWithSHACString:(const char *)string { +- (instancetype)initWithSHACString:(const char *)string { return [self initWithSHACString:string error:NULL]; } @@ -128,7 +133,7 @@ + (instancetype)OIDByHashingData:(NSData *)data type:(GTObjectType)type error:(N NSParameterAssert(data != nil); git_oid oid; - int gitError = git_odb_hash(&oid, data.bytes, data.length, (git_otype)type); + int gitError = git_odb_hash(&oid, data.bytes, data.length, (git_object_t)type); if (gitError != GIT_OK) { if (error != NULL) *error = [NSError git_errorFor:gitError description:@"Failed to hash"]; return nil; diff --git a/ObjectiveGit/GTObject.h b/ObjectiveGit/GTObject.h index aa07d70e6..a74ed418c 100644 --- a/ObjectiveGit/GTObject.h +++ b/ObjectiveGit/GTObject.h @@ -31,22 +31,22 @@ #import "git2/types.h" typedef NS_ENUM(int, GTObjectType) { - GTObjectTypeAny = GIT_OBJ_ANY, /**< Object can be any of the following */ - GTObjectTypeBad = GIT_OBJ_BAD, /**< Object is invalid. */ - GTObjectTypeExt1 = GIT_OBJ__EXT1, /**< Reserved for future use. */ - GTObjectTypeCommit = GIT_OBJ_COMMIT, /**< A commit object. */ - GTObjectTypeTree = GIT_OBJ_TREE, /**< A tree (directory listing) object. */ - GTObjectTypeBlob = GIT_OBJ_BLOB, /**< A file revision object. */ - GTObjectTypeTag = GIT_OBJ_TAG, /**< An annotated tag object. */ - GTObjectTypeExt2 = GIT_OBJ__EXT2, /**< Reserved for future use. */ - GTObjectTypeOffsetDelta = GIT_OBJ_OFS_DELTA,/**< A delta, base is given by an offset. */ - GTObjectTypeRefDelta = GIT_OBJ_REF_DELTA, /**< A delta, base is given by object id. */ + GTObjectTypeAny = GIT_OBJECT_ANY, /**< Object can be any of the following */ + GTObjectTypeBad = GIT_OBJECT_INVALID, /**< Object is invalid. */ + GTObjectTypeCommit = GIT_OBJECT_COMMIT, /**< A commit object. */ + GTObjectTypeTree = GIT_OBJECT_TREE, /**< A tree (directory listing) object. */ + GTObjectTypeBlob = GIT_OBJECT_BLOB, /**< A file revision object. */ + GTObjectTypeTag = GIT_OBJECT_TAG, /**< An annotated tag object. */ + GTObjectTypeOffsetDelta = GIT_OBJECT_OFS_DELTA,/**< A delta, base is given by an offset. */ + GTObjectTypeRefDelta = GIT_OBJECT_REF_DELTA, /**< A delta, base is given by object id. */ }; @class GTRepository; @class GTOdbObject; @class GTOID; +NS_ASSUME_NONNULL_BEGIN + @interface GTObject : NSObject @property (nonatomic, readonly) NSString *type; @@ -55,9 +55,13 @@ typedef NS_ENUM(int, GTObjectType) { @property (nonatomic, readonly, strong) GTRepository *repository; @property (nonatomic, readonly) GTOID *OID; -/// Convenience initializers -- (id)initWithObj:(git_object *)theObject inRepository:(GTRepository *)theRepo; -+ (id)objectWithObj:(git_object *)theObject inRepository:(GTRepository *)theRepo; +- (instancetype)init NS_UNAVAILABLE; + +/// Designated initializer. +- (id _Nullable)initWithObj:(git_object *)theObject inRepository:(GTRepository *)theRepo NS_DESIGNATED_INITIALIZER; + +/// Class convenience initializer ++ (id _Nullable)objectWithObj:(git_object *)theObject inRepository:(GTRepository *)theRepo; /// The underlying `git_object`. - (git_object *)git_object __attribute__((objc_returns_inner_pointer)); @@ -67,7 +71,7 @@ typedef NS_ENUM(int, GTObjectType) { /// error(out) - will be filled if an error occurs /// /// returns a GTOdbObject or nil if an error occurred. -- (GTOdbObject *)odbObjectWithError:(NSError **)error; +- (GTOdbObject * _Nullable)odbObjectWithError:(NSError **)error; /// Recursively peel an object until an object of the specified type is met. /// @@ -78,6 +82,8 @@ typedef NS_ENUM(int, GTObjectType) { /// May be NULL. /// /// Returns the found object or nil on error. -- (id)objectByPeelingToType:(GTObjectType)type error:(NSError **)error; +- (id _Nullable)objectByPeelingToType:(GTObjectType)type error:(NSError **)error; @end + +NS_ASSUME_NONNULL_END diff --git a/ObjectiveGit/GTObject.m b/ObjectiveGit/GTObject.m index aa3eab5bc..503585092 100644 --- a/ObjectiveGit/GTObject.m +++ b/ObjectiveGit/GTObject.m @@ -70,6 +70,11 @@ - (BOOL)isEqual:(id)otherObject { #pragma mark API +- (instancetype)init { + NSAssert(NO, @"Call to an unavailable initializer."); + return nil; +} + - (id)initWithObj:(git_object *)object inRepository:(GTRepository *)repo { NSParameterAssert(object != NULL); NSParameterAssert(repo != nil); @@ -77,18 +82,18 @@ - (id)initWithObj:(git_object *)object inRepository:(GTRepository *)repo { NSAssert(object_repo == repo.git_repository, @"object %p doesn't belong to repo %@", object, repo); Class objectClass = nil; - git_otype t = git_object_type(object); + git_object_t t = git_object_type(object); switch (t) { - case GIT_OBJ_COMMIT: + case GIT_OBJECT_COMMIT: objectClass = [GTCommit class]; break; - case GIT_OBJ_TREE: + case GIT_OBJECT_TREE: objectClass = [GTTree class]; break; - case GIT_OBJ_BLOB: + case GIT_OBJECT_BLOB: objectClass = [GTBlob class]; break; - case GIT_OBJ_TAG: + case GIT_OBJECT_TAG: objectClass = [GTTag class]; break; default: @@ -96,7 +101,7 @@ - (id)initWithObj:(git_object *)object inRepository:(GTRepository *)repo { } if (!objectClass) { - NSLog(@"Unknown git_otype %s (%d)", git_object_type2string(t), (int)t); + NSLog(@"Unknown git_object_t %s (%d)", git_object_type2string(t), (int)t); return nil; } @@ -118,7 +123,9 @@ + (id)objectWithObj:(git_object *)theObject inRepository:(GTRepository *)theRepo } - (NSString *)type { - return [NSString stringWithUTF8String:git_object_type2string(git_object_type(self.git_object))]; + NSString *type = [NSString stringWithUTF8String:git_object_type2string(git_object_type(self.git_object))]; + NSAssert(type != nil, @"type was nil"); + return type; } - (GTOID *)OID { @@ -142,7 +149,7 @@ - (GTOdbObject *)odbObjectWithError:(NSError **)error { - (id)objectByPeelingToType:(GTObjectType)type error:(NSError **)error { git_object *peeled = NULL; - int gitError = git_object_peel(&peeled, self.git_object, (git_otype)type); + int gitError = git_object_peel(&peeled, self.git_object, (git_object_t)type); if (gitError != GIT_OK) { if (error != NULL) *error = [NSError git_errorFor:gitError description:@"Cannot peel object"]; return nil; diff --git a/ObjectiveGit/GTObjectDatabase.h b/ObjectiveGit/GTObjectDatabase.h index 7220df2da..c111d8b6a 100644 --- a/ObjectiveGit/GTObjectDatabase.h +++ b/ObjectiveGit/GTObjectDatabase.h @@ -27,24 +27,28 @@ @class GTOID; +NS_ASSUME_NONNULL_BEGIN + @interface GTObjectDatabase : NSObject @property (nonatomic, readonly, strong) GTRepository *repository; -/// Initializes the object database with the given repository. +- (instancetype)init NS_UNAVAILABLE; + +/// Initializes the object database with the given repository. Designated initializer. /// /// repo - The repository from which the object database should be created. /// Cannot be nil. /// error - The error if one occurred. /// /// Returns the initialized object. -- (id)initWithRepository:(GTRepository *)repo error:(NSError **)error; +- (instancetype _Nullable)initWithRepository:(GTRepository *)repo error:(NSError **)error NS_DESIGNATED_INITIALIZER; /// The underlying `git_odb` object. - (git_odb *)git_odb __attribute__((objc_returns_inner_pointer)); -- (GTOdbObject *)objectWithOID:(GTOID *)OID error:(NSError **)error; -- (GTOdbObject *)objectWithSHA:(NSString *)SHA error:(NSError **)error; +- (GTOdbObject * _Nullable)objectWithOID:(GTOID *)OID error:(NSError **)error; +- (GTOdbObject * _Nullable)objectWithSHA:(NSString *)SHA error:(NSError **)error; /// Writes the data into the object database. /// @@ -54,7 +58,7 @@ /// /// Returns the OID for the object which was written, or nil if an error /// occurred. -- (GTOID *)writeData:(NSData *)data type:(GTObjectType)type error:(NSError **)error; +- (GTOID * _Nullable)writeData:(NSData *)data type:(GTObjectType)type error:(NSError **)error; - (BOOL)containsObjectWithSHA:(NSString *)SHA error:(NSError **)error; @@ -66,3 +70,5 @@ - (BOOL)containsObjectWithOID:(GTOID *)oid; @end + +NS_ASSUME_NONNULL_END diff --git a/ObjectiveGit/GTObjectDatabase.m b/ObjectiveGit/GTObjectDatabase.m index 1da225624..99c431a48 100644 --- a/ObjectiveGit/GTObjectDatabase.m +++ b/ObjectiveGit/GTObjectDatabase.m @@ -56,7 +56,12 @@ - (void)dealloc { #pragma mark API -- (id)initWithRepository:(GTRepository *)repo error:(NSError **)error { +- (instancetype)init { + NSAssert(NO, @"Call to an unavailable initializer."); + return nil; +} + +- (instancetype)initWithRepository:(GTRepository *)repo error:(NSError **)error { NSParameterAssert(repo != nil); self = [super init]; @@ -97,7 +102,7 @@ - (GTOID *)writeData:(NSData *)data type:(GTObjectType)type error:(NSError **)er NSParameterAssert(data != nil); git_odb_stream *stream; - int gitError = git_odb_open_wstream(&stream, self.git_odb, data.length, (git_otype)type); + int gitError = git_odb_open_wstream(&stream, self.git_odb, data.length, (git_object_t)type); @onExit { if (stream != NULL) git_odb_stream_free(stream); }; diff --git a/ObjectiveGit/GTOdbObject.h b/ObjectiveGit/GTOdbObject.h index 4d9dc5df5..389bce721 100644 --- a/ObjectiveGit/GTOdbObject.h +++ b/ObjectiveGit/GTOdbObject.h @@ -6,32 +6,36 @@ // Copyright 2011 GitHub, Inc. All rights reserved. // - #import "GTObject.h" +NS_ASSUME_NONNULL_BEGIN @interface GTOdbObject : NSObject /// The repository in which the object resides. @property (nonatomic, readonly, strong) GTRepository *repository; -/// Initializes the object with the underlying libgit2 object and repository. +- (instancetype)init NS_UNAVAILABLE; + +/// Initializes the object with the underlying libgit2 object and repository. Designated initializer. /// /// object - The underlying libgit2 object. Cannot be NULL. /// repository - The repository in which the object resides. Cannot be nil. /// /// Returns the initialized object. -- (id)initWithOdbObj:(git_odb_object *)object repository:(GTRepository *)repository; +- (instancetype _Nullable)initWithOdbObj:(git_odb_object *)object repository:(GTRepository *)repository NS_DESIGNATED_INITIALIZER; /// The underlying `git_odb_object`. - (git_odb_object *)git_odb_object __attribute__((objc_returns_inner_pointer)); -- (NSString *)shaHash; +- (NSString * _Nullable)shaHash; - (GTObjectType)type; - (size_t)length; -- (NSData *)data; +- (NSData * _Nullable)data; /// The object ID of this object. -@property (nonatomic, readonly) GTOID *OID; +@property (nonatomic, readonly) GTOID * _Nullable OID; @end + +NS_ASSUME_NONNULL_END diff --git a/ObjectiveGit/GTOdbObject.m b/ObjectiveGit/GTOdbObject.m index 9bbb235f0..09c13b7ea 100644 --- a/ObjectiveGit/GTOdbObject.m +++ b/ObjectiveGit/GTOdbObject.m @@ -31,7 +31,12 @@ - (NSString *)description { #pragma mark API -- (id)initWithOdbObj:(git_odb_object *)object repository:(GTRepository *)repository { +- (instancetype)init { + NSAssert(NO, @"Call to an unavailable initializer."); + return nil; +} + +- (instancetype)initWithOdbObj:(git_odb_object *)object repository:(GTRepository *)repository { NSParameterAssert(object != NULL); NSParameterAssert(repository != nil); diff --git a/ObjectiveGit/GTReference.h b/ObjectiveGit/GTReference.h index 5d8f44e68..c24a9fc7b 100644 --- a/ObjectiveGit/GTReference.h +++ b/ObjectiveGit/GTReference.h @@ -28,18 +28,19 @@ @class GTOID; @class GTReflog; -@class GTSignature; typedef NS_ENUM(NSInteger, GTReferenceErrorCode) { GTReferenceErrorCodeInvalidReference = -4, }; typedef NS_OPTIONS(NSInteger, GTReferenceType) { - GTReferenceTypeInvalid = GIT_REF_INVALID, /** Invalid reference */ - GTReferenceTypeOid = GIT_REF_OID, /** A reference which points at an object id */ - GTReferenceTypeSymbolic = GIT_REF_SYMBOLIC, /** A reference which points at another reference */ + GTReferenceTypeInvalid = GIT_REFERENCE_INVALID, /** Invalid reference */ + GTReferenceTypeDirect = GIT_REFERENCE_DIRECT, /** A reference which points at an object id */ + GTReferenceTypeSymbolic = GIT_REFERENCE_SYMBOLIC, /** A reference which points at another reference */ }; +NS_ASSUME_NONNULL_BEGIN + @class GTRepository; /// A git reference object @@ -51,37 +52,51 @@ typedef NS_OPTIONS(NSInteger, GTReferenceType) { @property (nonatomic, readonly, strong) GTRepository *repository; @property (nonatomic, readonly) GTReferenceType referenceType; @property (nonatomic, readonly) const git_oid *git_oid; -@property (nonatomic, strong, readonly) GTOID *OID; +@property (nonatomic, strong, readonly) GTOID * _Nullable OID; + +/// Whether this is a tag. +@property (nonatomic, readonly, getter = isTag) BOOL tag; + +/// Whether this is a local branch. +@property (nonatomic, readonly, getter = isBranch) BOOL branch; /// Whether this is a remote-tracking branch. @property (nonatomic, readonly, getter = isRemote) BOOL remote; +/// Whether this is a note ref. +@property (nonatomic, readonly, getter = isNote) BOOL note; + /// The reflog for the reference. -@property (nonatomic, readonly, strong) GTReflog *reflog; +@property (nonatomic, readonly, strong) GTReflog * _Nullable reflog; /// Convenience initializers -+ (id)referenceByLookingUpReferencedNamed:(NSString *)refName inRepository:(GTRepository *)theRepo error:(NSError **)error; -- (id)initByLookingUpReferenceNamed:(NSString *)refName inRepository:(GTRepository *)theRepo error:(NSError **)error; ++ (instancetype _Nullable)referenceByResolvingSymbolicReference:(GTReference *)symbolicRef error:(NSError **)error; +- (instancetype _Nullable)initByResolvingSymbolicReference:(GTReference *)symbolicRef error:(NSError **)error; -+ (id)referenceByResolvingSymbolicReference:(GTReference *)symbolicRef error:(NSError **)error; -- (id)initByResolvingSymbolicReference:(GTReference *)symbolicRef error:(NSError **)error; +- (instancetype)init NS_UNAVAILABLE; -- (id)initWithGitReference:(git_reference *)ref repository:(GTRepository *)repository; +/// Designated initializer. +/// +/// ref - The reference to wrap. Must not be nil. +/// repository - The repository containing the reference. Must not be nil. +/// +/// Returns the initialized receiver. +- (instancetype _Nullable)initWithGitReference:(git_reference *)ref repository:(GTRepository *)repository NS_DESIGNATED_INITIALIZER; /// The underlying `git_reference` object. - (git_reference *)git_reference __attribute__((objc_returns_inner_pointer)); /// The target (either GTObject or GTReference) to which the reference points. -@property (nonatomic, readonly, copy) id unresolvedTarget; +@property (nonatomic, readonly, copy) id _Nullable unresolvedTarget; /// The resolved object to which the reference points. -@property (nonatomic, readonly, copy) id resolvedTarget; +@property (nonatomic, readonly, copy) id _Nullable resolvedTarget; /// The last direct reference in a chain @property (nonatomic, readonly, copy) GTReference *resolvedReference; -/// The SHA of the target object -@property (nonatomic, readonly, copy) NSString *targetSHA; +/// The OID of the target object. +@property (nonatomic, readonly, copy, nullable) GTOID *targetOID; /// Updates the on-disk reference to point to the target and returns the updated /// reference. @@ -89,14 +104,12 @@ typedef NS_OPTIONS(NSInteger, GTReferenceType) { /// Note that this does *not* change the receiver's target. /// /// newTarget - The target for the new reference. This must not be nil. -/// signature - A signature for the committer updating this ref, used for -/// creating a reflog entry. This may be nil. /// message - A message to use when creating the reflog entry for this action. /// This may be nil. /// error - The error if one occurred. /// /// Returns the updated reference, or nil if an error occurred. -- (GTReference *)referenceByUpdatingTarget:(NSString *)newTarget committer:(GTSignature *)signature message:(NSString *)message error:(NSError **)error; +- (GTReference * _Nullable)referenceByUpdatingTarget:(NSString *)newTarget message:(NSString * _Nullable)message error:(NSError **)error; /// The name of the reference. @property (nonatomic, readonly, copy) NSString *name; @@ -109,7 +122,7 @@ typedef NS_OPTIONS(NSInteger, GTReferenceType) { /// error - The error if one occurred. /// /// Returns the renamed reference, or nil if an error occurred. -- (GTReference *)referenceByRenaming:(NSString *)newName error:(NSError **)error; +- (GTReference * _Nullable)referenceByRenaming:(NSString *)newName error:(NSError **)error; /// Delete this reference. /// @@ -123,14 +136,14 @@ typedef NS_OPTIONS(NSInteger, GTReferenceType) { /// error(out) - will be filled if an error occurs /// /// returns the peeled GTReference or nil if an error occurred. -- (GTReference *)resolvedReferenceWithError:(NSError **)error; +- (GTReference * _Nullable)resolvedReferenceWithError:(NSError **)error; /// Reload the reference from disk. /// /// error - The error if one occurred. /// /// Returns the reloaded reference, or nil if an error occurred. -- (GTReference *)reloadedReferenceWithError:(NSError **)error; +- (GTReference * _Nullable)reloadedReferenceWithError:(NSError **)error; /// An error indicating that the git_reference is no longer valid. + (NSError *)invalidReferenceError; @@ -143,3 +156,5 @@ typedef NS_OPTIONS(NSInteger, GTReferenceType) { + (BOOL)isValidReferenceName:(NSString *)refName; @end + +NS_ASSUME_NONNULL_END diff --git a/ObjectiveGit/GTReference.m b/ObjectiveGit/GTReference.m index 74aaa8496..080375dd2 100644 --- a/ObjectiveGit/GTReference.m +++ b/ObjectiveGit/GTReference.m @@ -32,6 +32,7 @@ #import "GTSignature.h" #import "NSError+Git.h" #import "NSString+Git.h" +#import "GTRepository+References.h" #import "git2/errors.h" @@ -44,7 +45,7 @@ @interface GTReference () case GTReferenceTypeInvalid: return @"invalid"; - case GTReferenceTypeOid: + case GTReferenceTypeDirect: return @"direct"; case GTReferenceTypeSymbolic: @@ -69,29 +70,16 @@ - (BOOL)isRemote { return git_reference_is_remote(self.git_reference) != 0; } -+ (id)referenceByLookingUpReferencedNamed:(NSString *)refName inRepository:(GTRepository *)theRepo error:(NSError **)error { - return [[self alloc] initByLookingUpReferenceNamed:refName inRepository:theRepo error:error]; -} - -+ (id)referenceByResolvingSymbolicReference:(GTReference *)symbolicRef error:(NSError **)error { ++ (instancetype)referenceByResolvingSymbolicReference:(GTReference *)symbolicRef error:(NSError **)error { return [[self alloc] initByResolvingSymbolicReference:symbolicRef error:error]; } -- (id)initByLookingUpReferenceNamed:(NSString *)refName inRepository:(GTRepository *)repo error:(NSError **)error { - NSParameterAssert(refName != nil); - NSParameterAssert(repo != nil); - - git_reference *ref = NULL; - int gitError = git_reference_lookup(&ref, repo.git_repository, refName.UTF8String); - if (gitError != GIT_OK) { - if (error != NULL) *error = [NSError git_errorFor:gitError description:@"Failed to lookup reference %@.", refName]; - return nil; - } - - return [self initWithGitReference:ref repository:repo]; +- (instancetype)init { + NSAssert(NO, @"Call to an unavailable initializer."); + return nil; } -- (id)initByResolvingSymbolicReference:(GTReference *)symbolicRef error:(NSError **)error { +- (instancetype)initByResolvingSymbolicReference:(GTReference *)symbolicRef error:(NSError **)error { NSParameterAssert(symbolicRef != nil); git_reference *ref = NULL; @@ -104,7 +92,7 @@ - (id)initByResolvingSymbolicReference:(GTReference *)symbolicRef error:(NSError return [self initWithGitReference:ref repository:symbolicRef.repository]; } -- (id)initWithGitReference:(git_reference *)ref repository:(GTRepository *)repo { +- (instancetype)initWithGitReference:(git_reference *)ref repository:(GTRepository *)repo { NSParameterAssert(ref != NULL); NSParameterAssert(repo != nil); @@ -117,18 +105,32 @@ - (id)initWithGitReference:(git_reference *)ref repository:(GTRepository *)repo return self; } +- (BOOL)isBranch { + return git_reference_is_branch(self.git_reference) != 0; +} + +- (BOOL)isTag { + return git_reference_is_tag(self.git_reference) != 0; +} + +- (BOOL)isNote { + return git_reference_is_note(self.git_reference) != 0; +} + - (NSString *)name { - const char *refName = git_reference_name(self.git_reference); - if (refName == NULL) return nil; + const char *cRefName = git_reference_name(self.git_reference); + NSAssert(cRefName != nil, @"Unexpected nil name"); - return @(refName); + NSString *refName = @(cRefName); + NSAssert(refName, @"refname is nil"); + return refName; } - (GTReference *)referenceByRenaming:(NSString *)newName error:(NSError **)error { NSParameterAssert(newName != nil); git_reference *newRef = NULL; - int gitError = git_reference_rename(&newRef, self.git_reference, newName.UTF8String, 0, [self.repository userSignatureForNow].git_signature, NULL); + int gitError = git_reference_rename(&newRef, self.git_reference, newName.UTF8String, 0, NULL); if (gitError != GIT_OK) { if (error != NULL) *error = [NSError git_errorFor:gitError description:@"Failed to rename reference %@ to %@.", self.name, newName]; return nil; @@ -142,7 +144,7 @@ - (GTReferenceType)referenceType { } - (id)unresolvedTarget { - if (self.referenceType == GTReferenceTypeOid) { + if (self.referenceType == GTReferenceTypeDirect) { const git_oid *oid = git_reference_target(self.git_reference); if (oid == NULL) return nil; @@ -151,14 +153,14 @@ - (id)unresolvedTarget { NSString *refName = @(git_reference_symbolic_target(self.git_reference)); if (refName == NULL) return nil; - return [self.class referenceByLookingUpReferencedNamed:refName inRepository:self.repository error:NULL]; + return [self.repository lookUpReferenceWithName:refName error:NULL]; } return nil; } - (id)resolvedTarget { git_object *obj; - if (git_reference_peel(&obj, self.git_reference, GIT_OBJ_ANY) != GIT_OK) { + if (git_reference_peel(&obj, self.git_reference, GIT_OBJECT_ANY) != GIT_OK) { return nil; } @@ -166,25 +168,26 @@ - (id)resolvedTarget { } - (GTReference *)resolvedReference { - return [self.class referenceByResolvingSymbolicReference:self error:NULL]; + GTReference *resolvedReference = [self.class referenceByResolvingSymbolicReference:self error:NULL]; + return resolvedReference ? resolvedReference : self; } -- (NSString *)targetSHA { - return [self.resolvedTarget SHA]; +- (GTOID *)targetOID { + return [self.resolvedTarget OID]; } -- (GTReference *)referenceByUpdatingTarget:(NSString *)newTarget committer:(GTSignature *)signature message:(NSString *)message error:(NSError **)error { +- (GTReference *)referenceByUpdatingTarget:(NSString *)newTarget message:(NSString *)message error:(NSError **)error { NSParameterAssert(newTarget != nil); int gitError; git_reference *newRef = NULL; - if (git_reference_type(self.git_reference) == GIT_REF_OID) { + if (git_reference_type(self.git_reference) == GIT_REFERENCE_DIRECT) { GTOID *oid = [[GTOID alloc] initWithSHA:newTarget error:error]; if (oid == nil) return nil; - gitError = git_reference_set_target(&newRef, self.git_reference, oid.git_oid, signature.git_signature, message.UTF8String); + gitError = git_reference_set_target(&newRef, self.git_reference, oid.git_oid, message.UTF8String); } else { - gitError = git_reference_symbolic_set_target(&newRef, self.git_reference, newTarget.UTF8String, signature.git_signature, message.UTF8String); + gitError = git_reference_symbolic_set_target(&newRef, self.git_reference, newTarget.UTF8String, message.UTF8String); } if (gitError != GIT_OK) { @@ -221,7 +224,7 @@ - (GTOID *)OID { } - (GTReference *)reloadedReferenceWithError:(NSError **)error { - return [[self.class alloc] initByLookingUpReferenceNamed:self.name inRepository:self.repository error:error]; + return [self.repository lookUpReferenceWithName:self.name error:error]; } + (NSError *)invalidReferenceError { diff --git a/ObjectiveGit/GTReflog+Private.h b/ObjectiveGit/GTReflog+Private.h index 7cf11f298..812cad515 100644 --- a/ObjectiveGit/GTReflog+Private.h +++ b/ObjectiveGit/GTReflog+Private.h @@ -8,15 +8,8 @@ #import "GTReflog.h" -@class GTReference; - @interface GTReflog () -/// Initializes the receiver with a reference. -/// -/// reference - The reference whose reflog is being represented. Cannot be nil. -/// -/// Returns the initialized object. -- (id)initWithReference:(GTReference *)reference; +- (instancetype _Nullable)init NS_UNAVAILABLE; @end diff --git a/ObjectiveGit/GTReflog.h b/ObjectiveGit/GTReflog.h index 94befcfd3..feeafea51 100644 --- a/ObjectiveGit/GTReflog.h +++ b/ObjectiveGit/GTReflog.h @@ -9,8 +9,11 @@ #import @class GTSignature; +@class GTReference; @class GTReflogEntry; +NS_ASSUME_NONNULL_BEGIN + /// A reflog for a reference. Reflogs should not be created manually. Use /// -[GTReference reflog] to get the reflog for a reference. @interface GTReflog : NSObject @@ -18,6 +21,13 @@ /// The number of reflog entries. @property (nonatomic, readonly, assign) NSUInteger entryCount; +/// Initializes the receiver with a reference. Designated initializer. +/// +/// reference - The reference whose reflog is being represented. Cannot be nil. +/// +/// Returns the initialized object. +- (instancetype _Nullable)initWithReference:(GTReference * _Nonnull)reference NS_DESIGNATED_INITIALIZER; + /// Writes a new entry to the reflog. /// /// committer - The committer for the reflog entry. Cannot be nil. @@ -32,7 +42,9 @@ /// index - The reflog entry to get. 0 is the most recent entry. If it is greater /// than `entryCount`, it will assert. /// -/// Returns the entry at that index. -- (GTReflogEntry *)entryAtIndex:(NSUInteger)index; +/// Returns the entry at that index or nil if not found. +- (GTReflogEntry * _Nullable)entryAtIndex:(NSUInteger)index; @end + +NS_ASSUME_NONNULL_END diff --git a/ObjectiveGit/GTReflog.m b/ObjectiveGit/GTReflog.m index b2e079593..be1ecad6b 100644 --- a/ObjectiveGit/GTReflog.m +++ b/ObjectiveGit/GTReflog.m @@ -33,7 +33,12 @@ - (void)dealloc { if (_git_reflog != NULL) git_reflog_free(_git_reflog); } -- (id)initWithReference:(GTReference *)reference { +- (instancetype)init { + NSAssert(NO, @"Call to an unavailable initializer."); + return nil; +} + +- (instancetype)initWithReference:(GTReference *)reference { NSParameterAssert(reference != nil); NSParameterAssert(reference.name != nil); diff --git a/ObjectiveGit/GTReflogEntry+Private.h b/ObjectiveGit/GTReflogEntry+Private.h index 5582fd272..b30415160 100644 --- a/ObjectiveGit/GTReflogEntry+Private.h +++ b/ObjectiveGit/GTReflogEntry+Private.h @@ -9,14 +9,18 @@ #import "GTReflogEntry.h" #import "git2/types.h" +NS_ASSUME_NONNULL_BEGIN + @interface GTReflogEntry () -/// Initializes the receiver with the underlying reflog entry. +/// Initializes the receiver with the underlying reflog entry. Designated initializer. /// /// entry - The reflog entry. Cannot be NULL. /// reflog - The reflog in which the entry resides. Cannot be nil. /// /// Returns the initialized object. -- (id)initWithGitReflogEntry:(const git_reflog_entry *)entry reflog:(GTReflog *)reflog; +- (instancetype _Nullable)initWithGitReflogEntry:(const git_reflog_entry *)entry reflog:(GTReflog *)reflog NS_DESIGNATED_INITIALIZER; @end + +NS_ASSUME_NONNULL_END \ No newline at end of file diff --git a/ObjectiveGit/GTReflogEntry.h b/ObjectiveGit/GTReflogEntry.h index 3f66f4c4e..99fcc503f 100644 --- a/ObjectiveGit/GTReflogEntry.h +++ b/ObjectiveGit/GTReflogEntry.h @@ -15,15 +15,15 @@ @interface GTReflogEntry : NSObject /// The OID of the ref before the entry. -@property (nonatomic, readonly, strong) GTOID *previousOID; +@property (nonatomic, readonly, strong) GTOID * _Nullable previousOID; /// The OID of the ref when the entry was made. -@property (nonatomic, readonly, strong) GTOID *updatedOID; +@property (nonatomic, readonly, strong) GTOID * _Nullable updatedOID; /// The person who committed the entry. -@property (nonatomic, readonly, strong) GTSignature *committer; +@property (nonatomic, readonly, strong) GTSignature * _Nullable committer; /// The message associated with the entry. -@property (nonatomic, readonly, copy) NSString *message; +@property (nonatomic, readonly, copy) NSString * _Nullable message; @end diff --git a/ObjectiveGit/GTReflogEntry.m b/ObjectiveGit/GTReflogEntry.m index 9aaaea029..7035b2900 100644 --- a/ObjectiveGit/GTReflogEntry.m +++ b/ObjectiveGit/GTReflogEntry.m @@ -27,7 +27,7 @@ @implementation GTReflogEntry #pragma mark Lifecycle -- (id)initWithGitReflogEntry:(const git_reflog_entry *)entry reflog:(GTReflog *)reflog { +- (instancetype)initWithGitReflogEntry:(const git_reflog_entry *)entry reflog:(GTReflog *)reflog { NSParameterAssert(entry != NULL); NSParameterAssert(reflog != nil); diff --git a/ObjectiveGit/GTRemote.h b/ObjectiveGit/GTRemote.h index 55a7805d1..bde9a37f1 100644 --- a/ObjectiveGit/GTRemote.h +++ b/ObjectiveGit/GTRemote.h @@ -14,6 +14,8 @@ @class GTReference; @class GTCredentialProvider; +NS_ASSUME_NONNULL_BEGIN + extern NSString * const GTRemoteRenameProblematicRefSpecs; // Auto Tag settings. See `git_remote_autotag_option_t`. @@ -32,13 +34,13 @@ typedef enum { @property (nonatomic, readonly, strong) GTRepository *repository; /// The name of the remote. -@property (nonatomic, readonly, copy) NSString *name; +@property (nonatomic, readonly, copy) NSString * _Nullable name; /// The URL string for the remote. -@property (nonatomic, readonly, copy) NSString *URLString; +@property (nonatomic, readonly, copy) NSString * _Nullable URLString; /// The push URL for the remote, if provided. -@property (nonatomic, copy) NSString *pushURLString; +@property (nonatomic, copy) NSString * _Nullable pushURLString; /// Whether the remote is connected or not. @property (nonatomic, readonly, getter=isConnected) BOOL connected; @@ -54,16 +56,13 @@ typedef enum { /// /// This array will contain NSStrings of the form /// `+refs/heads/*:refs/remotes/REMOTE/*`. -@property (nonatomic, readonly, copy) NSArray *fetchRefspecs; +@property (nonatomic, readonly, copy) NSArray * _Nullable fetchRefspecs; /// The push refspecs for this remote. /// /// This array will contain NSStrings of the form /// `+refs/heads/*:refs/remotes/REMOTE/*`. -@property (nonatomic, readonly, copy) NSArray *pushRefspecs; - -/// Tests if a URL is supported (e.g. it's a supported URL scheme) -+ (BOOL)isSupportedURLString:(NSString *)URLString; +@property (nonatomic, readonly, copy) NSArray * _Nullable pushRefspecs; /// Tests if a name is valid + (BOOL)isValidRemoteName:(NSString *)name; @@ -76,7 +75,7 @@ typedef enum { /// error - Will be set if an error occurs. /// /// Returns a new remote, or nil if an error occurred -+ (instancetype)createRemoteWithName:(NSString *)name URLString:(NSString *)URLString inRepository:(GTRepository *)repo error:(NSError **)error; ++ (instancetype _Nullable)createRemoteWithName:(NSString *)name URLString:(NSString *)URLString inRepository:(GTRepository *)repo error:(NSError **)error; /// Load a remote from a repository. /// @@ -85,13 +84,17 @@ typedef enum { /// error - Will be set if an error occurs. /// /// Returns the loaded remote, or nil if an error occurred. -+ (instancetype)remoteWithName:(NSString *)name inRepository:(GTRepository *)repo error:(NSError **)error; ++ (instancetype _Nullable)remoteWithName:(NSString *)name inRepository:(GTRepository *)repo error:(NSError **)error; + +- (instancetype)init NS_UNAVAILABLE; -/// Initialize a remote from a `git_remote`. +/// Initialize a remote from a `git_remote`. Designated initializer. /// /// remote - The underlying `git_remote` object. Cannot be nil. /// repo - The repository the remote belongs to. Cannot be nil. -- (instancetype)initWithGitRemote:(git_remote *)remote inRepository:(GTRepository *)repo; +/// +/// Returns the initialized receiver, or nil if an error occurred. +- (instancetype _Nullable)initWithGitRemote:(git_remote *)remote inRepository:(GTRepository *)repo NS_DESIGNATED_INITIALIZER; /// The underlying `git_remote` object. - (git_remote *)git_remote __attribute__((objc_returns_inner_pointer)); @@ -116,6 +119,16 @@ typedef enum { /// if updating or saving the remote failed. - (BOOL)updateURLString:(NSString *)URLString error:(NSError **)error; +/// Updates the push URL string for this remote. +/// +/// URLString - The URLString to update to. May not be nil. +/// error - If not NULL, this will be set to any error that occurs when +/// updating the URLString or saving the remote. +/// +/// Returns YES if the push URLString was successfully updated, NO and an error +/// if updating or saving the remote failed. +- (BOOL)updatePushURLString:(NSString *)URLString error:(NSError **)error; + /// Adds a fetch refspec to this remote. /// /// fetchRefspec - The fetch refspec string to add. May not be nil. @@ -128,3 +141,5 @@ typedef enum { - (BOOL)addFetchRefspec:(NSString *)fetchRefspec error:(NSError **)error; @end + +NS_ASSUME_NONNULL_END diff --git a/ObjectiveGit/GTRemote.m b/ObjectiveGit/GTRemote.m index 2bf139a9f..03f76b7ca 100644 --- a/ObjectiveGit/GTRemote.m +++ b/ObjectiveGit/GTRemote.m @@ -50,7 +50,7 @@ + (instancetype)remoteWithName:(NSString *)name inRepository:(GTRepository *)rep NSParameterAssert(repo != nil); git_remote *remote; - int gitError = git_remote_load(&remote, repo.git_repository, name.UTF8String); + int gitError = git_remote_lookup(&remote, repo.git_repository, name.UTF8String); if (gitError != GIT_OK) { if (error != NULL) *error = [NSError git_errorFor:gitError description:@"Remote loading failed" failureReason:nil]; @@ -60,6 +60,11 @@ + (instancetype)remoteWithName:(NSString *)name inRepository:(GTRepository *)rep return [[self alloc] initWithGitRemote:remote inRepository:repo]; } +- (instancetype)init { + NSAssert(NO, @"Call to an unavailable initializer."); + return nil; +} + - (instancetype)initWithGitRemote:(git_remote *)remote inRepository:(GTRepository *)repo { NSParameterAssert(remote != NULL); NSParameterAssert(repo != nil); @@ -90,18 +95,16 @@ - (NSUInteger)hash { return self.name.hash ^ self.URLString.hash; } -#pragma mark API - -+ (BOOL)isSupportedURLString:(NSString *)URLString { - NSParameterAssert(URLString != nil); - - return git_remote_supported_url(URLString.UTF8String) == GIT_OK; +- (NSString *)description { + return [NSString stringWithFormat:@"<%@: %p> name: %@, URLString: %@", NSStringFromClass([self class]), self, self.name, self.URLString]; } +#pragma mark API + + (BOOL)isValidRemoteName:(NSString *)name { NSParameterAssert(name != nil); - return git_remote_is_valid_name(name.UTF8String) == GIT_OK; + return (git_remote_is_valid_name(name.UTF8String) == 1 ? YES : NO); } #pragma mark Properties @@ -121,7 +124,7 @@ - (NSString *)URLString { } - (void)setURLString:(NSString *)URLString { - git_remote_set_url(self.git_remote, URLString.UTF8String); + git_remote_set_url(self.repository.git_repository, self.name.UTF8String, URLString.UTF8String); } - (NSString *)pushURLString { @@ -132,23 +135,7 @@ - (NSString *)pushURLString { } - (void)setPushURLString:(NSString *)pushURLString { - git_remote_set_pushurl(self.git_remote, pushURLString.UTF8String); -} - -- (BOOL)updatesFetchHead { - return git_remote_update_fetchhead(self.git_remote) != 0; -} - -- (void)setUpdatesFetchHead:(BOOL)updatesFetchHead { - git_remote_set_update_fetchhead(self.git_remote, updatesFetchHead); -} - -- (GTRemoteAutoTagOption)autoTag { - return (GTRemoteAutoTagOption)git_remote_autotag(self.git_remote); -} - -- (void)setAutoTag:(GTRemoteAutoTagOption)autoTag { - git_remote_set_autotag(self.git_remote, (git_remote_autotag_option_t)autoTag); + git_remote_set_pushurl(self.repository.git_repository, self.name.UTF8String, pushURLString.UTF8String); } - (BOOL)isConnected { @@ -162,7 +149,7 @@ - (BOOL)rename:(NSString *)name error:(NSError **)error { git_strarray problematic_refspecs; - int gitError = git_remote_rename(&problematic_refspecs, self.git_remote, name.UTF8String); + int gitError = git_remote_rename(&problematic_refspecs, self.repository.git_repository, git_remote_name(self.git_remote), name.UTF8String); if (gitError != GIT_OK) { NSArray *problematicRefspecs = [NSArray git_arrayWithStrarray:problematic_refspecs]; NSDictionary *userInfo = [NSDictionary dictionaryWithObject:problematicRefspecs forKey:GTRemoteRenameProblematicRefSpecs]; @@ -202,30 +189,34 @@ - (NSArray *)pushRefspecs { #pragma mark Update the remote -- (BOOL)saveRemote:(NSError **)error { - int gitError = git_remote_save(self.git_remote); +- (BOOL)updateURLString:(NSString *)URLString error:(NSError **)error { + NSParameterAssert(URLString != nil); + + if ([self.URLString isEqualToString:URLString]) return YES; + + int gitError = git_remote_set_url(self.repository.git_repository, self.name.UTF8String, URLString.UTF8String); if (gitError != GIT_OK) { if (error != NULL) { - *error = [NSError git_errorFor:gitError description:@"Failed to save remote configuration."]; + *error = [NSError git_errorFor:gitError description:@"Failed to update remote URL string."]; } return NO; } return YES; } -- (BOOL)updateURLString:(NSString *)URLString error:(NSError **)error { +- (BOOL)updatePushURLString:(NSString *)URLString error:(NSError **)error { NSParameterAssert(URLString != nil); - - if ([self.URLString isEqualToString:URLString]) return YES; - - int gitError = git_remote_set_url(self.git_remote, URLString.UTF8String); + + if ([self.pushURLString isEqualToString:URLString]) return YES; + + int gitError = git_remote_set_pushurl(self.repository.git_repository, self.name.UTF8String, URLString.UTF8String); if (gitError != GIT_OK) { if (error != NULL) { - *error = [NSError git_errorFor:gitError description:@"Failed to update remote URL string."]; + *error = [NSError git_errorFor:gitError description:@"Failed to update remote push URL string."]; } return NO; } - return [self saveRemote:error]; + return YES; } - (BOOL)addFetchRefspec:(NSString *)fetchRefspec error:(NSError **)error { @@ -233,14 +224,14 @@ - (BOOL)addFetchRefspec:(NSString *)fetchRefspec error:(NSError **)error { if ([self.fetchRefspecs containsObject:fetchRefspec]) return YES; - int gitError = git_remote_add_fetch(self.git_remote, fetchRefspec.UTF8String); + int gitError = git_remote_add_fetch(self.repository.git_repository, self.name.UTF8String, fetchRefspec.UTF8String); if (gitError != GIT_OK) { if (error != NULL) { *error = [NSError git_errorFor:gitError description:@"Failed to add fetch refspec."]; } return NO; } - return [self saveRemote:error]; + return YES; } @end diff --git a/ObjectiveGit/GTRepository+Attributes.h b/ObjectiveGit/GTRepository+Attributes.h index 8f214505f..a86ab6e28 100644 --- a/ObjectiveGit/GTRepository+Attributes.h +++ b/ObjectiveGit/GTRepository+Attributes.h @@ -8,6 +8,8 @@ #import "GTRepository.h" +NS_ASSUME_NONNULL_BEGIN + @interface GTRepository (Attributes) /// Look up the value for the attribute of the given name for the given path. @@ -16,6 +18,8 @@ /// path - The path to use for the lookup. Cannot be nil. /// /// Returns the value of the attribute or nil. -- (NSString *)attributeWithName:(NSString *)name path:(NSString *)path; +- (NSString * _Nullable)attributeWithName:(NSString *)name path:(NSString *)path; @end + +NS_ASSUME_NONNULL_END diff --git a/ObjectiveGit/GTRepository+Committing.h b/ObjectiveGit/GTRepository+Committing.h index e85318d42..4e5518664 100644 --- a/ObjectiveGit/GTRepository+Committing.h +++ b/ObjectiveGit/GTRepository+Committing.h @@ -8,6 +8,8 @@ #import "GTRepository.h" +NS_ASSUME_NONNULL_BEGIN + @interface GTRepository (Committing) /// Creates a new commit. @@ -23,10 +25,12 @@ /// error - The error if one occurred. /// /// Returns the newly created commit, or nil if an error occurred. -- (GTCommit *)createCommitWithTree:(GTTree *)tree message:(NSString *)message author:(GTSignature *)author committer:(GTSignature *)committer parents:(NSArray *)parents updatingReferenceNamed:(NSString *)refName error:(NSError **)error; +- (GTCommit * _Nullable)createCommitWithTree:(GTTree *)tree message:(NSString *)message author:(GTSignature *)author committer:(GTSignature *)committer parents:(NSArray * _Nullable)parents updatingReferenceNamed:(NSString * _Nullable)refName error:(NSError **)error; /// Creates a new commit using +createCommitWithTree:message:author:committer:parents:updatingReferenceNamed:error: /// with -userSignatureForNow as both the author and committer. -- (GTCommit *)createCommitWithTree:(GTTree *)tree message:(NSString *)message parents:(NSArray *)parents updatingReferenceNamed:(NSString *)refName error:(NSError **)error; +- (GTCommit * _Nullable)createCommitWithTree:(GTTree *)tree message:(NSString *)message parents:(NSArray * _Nullable)parents updatingReferenceNamed:(NSString * _Nullable)refName error:(NSError **)error; @end + +NS_ASSUME_NONNULL_END diff --git a/ObjectiveGit/GTRepository+Merging.h b/ObjectiveGit/GTRepository+Merging.h new file mode 100644 index 000000000..53649a095 --- /dev/null +++ b/ObjectiveGit/GTRepository+Merging.h @@ -0,0 +1,80 @@ +// +// GTRepository+Merging.h +// ObjectiveGitFramework +// +// Created by Piet Brauer on 02/03/16. +// Copyright © 2016 GitHub, Inc. All rights reserved. +// + +#import "GTRepository.h" +#import "GTIndexEntry.h" +#import "git2/merge.h" + +NS_ASSUME_NONNULL_BEGIN + +/// UserInfo key for conflicted files when pulling fails with a merge conflict +extern NSString * const GTPullMergeConflictedFiles; + +/// An enum describing the result of the merge analysis. +/// See `git_merge_analysis_t`. +typedef NS_OPTIONS(NSInteger, GTMergeAnalysis) { + GTMergeAnalysisNone = GIT_MERGE_ANALYSIS_NONE, + GTMergeAnalysisNormal = GIT_MERGE_ANALYSIS_NORMAL, + GTMergeAnalysisUpToDate = GIT_MERGE_ANALYSIS_UP_TO_DATE, + GTMergeAnalysisUnborn = GIT_MERGE_ANALYSIS_UNBORN, + GTMergeAnalysisFastForward = GIT_MERGE_ANALYSIS_FASTFORWARD, +}; + +@interface GTRepository (Merging) + +/// Enumerate all available merge head entries. +/// +/// error - The error if one ocurred. Can be NULL. +/// block - A block to execute for each MERGE_HEAD entry. `mergeHeadEntry` will +/// be the current merge head entry. Setting `stop` to YES will cause +/// enumeration to stop after the block returns. Must not be nil. +/// +/// Returns YES if the operation succedded, NO otherwise. +- (BOOL)enumerateMergeHeadEntriesWithError:(NSError **)error usingBlock:(void (^)(GTOID *mergeHeadEntry, BOOL *stop))block; + +/// Convenience method for -enumerateMergeHeadEntriesWithError:usingBlock: that retuns an NSArray with all the fetch head entries. +/// +/// error - The error if one ocurred. Can be NULL. +/// +/// Retruns a (possibly empty) array with GTOID objects. Will not be nil. +- (NSArray *)mergeHeadEntriesWithError:(NSError **)error; + +/// Merge Branch into current branch +/// +/// fromBranch - The branch to merge from. +/// error - The error if one occurred. Can be NULL. +/// +/// Returns YES if the merge was successful, NO otherwise (and `error`, if provided, +/// will point to an error describing what happened). +- (BOOL)mergeBranchIntoCurrentBranch:(GTBranch *)fromBranch withError:(NSError **)error; + +/// Gets the file content with conflict markers for the given file +/// +/// The parameters taked are the ones received from `enumerateConflictedFiles`. +/// +/// ancestor - The ancestor entry +/// ours - The index entry of our side +/// theirs - The index entry of their side +/// error - The error if one occurred. Can be NULL. +/// +/// Returns The file content annotated with conflict markers or null on error +- (NSString * _Nullable)contentsOfDiffWithAncestor:(GTIndexEntry *)ancestor ourSide:(GTIndexEntry *)ourSide theirSide:(GTIndexEntry *)theirSide error:(NSError **)error; + +/// Analyze which merge to perform. +/// +/// analysis - The resulting analysis. +/// fromBranch - The branch to merge from. +/// error - The error if one occurred. Can be NULL. +/// +/// Returns YES if the analysis was successful, NO otherwise (and `error`, if provided, +/// will point to an error describing what happened). +- (BOOL)analyzeMerge:(GTMergeAnalysis *)analysis fromBranch:(GTBranch *)fromBranch error:(NSError **)error; + +@end + +NS_ASSUME_NONNULL_END diff --git a/ObjectiveGit/GTRepository+Merging.m b/ObjectiveGit/GTRepository+Merging.m new file mode 100644 index 000000000..f7b9837df --- /dev/null +++ b/ObjectiveGit/GTRepository+Merging.m @@ -0,0 +1,288 @@ +// +// GTRepository+Merging.m +// ObjectiveGitFramework +// +// Created by Piet Brauer on 02/03/16. +// Copyright © 2016 GitHub, Inc. All rights reserved. +// + +#import "GTRepository+Merging.h" +#import "GTOID.h" +#import "NSError+Git.h" +#import "git2/errors.h" +#import "GTCommit.h" +#import "GTReference.h" +#import "GTRepository+Committing.h" +#import "GTRepository+Pull.h" +#import "GTTree.h" +#import "GTIndex.h" +#import "GTIndexEntry.h" +#import "GTOdbObject.h" +#import "GTObjectDatabase.h" + +typedef void (^GTRemoteFetchTransferProgressBlock)(const git_transfer_progress *stats, BOOL *stop); + +@implementation GTRepository (Merging) + +typedef void (^GTRepositoryEnumerateMergeHeadEntryBlock)(GTOID *entry, BOOL *stop); + +typedef struct { + __unsafe_unretained GTRepositoryEnumerateMergeHeadEntryBlock enumerationBlock; +} GTEnumerateMergeHeadEntriesPayload; + +int GTMergeHeadEntriesCallback(const git_oid *oid, void *payload) { + GTEnumerateMergeHeadEntriesPayload *entriesPayload = payload; + + GTRepositoryEnumerateMergeHeadEntryBlock enumerationBlock = entriesPayload->enumerationBlock; + + GTOID *gtoid = [GTOID oidWithGitOid:oid]; + + BOOL stop = NO; + + enumerationBlock(gtoid, &stop); + + return (stop == YES ? GIT_EUSER : 0); +} + +- (BOOL)enumerateMergeHeadEntriesWithError:(NSError **)error usingBlock:(void (^)(GTOID *mergeHeadEntry, BOOL *stop))block { + NSParameterAssert(block != nil); + + GTEnumerateMergeHeadEntriesPayload payload = { + .enumerationBlock = block, + }; + + int gitError = git_repository_mergehead_foreach(self.git_repository, GTMergeHeadEntriesCallback, &payload); + + if (gitError != GIT_OK) { + if (error != NULL) *error = [NSError git_errorFor:gitError description:@"Failed to get mergehead entries"]; + return NO; + } + + return YES; +} + +- (NSArray *)mergeHeadEntriesWithError:(NSError **)error { + NSMutableArray *entries = [NSMutableArray array]; + + [self enumerateMergeHeadEntriesWithError:error usingBlock:^(GTOID *mergeHeadEntry, BOOL *stop) { + [entries addObject:mergeHeadEntry]; + + *stop = NO; + }]; + + return entries; +} + +- (BOOL)mergeBranchIntoCurrentBranch:(GTBranch *)branch withError:(NSError **)error { + // Check if merge is necessary + GTBranch *localBranch = [self currentBranchWithError:error]; + if (!localBranch) { + return NO; + } + + GTCommit *localCommit = [localBranch targetCommitWithError:error]; + if (!localCommit) { + return NO; + } + + GTCommit *remoteCommit = [branch targetCommitWithError:error]; + if (!remoteCommit) { + return NO; + } + + if ([localCommit.SHA isEqualToString:remoteCommit.SHA]) { + // Local and remote tracking branch are already in sync + return YES; + } + + GTMergeAnalysis analysis = GTMergeAnalysisNone; + BOOL success = [self analyzeMerge:&analysis fromBranch:branch error:error]; + if (!success) { + return NO; + } + + if (analysis & GTMergeAnalysisUpToDate) { + // Nothing to do + return YES; + } else if (analysis & GTMergeAnalysisFastForward || + analysis & GTMergeAnalysisUnborn) { + // Fast-forward branch + NSString *message = [NSString stringWithFormat:@"merge %@: Fast-forward", branch.name]; + GTReference *reference = [localBranch.reference referenceByUpdatingTarget:remoteCommit.SHA message:message error:error]; + BOOL checkoutSuccess = [self checkoutReference:reference options:[GTCheckoutOptions checkoutOptionsWithStrategy:GTCheckoutStrategyForce] error:error]; + return checkoutSuccess; + } else if (analysis & GTMergeAnalysisNormal) { + // Do normal merge + GTTree *localTree = localCommit.tree; + GTTree *remoteTree = remoteCommit.tree; + + // TODO: Find common ancestor + GTTree *ancestorTree = nil; + + // Merge + GTIndex *index = [localTree merge:remoteTree ancestor:ancestorTree error:error]; + if (!index) { + return NO; + } + + // Check for conflict + if (index.hasConflicts) { + NSMutableArray *files = [NSMutableArray array]; + [index enumerateConflictedFilesWithError:error usingBlock:^(GTIndexEntry * _Nonnull ancestor, GTIndexEntry * _Nonnull ours, GTIndexEntry * _Nonnull theirs, BOOL * _Nonnull stop) { + [files addObject:ours.path]; + }]; + + if (error != NULL) { + NSDictionary *userInfo = @{GTPullMergeConflictedFiles: files}; + *error = [NSError git_errorFor:GIT_ECONFLICT description:@"Merge conflict" userInfo:userInfo failureReason:nil]; + } + + // Write conflicts + git_merge_options merge_opts = GIT_MERGE_OPTIONS_INIT; + git_checkout_options checkout_opts = GIT_CHECKOUT_OPTIONS_INIT; + checkout_opts.checkout_strategy = (GIT_CHECKOUT_SAFE | GIT_CHECKOUT_ALLOW_CONFLICTS); + + git_annotated_commit *annotatedCommit; + [self annotatedCommit:&annotatedCommit fromCommit:remoteCommit error:error]; + + git_merge(self.git_repository, (const git_annotated_commit **)&annotatedCommit, 1, &merge_opts, &checkout_opts); + + return NO; + } + + GTTree *newTree = [index writeTreeToRepository:self error:error]; + if (!newTree) { + return NO; + } + + // Create merge commit + NSString *message = [NSString stringWithFormat:@"Merge branch '%@'", localBranch.shortName]; + NSArray *parents = @[ localCommit, remoteCommit ]; + + // FIXME: This is stepping on the local tree + GTCommit *mergeCommit = [self createCommitWithTree:newTree message:message parents:parents updatingReferenceNamed:localBranch.reference.name error:error]; + if (!mergeCommit) { + return NO; + } + + BOOL success = [self checkoutReference:localBranch.reference options:[GTCheckoutOptions checkoutOptionsWithStrategy:GTCheckoutStrategyForce] error:error]; + return success; + } + + return NO; +} + +- (NSString * _Nullable)contentsOfDiffWithAncestor:(GTIndexEntry *)ancestor ourSide:(GTIndexEntry *)ourSide theirSide:(GTIndexEntry *)theirSide error:(NSError **)error { + + GTObjectDatabase *database = [self objectDatabaseWithError:error]; + if (database == nil) { + return nil; + } + + // initialize the ancestor's merge file input + git_merge_file_input ancestorInput; + int gitError = git_merge_file_init_input(&ancestorInput, GIT_MERGE_FILE_INPUT_VERSION); + if (gitError != GIT_OK) { + if (error != NULL) *error = [NSError git_errorFor:gitError description:@"Failed to create merge file input for ancestor"]; + return nil; + } + + git_oid ancestorId = ancestor.git_index_entry->id; + GTOID *ancestorOID = [[GTOID alloc] initWithGitOid:&ancestorId]; + NSData *ancestorData = [[database objectWithOID:ancestorOID error: error] data]; + if (ancestorData == nil) { + return nil; + } + ancestorInput.ptr = ancestorData.bytes; + ancestorInput.size = ancestorData.length; + + + // initialize our merge file input + git_merge_file_input ourInput; + gitError = git_merge_file_init_input(&ourInput, GIT_MERGE_FILE_INPUT_VERSION); + if (gitError != GIT_OK) { + if (error != NULL) *error = [NSError git_errorFor:gitError description:@"Failed to create merge file input for our side"]; + return nil; + } + + git_oid ourId = ourSide.git_index_entry->id; + GTOID *ourOID = [[GTOID alloc] initWithGitOid:&ourId]; + NSData *ourData = [[database objectWithOID:ourOID error: error] data]; + if (ourData == nil) { + return nil; + } + ourInput.ptr = ourData.bytes; + ourInput.size = ourData.length; + + + // initialize their merge file input + git_merge_file_input theirInput; + gitError = git_merge_file_init_input(&theirInput, GIT_MERGE_FILE_INPUT_VERSION); + if (gitError != GIT_OK) { + if (error != NULL) *error = [NSError git_errorFor:gitError description:@"Failed to create merge file input other side"]; + return nil; + } + + git_oid theirId = theirSide.git_index_entry->id; + GTOID *theirOID = [[GTOID alloc] initWithGitOid:&theirId]; + NSData *theirData = [[database objectWithOID:theirOID error: error] data]; + if (theirData == nil) { + return nil; + } + theirInput.ptr = theirData.bytes; + theirInput.size = theirData.length; + + + git_merge_file_result result; + gitError = git_merge_file(&result, &ancestorInput, &ourInput, &theirInput, nil); + if (gitError != GIT_OK) { + if (error != NULL) *error = [NSError git_errorFor:gitError description:@"Failed to create merge file"]; + return nil; + } + + NSString *mergedContent = [[NSString alloc] initWithBytes:result.ptr length:result.len encoding:NSUTF8StringEncoding]; + + git_merge_file_result_free(&result); + + return mergedContent; +} + +- (BOOL)annotatedCommit:(git_annotated_commit **)annotatedCommit fromCommit:(GTCommit *)fromCommit error:(NSError **)error { + int gitError = git_annotated_commit_lookup(annotatedCommit, self.git_repository, fromCommit.OID.git_oid); + if (gitError != GIT_OK) { + if (error != NULL) *error = [NSError git_errorFor:gitError description:@"Failed to lookup annotated commit for %@", fromCommit]; + return NO; + } + + return YES; +} + +- (BOOL)analyzeMerge:(GTMergeAnalysis *)analysis fromBranch:(GTBranch *)fromBranch error:(NSError **)error { + NSParameterAssert(analysis != NULL); + NSParameterAssert(fromBranch != nil); + + GTCommit *fromCommit = [fromBranch targetCommitWithError:error]; + if (!fromCommit) { + return NO; + } + + git_annotated_commit *annotatedCommit; + [self annotatedCommit:&annotatedCommit fromCommit:fromCommit error:error]; + + // Allow fast-forward or normal merge + git_merge_preference_t preference = GIT_MERGE_PREFERENCE_NONE; + + // Merge analysis + int gitError = git_merge_analysis((git_merge_analysis_t *)analysis, &preference, self.git_repository, (const git_annotated_commit **) &annotatedCommit, 1); + if (gitError != GIT_OK) { + if (error != NULL) *error = [NSError git_errorFor:gitError description:@"Failed to analyze merge"]; + return NO; + } + + // Cleanup + git_annotated_commit_free(annotatedCommit); + + return YES; +} + +@end diff --git a/ObjectiveGit/GTRepository+Private.h b/ObjectiveGit/GTRepository+Private.h index 9fc6577c9..f3341730c 100644 --- a/ObjectiveGit/GTRepository+Private.h +++ b/ObjectiveGit/GTRepository+Private.h @@ -8,7 +8,13 @@ #import "GTRepository.h" +NS_ASSUME_NONNULL_BEGIN + @interface GTRepository () -- (id)lookUpObjectByGitOid:(const git_oid *)oid objectType:(GTObjectType)type error:(NSError **)error; -- (id)lookUpObjectByGitOid:(const git_oid *)oid error:(NSError **)error; + +- (id _Nullable)lookUpObjectByGitOid:(const git_oid *)oid objectType:(GTObjectType)type error:(NSError **)error; +- (id _Nullable)lookUpObjectByGitOid:(const git_oid *)oid error:(NSError **)error; + @end + +NS_ASSUME_NONNULL_END diff --git a/ObjectiveGit/GTRepository+Pull.h b/ObjectiveGit/GTRepository+Pull.h new file mode 100644 index 000000000..cbc1f74fd --- /dev/null +++ b/ObjectiveGit/GTRepository+Pull.h @@ -0,0 +1,37 @@ +// +// GTRepository+Pull.h +// ObjectiveGitFramework +// +// Created by Ben Chatelain on 6/17/15. +// Copyright © 2015 GitHub, Inc. All rights reserved. +// + +#import "GTRepository.h" + +NS_ASSUME_NONNULL_BEGIN + +typedef void (^GTRemoteFetchTransferProgressBlock)(const git_transfer_progress *progress, BOOL *stop); + +@interface GTRepository (Pull) + +#pragma mark - Pull + +/// Pull a single branch from a remote. +/// +/// branch - The branch to pull. +/// remote - The remote to pull from. +/// options - Options applied to the fetch operation. +/// Recognized options are: +/// `GTRepositoryRemoteOptionsCredentialProvider` +/// `GTRepositoryRemoteOptionsFetchPrune` +/// `GTRepositoryRemoteOptionsDownloadTags` +/// error - The error if one occurred. Can be NULL. +/// progressBlock - An optional callback for monitoring progress. +/// +/// Returns YES if the pull was successful, NO otherwise (and `error`, if provided, +/// will point to an error describing what happened). +- (BOOL)pullBranch:(GTBranch *)branch fromRemote:(GTRemote *)remote withOptions:(NSDictionary * _Nullable)options error:(NSError **)error progress:(GTRemoteFetchTransferProgressBlock _Nullable)progressBlock; + +@end + +NS_ASSUME_NONNULL_END diff --git a/ObjectiveGit/GTRepository+Pull.m b/ObjectiveGit/GTRepository+Pull.m new file mode 100644 index 000000000..b99bf37ce --- /dev/null +++ b/ObjectiveGit/GTRepository+Pull.m @@ -0,0 +1,55 @@ +// +// GTRepository+Pull.m +// ObjectiveGitFramework +// +// Created by Ben Chatelain on 6/17/15. +// Copyright © 2015 GitHub, Inc. All rights reserved. +// + +#import "GTRepository+Pull.h" + +#import "GTCommit.h" +#import "GTRepository+RemoteOperations.h" +#import "NSError+Git.h" +#import "git2/errors.h" +#import "GTRepository+Merging.h" + +NSString * const GTPullMergeConflictedFiles = @"GTPullMergeConflictedFiles"; + +@implementation GTRepository (Pull) + +#pragma mark - Pull + +- (BOOL)pullBranch:(GTBranch *)branch fromRemote:(GTRemote *)remote withOptions:(NSDictionary *)options error:(NSError **)error progress:(GTRemoteFetchTransferProgressBlock)progressBlock { + NSParameterAssert(branch != nil); + NSParameterAssert(remote != nil); + + GTRepository *repo = branch.repository; + + if (![self fetchRemote:remote withOptions:options error:error progress:progressBlock]) { + return NO; + } + + // Get tracking branch after fetch so that it is up-to-date and doesn't need to be refreshed from disk + GTBranch *trackingBranch; + if (branch.branchType == GTBranchTypeLocal) { + BOOL success = NO; + trackingBranch = [branch trackingBranchWithError:error success:&success]; + if (!success) { + if (error != NULL) *error = [NSError git_errorFor:GIT_ERROR description:@"Tracking branch not found for %@", branch.name]; + return NO; + } + else if (!trackingBranch) { + // Error should already be provided by libgit2 + return NO; + } + } + else { + // When given a remote branch, use it as the tracking branch + trackingBranch = branch; + } + + return [repo mergeBranchIntoCurrentBranch:trackingBranch withError:error]; +} + +@end diff --git a/ObjectiveGit/GTRepository+References.h b/ObjectiveGit/GTRepository+References.h new file mode 100644 index 000000000..cfddac2fc --- /dev/null +++ b/ObjectiveGit/GTRepository+References.h @@ -0,0 +1,27 @@ +// +// GTRepository+References.h +// ObjectiveGitFramework +// +// Created by Josh Abernathy on 6/4/15. +// Copyright (c) 2015 GitHub, Inc. All rights reserved. +// + +#import "GTRepository.h" + +NS_ASSUME_NONNULL_BEGIN + +@class GTReference; + +@interface GTRepository (References) + +/// Look up a reference by name. +/// +/// name - The name of the reference to look up. Cannot be nil. +/// error - The error if one occurs. May be NULL. +/// +/// Returns the reference or nil if look up failed. +- (GTReference * _Nullable)lookUpReferenceWithName:(NSString *)name error:(NSError **)error; + +@end + +NS_ASSUME_NONNULL_END diff --git a/ObjectiveGit/GTRepository+References.m b/ObjectiveGit/GTRepository+References.m new file mode 100644 index 000000000..1494d7539 --- /dev/null +++ b/ObjectiveGit/GTRepository+References.m @@ -0,0 +1,30 @@ +// +// GTRepository+References.m +// ObjectiveGitFramework +// +// Created by Josh Abernathy on 6/4/15. +// Copyright (c) 2015 GitHub, Inc. All rights reserved. +// + +#import "GTRepository+References.h" +#import "GTReference.h" +#import "NSError+Git.h" + +#import "git2/errors.h" + +@implementation GTRepository (References) + +- (GTReference *)lookUpReferenceWithName:(NSString *)name error:(NSError **)error { + NSParameterAssert(name != nil); + + git_reference *ref = NULL; + int gitError = git_reference_lookup(&ref, self.git_repository, name.UTF8String); + if (gitError != GIT_OK) { + if (error != NULL) *error = [NSError git_errorFor:gitError description:@"Failed to lookup reference %@.", name]; + return nil; + } + + return [[GTReference alloc] initWithGitReference:ref repository:self]; +} + +@end diff --git a/ObjectiveGit/GTRepository+RemoteOperations.h b/ObjectiveGit/GTRepository+RemoteOperations.h index f824f4651..d93ebaad7 100644 --- a/ObjectiveGit/GTRepository+RemoteOperations.h +++ b/ObjectiveGit/GTRepository+RemoteOperations.h @@ -7,31 +7,58 @@ // #import "GTRepository.h" +#import "git2/remote.h" + +@class GTFetchHeadEntry; + +NS_ASSUME_NONNULL_BEGIN /// A `GTCredentialProvider`, that will be used to authenticate against the remote. extern NSString *const GTRepositoryRemoteOptionsCredentialProvider; -@class GTFetchHeadEntry; +/// A `GTFetchPruneOption`, that will be used to determine if the fetch should prune or not. +extern NSString *const GTRepositoryRemoteOptionsFetchPrune; + +/// A `GTRemoteAutoTagOption`, that will be used to determine how the fetch should handle tags. +extern NSString *const GTRepositoryRemoteOptionsDownloadTags; + +/// A `@(BOOL)`, indicating git notes should also be pushed to the default notes reference name (if `@(YES)`), or an `NSArray(NSString)` containing reference names to be pushed through. +extern NSString *const GTRepositoryRemoteOptionsPushNotes; + +/// An enum describing the data needed for pruning. +/// See `git_fetch_prune_t`. +typedef NS_ENUM(NSInteger, GTFetchPruneOption) { + GTFetchPruneOptionUnspecified = GIT_FETCH_PRUNE_UNSPECIFIED, + GTFetchPruneOptionYes = GIT_FETCH_PRUNE, + GTFetchPruneOptionNo = GIT_FETCH_NO_PRUNE, +}; @interface GTRepository (RemoteOperations) +#pragma mark - Fetch + /// Fetch a remote. /// -/// remote - The remote to fetch from. -/// options - Options applied to the fetch operation. +/// remote - The remote to fetch from. Must not be nil. +/// options - Options applied to the fetch operation. May be nil. /// Recognized options are : /// `GTRepositoryRemoteOptionsCredentialProvider` +/// `GTRepositoryRemoteOptionsFetchPrune` +/// `GTRepositoryRemoteOptionsDownloadTags` /// error - The error if one occurred. Can be NULL. +/// progressBlock - Optional callback to receive fetch progress stats during the +/// transfer. May be nil. /// /// Returns YES if the fetch was successful, NO otherwise (and `error`, if provided, /// will point to an error describing what happened). -- (BOOL)fetchRemote:(GTRemote *)remote withOptions:(NSDictionary *)options error:(NSError **)error progress:(void (^)(const git_transfer_progress *stats, BOOL *stop))progressBlock; +- (BOOL)fetchRemote:(GTRemote *)remote withOptions:(NSDictionary * _Nullable)options error:(NSError **)error progress:(void (^ _Nullable)(const git_transfer_progress *stats, BOOL *stop))progressBlock; /// Enumerate all available fetch head entries. /// /// error - The error if one ocurred. Can be NULL. -/// block - A block to execute for each FETCH_HEAD entry. `fetchHeadEntry` will be the current -/// fetch head entry. Setting `stop` to YES will cause enumeration to stop after the block returns. +/// block - A block to execute for each FETCH_HEAD entry. `fetchHeadEntry` will +/// be the current fetch head entry. Setting `stop` to YES will cause +/// enumeration to stop after the block returns. Must not be nil. /// /// Returns YES if the operation succedded, NO otherwise. - (BOOL)enumerateFetchHeadEntriesWithError:(NSError **)error usingBlock:(void (^)(GTFetchHeadEntry *fetchHeadEntry, BOOL *stop))block; @@ -40,7 +67,67 @@ extern NSString *const GTRepositoryRemoteOptionsCredentialProvider; /// /// error - The error if one ocurred. Can be NULL. /// -/// Retruns an array with GTFetchHeadEntry objects -- (NSArray *)fetchHeadEntriesWithError:(NSError **)error; +/// Retruns a (possibly empty) array with GTFetchHeadEntry objects. Will not be nil. +- (NSArray *)fetchHeadEntriesWithError:(NSError **)error; + +#pragma mark - Push + +/// Push a single branch to a remote. +/// +/// branch - The branch to push. Must not be nil. +/// remote - The remote to push to. Must not be nil. +/// options - Options applied to the push operation. Can be NULL. +/// Recognized options are: +/// `GTRepositoryRemoteOptionsCredentialProvider` +/// `GTRepositoryRemoteOptionsPushNotes` (to push together with notes in one push) +/// error - The error if one occurred. Can be NULL. +/// progressBlock - An optional callback for monitoring progress. May be NULL. +/// +/// Returns YES if the push was successful, NO otherwise (and `error`, if provided, +/// will point to an error describing what happened). +- (BOOL)pushBranch:(GTBranch *)branch toRemote:(GTRemote *)remote withOptions:(NSDictionary * _Nullable)options error:(NSError **)error progress:(void (^ _Nullable)(unsigned int current, unsigned int total, size_t bytes, BOOL *stop))progressBlock; +/// Push an array of branches to a remote. +/// +/// branches - An array of branches to push. Must not be nil. +/// remote - The remote to push to. Must not be nil. +/// options - Options applied to the push operation. Can be NULL. +/// Recognized options are: +/// `GTRepositoryRemoteOptionsCredentialProvider`, +/// `GTRepositoryRemoteOptionsPushNotes` (to push together with notes in one push) +/// error - The error if one occurred. Can be NULL. +/// progressBlock - An optional callback for monitoring progress. May be NULL. +/// +/// Returns YES if the push was successful, NO otherwise (and `error`, if provided, +/// will point to an error describing what happened). +- (BOOL)pushBranches:(NSArray *)branches toRemote:(GTRemote *)remote withOptions:(NSDictionary * _Nullable)options error:(NSError **)error progress:(void (^ _Nullable)(unsigned int current, unsigned int total, size_t bytes, BOOL *stop))progressBlock; + +/// Push a given Git notes reference name to a remote. +/// +/// noteReferenceName - Name of the notes reference. If NULL, will default to whatever the default is (e.g. "refs/notes/commits") +/// remote - The remote to push to. Must not be nil. +/// options - Options applied to the push operation. Can be NULL. +/// Recognized options are: +/// `GTRepositoryRemoteOptionsCredentialProvider` +/// error - The error if one occurred. Can be NULL. +/// progressBlock - An optional callback for monitoring progress. May be NULL. +/// +/// Returns YES if the push was successful, NO otherwise (and `error`, if provided, +/// will point to an error describing what happened). +- (BOOL)pushNotes:(NSString * _Nullable)noteReferenceName toRemote:(GTRemote *)remote withOptions:(NSDictionary * _Nullable)options error:(NSError **)error progress:(void (^ _Nullable)(unsigned int current, unsigned int total, size_t bytes, BOOL *stop))progressBlock; + +/// Delete a remote branch +/// +/// branch - The branch to push. Must not be nil. +/// remote - The remote to push to. Must not be nil. +/// options - Options applied to the push operation. Can be NULL. +/// Recognized options are: +/// `GTRepositoryRemoteOptionsCredentialProvider` +/// error - The error if one occurred. Can be NULL. +/// +/// Returns YES if the push was successful, NO otherwise (and `error`, if provided, +/// will point to an error describing what happened). +- (BOOL)deleteBranch:(GTBranch *)branch fromRemote:(GTRemote *)remote withOptions:(NSDictionary * _Nullable)options error:(NSError **)error; @end + +NS_ASSUME_NONNULL_END diff --git a/ObjectiveGit/GTRepository+RemoteOperations.m b/ObjectiveGit/GTRepository+RemoteOperations.m index 21f4457ee..822171ab9 100644 --- a/ObjectiveGit/GTRepository+RemoteOperations.m +++ b/ObjectiveGit/GTRepository+RemoteOperations.m @@ -15,23 +15,33 @@ #import "GTOID.h" #import "GTRemote.h" #import "GTSignature.h" +#import "NSArray+StringArray.h" #import "NSError+Git.h" +#import "GTRepository+References.h" +#import "GTNote.h" #import "git2/errors.h" +#import "git2/remote.h" +#import "git2/notes.h" +#import "git2/buffer.h" NSString *const GTRepositoryRemoteOptionsCredentialProvider = @"GTRepositoryRemoteOptionsCredentialProvider"; +NSString *const GTRepositoryRemoteOptionsFetchPrune = @"GTRepositoryRemoteOptionsFetchPrune"; +NSString *const GTRepositoryRemoteOptionsDownloadTags = @"GTRepositoryRemoteOptionsDownloadTags"; +NSString *const GTRepositoryRemoteOptionsPushNotes = @"GTRepositoryRemoteOptionsPushNotes"; + +typedef void (^GTRemoteFetchTransferProgressBlock)(const git_transfer_progress *stats, BOOL *stop); +typedef void (^GTRemotePushTransferProgressBlock)(unsigned int current, unsigned int total, size_t bytes, BOOL *stop); @implementation GTRepository (RemoteOperations) #pragma mark - #pragma mark Common Remote code -typedef void (^GTRemoteFetchTransferProgressBlock)(const git_transfer_progress *stats, BOOL *stop); - typedef struct { GTCredentialAcquireCallbackInfo credProvider; __unsafe_unretained GTRemoteFetchTransferProgressBlock fetchProgressBlock; - __unsafe_unretained GTRemoteFetchTransferProgressBlock pushProgressBlock; + __unsafe_unretained GTRemotePushTransferProgressBlock pushProgressBlock; git_direction direction; } GTRemoteConnectionInfo; @@ -46,10 +56,21 @@ int GTRemoteFetchTransferProgressCallback(const git_transfer_progress *stats, vo return (stop == YES ? GIT_EUSER : 0); } -#pragma mark - -#pragma mark Fetch +int GTRemotePushTransferProgressCallback(unsigned int current, unsigned int total, size_t bytes, void *payload) { + GTRemoteConnectionInfo *pushPayload = payload; + + BOOL stop = NO; + if (pushPayload->pushProgressBlock) { + pushPayload->pushProgressBlock(current, total, bytes, &stop); + } + + return (stop == YES ? GIT_EUSER : 0); +} + +#pragma mark - Fetch - (BOOL)fetchRemote:(GTRemote *)remote withOptions:(NSDictionary *)options error:(NSError **)error progress:(GTRemoteFetchTransferProgressBlock)progressBlock { + GTCredentialProvider *credProvider = options[GTRepositoryRemoteOptionsCredentialProvider]; GTRemoteConnectionInfo connectionInfo = { .credProvider = {credProvider}, @@ -63,14 +84,13 @@ - (BOOL)fetchRemote:(GTRemote *)remote withOptions:(NSDictionary *)options error .payload = &connectionInfo, }; - int gitError = git_remote_set_callbacks(remote.git_remote, &remote_callbacks); - if (gitError != GIT_OK) { - if (error != NULL) *error = [NSError git_errorFor:gitError description:@"Failed to set callbacks on remote"]; - return NO; - } + git_fetch_options fetchOptions = GIT_FETCH_OPTIONS_INIT; + fetchOptions.callbacks = remote_callbacks; + fetchOptions.prune = [options[GTRepositoryRemoteOptionsFetchPrune] unsignedIntValue]; + fetchOptions.download_tags = [options[GTRepositoryRemoteOptionsDownloadTags] unsignedIntValue]; __block git_strarray refspecs; - gitError = git_remote_get_fetch_refspecs(&refspecs, remote.git_remote); + int gitError = git_remote_get_fetch_refspecs(&refspecs, remote.git_remote); if (gitError != GIT_OK) { if (error != NULL) *error = [NSError git_errorFor:gitError description:@"Failed to get fetch refspecs for remote"]; return NO; @@ -80,7 +100,9 @@ - (BOOL)fetchRemote:(GTRemote *)remote withOptions:(NSDictionary *)options error git_strarray_free(&refspecs); }; - gitError = git_remote_fetch(remote.git_remote, &refspecs, self.userSignatureForNow.git_signature, NULL); + NSString *reflog_message = [NSString stringWithFormat:@"fetching remote %@", remote.name]; + + gitError = git_remote_fetch(remote.git_remote, &refspecs, &fetchOptions, reflog_message.UTF8String); if (gitError != GIT_OK) { if (error != NULL) *error = [NSError git_errorFor:gitError description:@"Failed to fetch from remote"]; return NO; @@ -89,8 +111,7 @@ - (BOOL)fetchRemote:(GTRemote *)remote withOptions:(NSDictionary *)options error return YES; } -#pragma mark - -#pragma mark Fetch Head enumeration +#pragma mark - Fetch Head Enumeration typedef void (^GTRemoteEnumerateFetchHeadEntryBlock)(GTFetchHeadEntry *entry, BOOL *stop); @@ -105,9 +126,15 @@ int GTFetchHeadEntriesCallback(const char *ref_name, const char *remote_url, con GTRepository *repository = entriesPayload->repository; GTRemoteEnumerateFetchHeadEntryBlock enumerationBlock = entriesPayload->enumerationBlock; - GTReference *reference = [GTReference referenceByLookingUpReferencedNamed:@(ref_name) inRepository:repository error:NULL]; + NSString *refName = @(ref_name); + NSCAssert(refName, @"refName is nil"); + + NSString *remoteURL = @(remote_url); + NSCAssert(remote_url, @"remoteURL is nil"); + + GTReference *reference = [repository lookUpReferenceWithName:refName error:NULL]; - GTFetchHeadEntry *entry = [[GTFetchHeadEntry alloc] initWithReference:reference remoteURLString:@(remote_url) targetOID:[GTOID oidWithGitOid:oid] isMerge:(BOOL)is_merge]; + GTFetchHeadEntry *entry = [[GTFetchHeadEntry alloc] initWithReference:reference remoteURLString:remoteURL targetOID:[GTOID oidWithGitOid:oid] isMerge:(BOOL)is_merge]; BOOL stop = NO; @@ -145,4 +172,149 @@ - (NSArray *)fetchHeadEntriesWithError:(NSError **)error { return entries; } +#pragma mark - Push (Public) + +- (BOOL)pushBranch:(GTBranch *)branch toRemote:(GTRemote *)remote withOptions:(NSDictionary *)options error:(NSError **)error progress:(GTRemotePushTransferProgressBlock)progressBlock { + NSParameterAssert(branch != nil); + NSParameterAssert(remote != nil); + + return [self pushBranches:@[ branch ] toRemote:remote withOptions:options error:error progress:progressBlock]; +} + +- (BOOL)pushBranches:(NSArray *)branches toRemote:(GTRemote *)remote withOptions:(NSDictionary *)options error:(NSError **)error progress:(GTRemotePushTransferProgressBlock)progressBlock { + NSParameterAssert(branches != nil); + NSParameterAssert(branches.count != 0); + NSParameterAssert(remote != nil); + + NSMutableArray *refspecs = nil; + // Build refspecs for the passed in branches + refspecs = [NSMutableArray arrayWithCapacity:branches.count]; + for (GTBranch *branch in branches) { + // Default remote reference for when branch doesn't exist on remote - create with same short name + NSString *remoteBranchReference = [NSString stringWithFormat:@"refs/heads/%@", branch.shortName]; + + BOOL success = NO; + GTBranch *trackingBranch = [branch trackingBranchWithError:error success:&success]; + + if (success && trackingBranch != nil) { + // Use remote branch short name from trackingBranch, which could be different + // (e.g. refs/heads/master:refs/heads/my_master) + remoteBranchReference = [NSString stringWithFormat:@"refs/heads/%@", trackingBranch.shortName]; + } + + [refspecs addObject:[NSString stringWithFormat:@"refs/heads/%@:%@", branch.shortName, remoteBranchReference]]; + } + + // Also push the notes reference(s), if needed. + id pushNotesOption = options[GTRepositoryRemoteOptionsPushNotes]; + if (pushNotesOption != nil) { + if ([pushNotesOption isKindOfClass:[NSNumber class]]) { // Push notes is a bool, only push the default reference name if it's YES + if ([(NSNumber *)pushNotesOption boolValue]) { + NSString *notesReferenceName = [GTNote defaultReferenceNameForRepository:self error:nil]; + + // Check whether the reference name exists for the repo, or our push will fail + if (notesReferenceName != nil && [self lookUpReferenceWithName:notesReferenceName error:nil] != nil) { + [refspecs addObject:[NSString stringWithFormat:@"%@:%@", notesReferenceName, notesReferenceName]]; + } + } + } else if ([pushNotesOption isKindOfClass:[NSArray class]]) { + for (NSString *notesReferenceName in (NSArray *)pushNotesOption) { + if ([notesReferenceName isKindOfClass:[NSString class]]) { // Just a sanity check, we only accept NSStrings in the array + // Check whether the reference name exists for the repo, or our push will fail + if (notesReferenceName != nil && [self lookUpReferenceWithName:notesReferenceName error:nil] != nil) { + [refspecs addObject:[NSString stringWithFormat:@"%@:%@", notesReferenceName, notesReferenceName]]; + } + } + } + } + } + + return [self pushRefspecs:refspecs toRemote:remote withOptions:options error:error progress:progressBlock]; +} + +- (BOOL)pushNotes:(NSString *)noteRef toRemote:(GTRemote *)remote withOptions:(NSDictionary *)options error:(NSError **)error progress:(GTRemotePushTransferProgressBlock)progressBlock { + NSParameterAssert(remote != nil); + + if (noteRef == nil) { + noteRef = [GTNote defaultReferenceNameForRepository:self error:error]; + + if (noteRef == nil) return NO; + } + + GTReference *notesReference = [self lookUpReferenceWithName:noteRef error:error]; + + if (notesReference == nil) return NO; + + return [self pushRefspecs:@[[NSString stringWithFormat:@"%@:%@", noteRef, noteRef]] toRemote:remote withOptions:options error:error progress:progressBlock]; +} + +#pragma mark - Deletion (Public) +- (BOOL)deleteBranch:(GTBranch *)branch fromRemote:(GTRemote *)remote withOptions:(NSDictionary *)options error:(NSError **)error { + NSParameterAssert(branch != nil); + NSParameterAssert(remote != nil); + + NSArray *refspecs = @[ [NSString stringWithFormat:@":refs/heads/%@", branch.shortName] ]; + + return [self pushRefspecs:refspecs toRemote:remote withOptions:options error:error progress:nil]; +} + +#pragma mark - Push (Private) + +- (BOOL)pushRefspecs:(NSArray *)refspecs toRemote:(GTRemote *)remote withOptions:(NSDictionary *)options error:(NSError **)error progress:(GTRemotePushTransferProgressBlock)progressBlock { + + int gitError; + GTCredentialProvider *credProvider = options[GTRepositoryRemoteOptionsCredentialProvider]; + + GTRemoteConnectionInfo connectionInfo = { + .credProvider = { .credProvider = credProvider }, + .direction = GIT_DIRECTION_PUSH, + .pushProgressBlock = progressBlock, + }; + + git_remote_callbacks remote_callbacks = GIT_REMOTE_CALLBACKS_INIT; + remote_callbacks.credentials = (credProvider != nil ? GTCredentialAcquireCallback : NULL); + remote_callbacks.push_transfer_progress = GTRemotePushTransferProgressCallback; + remote_callbacks.payload = &connectionInfo; + + gitError = git_remote_connect(remote.git_remote, GIT_DIRECTION_PUSH, &remote_callbacks, NULL, NULL); + if (gitError != GIT_OK) { + if (error != NULL) *error = [NSError git_errorFor:gitError description:@"Failed to connect remote"]; + return NO; + } + @onExit { + git_remote_disconnect(remote.git_remote); + }; + + git_push_options push_options = GIT_PUSH_OPTIONS_INIT; + + gitError = git_push_init_options(&push_options, GIT_PUSH_OPTIONS_VERSION); + if (gitError != GIT_OK) { + if (error != NULL) *error = [NSError git_errorFor:gitError description:@"Failed to init push options"]; + return NO; + } + + push_options.callbacks = remote_callbacks; + + const git_strarray git_refspecs = refspecs.git_strarray; + + gitError = git_remote_upload(remote.git_remote, &git_refspecs, &push_options); + if (gitError != GIT_OK) { + if (error != NULL) *error = [NSError git_errorFor:gitError description:@"Push upload to remote failed"]; + return NO; + } + + int update_fetchhead = 1; + // Ignored for push + git_remote_autotag_option_t download_tags = GIT_REMOTE_DOWNLOAD_TAGS_UNSPECIFIED; + NSString *reflog_message = [NSString stringWithFormat:@"pushing remote %@", remote.name]; + + gitError = git_remote_update_tips(remote.git_remote, &remote_callbacks, update_fetchhead, download_tags, reflog_message.UTF8String); + if (gitError != GIT_OK) { + if (error != NULL) *error = [NSError git_errorFor:gitError description:@"Update tips failed"]; + return NO; + } + + return YES; +} + @end diff --git a/ObjectiveGit/GTRepository+Reset.h b/ObjectiveGit/GTRepository+Reset.h index f43cdb97f..cbb06158a 100644 --- a/ObjectiveGit/GTRepository+Reset.h +++ b/ObjectiveGit/GTRepository+Reset.h @@ -17,6 +17,8 @@ typedef NS_ENUM(NSInteger, GTRepositoryResetType) { GTRepositoryResetTypeHard = GIT_RESET_HARD, }; +NS_ASSUME_NONNULL_BEGIN + @interface GTRepository (Reset) /// Reset the repository's HEAD to the given commit. @@ -35,6 +37,8 @@ typedef NS_ENUM(NSInteger, GTRepositoryResetType) { /// error - The error if one occurred. /// /// Returns whether the reset was successful. -- (BOOL)resetPathspecs:(NSArray *)pathspecs toCommit:(GTCommit *)commit error:(NSError **)error; +- (BOOL)resetPathspecs:(NSArray *)pathspecs toCommit:(GTCommit *)commit error:(NSError **)error; @end + +NS_ASSUME_NONNULL_END diff --git a/ObjectiveGit/GTRepository+Reset.m b/ObjectiveGit/GTRepository+Reset.m index ebf794fce..71d24b1f0 100644 --- a/ObjectiveGit/GTRepository+Reset.m +++ b/ObjectiveGit/GTRepository+Reset.m @@ -20,7 +20,7 @@ - (BOOL)resetToCommit:(GTCommit *)commit resetType:(GTRepositoryResetType)resetT NSParameterAssert(commit != nil); git_checkout_options options = GIT_CHECKOUT_OPTIONS_INIT; - int gitError = git_reset(self.git_repository, commit.git_object, (git_reset_t)resetType, &options, (git_signature *)[self userSignatureForNow].git_signature, NULL); + int gitError = git_reset(self.git_repository, commit.git_object, (git_reset_t)resetType, &options); if (gitError != GIT_OK) { if (error != NULL) { *error = [NSError git_errorFor:gitError description:@"Failed to reset repository to commit %@.", commit.SHA]; diff --git a/ObjectiveGit/GTRepository+Stashing.h b/ObjectiveGit/GTRepository+Stashing.h index 925bbeef5..a7dc57b34 100644 --- a/ObjectiveGit/GTRepository+Stashing.h +++ b/ObjectiveGit/GTRepository+Stashing.h @@ -19,6 +19,29 @@ typedef NS_OPTIONS(NSInteger, GTRepositoryStashFlag) { GTRepositoryStashFlagIncludeIgnored = GIT_STASH_INCLUDE_IGNORED }; +/// Flags for -applyStashAtIndex:flags:error: and +/// -popStashAtIndex:flags:error. +/// Those can be ORed together. See git_stash_apply_flags for additional information. +typedef NS_OPTIONS(NSInteger, GTRepositoryStashApplyFlag) { + GTRepositoryStashApplyFlagDefault = GIT_STASH_APPLY_DEFAULT, + GTRepositoryStashApplyFlagReinstateIndex = GIT_STASH_APPLY_REINSTATE_INDEX, +}; + +/// Enum representing the current state of a stash apply/pop operation. +/// See git_stash_apply_progress_t for additional information. +typedef NS_ENUM(NSInteger, GTRepositoryStashApplyProgress) { + GTRepositoryStashApplyProgressNone = GIT_STASH_APPLY_PROGRESS_NONE, + GTRepositoryStashApplyProgressLoadingStash = GIT_STASH_APPLY_PROGRESS_LOADING_STASH, + GTRepositoryStashApplyProgressAnalyzeIndex = GIT_STASH_APPLY_PROGRESS_ANALYZE_INDEX, + GTRepositoryStashApplyProgressAnalyzeModified = GIT_STASH_APPLY_PROGRESS_ANALYZE_MODIFIED, + GTRepositoryStashApplyProgressAnalyzeUntracked = GIT_STASH_APPLY_PROGRESS_ANALYZE_UNTRACKED, + GTRepositoryStashApplyProgressCheckoutUntracked = GIT_STASH_APPLY_PROGRESS_CHECKOUT_UNTRACKED, + GTRepositoryStashApplyProgressCheckoutModified = GIT_STASH_APPLY_PROGRESS_CHECKOUT_MODIFIED, + GTRepositoryStashApplyProgressDone = GIT_STASH_APPLY_PROGRESS_DONE, +}; + +NS_ASSUME_NONNULL_BEGIN + @interface GTRepository (Stashing) /// Stash the repository's changes. @@ -30,14 +53,36 @@ typedef NS_OPTIONS(NSInteger, GTRepositoryStashFlag) { /// /// Returns a commit representing the stashed changes if successful, or nil /// otherwise. -- (GTCommit *)stashChangesWithMessage:(NSString *)message flags:(GTRepositoryStashFlag)flags error:(NSError **)error; +- (GTCommit * _Nullable)stashChangesWithMessage:(NSString * _Nullable)message flags:(GTRepositoryStashFlag)flags error:(NSError **)error; /// Enumerate over all the stashes in the repository, from most recent to oldest. /// /// block - A block to execute for each stash found. `index` will be the zero-based /// stash index (where 0 is the most recent stash). Setting `stop` to YES -/// will cause enumeration to stop after the block returns. -- (void)enumerateStashesUsingBlock:(void (^)(NSUInteger index, NSString *message, GTOID *oid, BOOL *stop))block; +/// will cause enumeration to stop after the block returns. Must not be nil. +- (void)enumerateStashesUsingBlock:(void (^)(NSUInteger index, NSString * _Nullable message, GTOID * _Nullable oid, BOOL *stop))block; + +/// Apply stashed changes. +/// +/// index - The index of the stash to apply. 0 is the latest one. +/// flags - The flags to use when applying the stash. +/// options - The options to use when checking out (if nil, use the defaults provided by libgit2). +/// error - If not NULL, set to any error that occurred. +/// progressBlock - A block that will be executed on each step of the stash application. +/// +/// Returns YES if the requested stash was successfully applied, NO otherwise. +- (BOOL)applyStashAtIndex:(NSUInteger)index flags:(GTRepositoryStashApplyFlag)flags checkoutOptions:(GTCheckoutOptions * _Nullable)options error:(NSError **)error progressBlock:(void (^ _Nullable)(GTRepositoryStashApplyProgress progress, BOOL *stop))progressBlock; + +/// Pop stashed changes. +/// +/// index - The index of the stash to apply. 0 is the most recent stash. +/// flags - The flags to use when applying the stash. +/// options - The options to use when checking out (if nil, use the defaults provided by libgit2). +/// error - If not NULL, set to any error that occurred. +/// progressBlock - A block that will be executed on each step of the stash application. +/// +/// Returns YES if the requested stash was successfully applied, NO otherwise. +- (BOOL)popStashAtIndex:(NSUInteger)index flags:(GTRepositoryStashApplyFlag)flags checkoutOptions:(GTCheckoutOptions * _Nullable)options error:(NSError **)error progressBlock:(void (^ _Nullable)(GTRepositoryStashApplyProgress progress, BOOL *stop))progressBlock; /// Drop a stash from the repository's list of stashes. /// @@ -48,3 +93,5 @@ typedef NS_OPTIONS(NSInteger, GTRepositoryStashFlag) { - (BOOL)dropStashAtIndex:(NSUInteger)index error:(NSError **)error; @end + +NS_ASSUME_NONNULL_END diff --git a/ObjectiveGit/GTRepository+Stashing.m b/ObjectiveGit/GTRepository+Stashing.m index 1db98875a..e5903a87f 100644 --- a/ObjectiveGit/GTRepository+Stashing.m +++ b/ObjectiveGit/GTRepository+Stashing.m @@ -26,13 +26,13 @@ - (GTCommit *)stashChangesWithMessage:(NSString *)message flags:(GTRepositorySta if (error != NULL) *error = [NSError git_errorFor:gitError description:@"Failed to stash."]; return nil; } - + return [self lookUpObjectByGitOid:&git_oid error:error]; } static int stashEnumerationCallback(size_t index, const char *message, const git_oid *stash_id, void *payload) { GTRepositoryStashEnumerationBlock block = (__bridge GTRepositoryStashEnumerationBlock)payload; - + NSString *messageString = nil; if (message != NULL) messageString = @(message); @@ -40,20 +40,73 @@ static int stashEnumerationCallback(size_t index, const char *message, const git BOOL stop = NO; block(index, messageString, stashOID, &stop); - + return (stop ? GIT_EUSER : 0); } - (void)enumerateStashesUsingBlock:(GTRepositoryStashEnumerationBlock)block { NSParameterAssert(block != nil); - + git_stash_foreach(self.git_repository, &stashEnumerationCallback, (__bridge void *)block); } +static int stashApplyProgressCallback(git_stash_apply_progress_t progress, void *payload) { + void (^block)(GTRepositoryStashApplyProgress, BOOL *) = (__bridge id)payload; + + BOOL stop = NO; + block((GTRepositoryStashApplyProgress)progress, &stop); + + return (stop ? GIT_EUSER : 0); +} + +- (BOOL)applyStashAtIndex:(NSUInteger)index flags:(GTRepositoryStashApplyFlag)flags checkoutOptions:(GTCheckoutOptions *)options error:(NSError **)error progressBlock:(void (^)(GTRepositoryStashApplyProgress progress, BOOL *stop))progressBlock { + git_stash_apply_options stash_options = GIT_STASH_APPLY_OPTIONS_INIT; + + stash_options.flags = (git_stash_apply_flags)flags; + + if (progressBlock != nil) { + stash_options.progress_cb = stashApplyProgressCallback; + stash_options.progress_payload = (__bridge void *)progressBlock; + } + + if (options != nil) { + stash_options.checkout_options = *options.git_checkoutOptions; + } + + int gitError = git_stash_apply(self.git_repository, index, &stash_options); + if (gitError != GIT_OK) { + if (error != NULL) *error = [NSError git_errorFor:gitError description:@"Stash apply failed" failureReason:@"The stash at index %ld couldn't be applied.", (unsigned long)index]; + return NO; + } + return YES; +} + +- (BOOL)popStashAtIndex:(NSUInteger)index flags:(GTRepositoryStashApplyFlag)flags checkoutOptions:(GTCheckoutOptions *)options error:(NSError **)error progressBlock:(void (^)(GTRepositoryStashApplyProgress progress, BOOL *stop))progressBlock { + git_stash_apply_options stash_options = GIT_STASH_APPLY_OPTIONS_INIT; + + stash_options.flags = (git_stash_apply_flags)flags; + + if (progressBlock != nil) { + stash_options.progress_cb = stashApplyProgressCallback; + stash_options.progress_payload = (__bridge void *)progressBlock; + } + + if (options != nil) { + stash_options.checkout_options = *options.git_checkoutOptions; + } + + int gitError = git_stash_pop(self.git_repository, index, &stash_options); + if (gitError != GIT_OK) { + if (error != NULL) *error = [NSError git_errorFor:gitError description:@"Stash pop failed" failureReason:@"The stash at index %ld couldn't be applied.", (unsigned long)index]; + return NO; + } + return YES; +} + - (BOOL)dropStashAtIndex:(NSUInteger)index error:(NSError **)error { int gitError = git_stash_drop(self.git_repository, index); if (gitError != GIT_OK) { - if (error != NULL) *error = [NSError git_errorFor:gitError description:@"Failed to drop stash."]; + if (error != NULL) *error = [NSError git_errorFor:gitError description:@"Stash drop failed" failureReason:@"The stash at index %ld couldn't be dropped", (unsigned long)index]; return NO; } diff --git a/ObjectiveGit/GTRepository+Status.h b/ObjectiveGit/GTRepository+Status.h index e6c45c231..86d4121ca 100644 --- a/ObjectiveGit/GTRepository+Status.h +++ b/ObjectiveGit/GTRepository+Status.h @@ -12,6 +12,8 @@ @class GTStatusDelta; +NS_ASSUME_NONNULL_BEGIN + /// An enum representing the status of a file /// See git_status_t typedef NS_OPTIONS(NSInteger, GTFileStatusFlags) { @@ -111,12 +113,36 @@ extern NSString *const GTRepositoryStatusOptionsPathSpecArrayKey; /// /// Returns `NO` in case of a failure or `YES` if the enumeration completed /// successfully. -- (BOOL)enumerateFileStatusWithOptions:(NSDictionary *)options error:(NSError **)error usingBlock:(void (^)(GTStatusDelta *headToIndex, GTStatusDelta *indexToWorkingDirectory, BOOL *stop))block; +- (BOOL)enumerateFileStatusWithOptions:(NSDictionary * _Nullable)options error:(NSError **)error usingBlock:(void (^ _Nullable)(GTStatusDelta * _Nullable headToIndex, GTStatusDelta * _Nullable indexToWorkingDirectory, BOOL *stop))block; /// Query the status of one file -- (GTFileStatusFlags)statusForFile:(NSString *)filePath success:(BOOL *)success error:(NSError **)error; +/// +/// filePath - A string path relative to the working copy. The must not be nil. +/// success - If not NULL, will be set to indicate success or fail. +/// error - If not nil, set to any error that occurs. +/// +/// Returns the combined GTFileStatusFlags for the file. +- (GTFileStatusFlags)statusForFile:(NSString *)filePath success:(BOOL * _Nullable)success error:(NSError **)error; + +/// Tests the ignore rules to see if the file should be considered as ignored. +/// +/// fileURL - A local file URL for a file in the repository. Must not be nil. +/// success - If not NULL, will be set to indicate success or fail. +/// error - If not nil, set to any error that occurs. +/// +/// Returns YES if the file should be ignored; NO otherwise. +- (BOOL)shouldFileBeIgnored:(NSURL *)fileURL success:(BOOL * _Nullable)success error:(NSError **)error; + +/// An enum for use with shouldIgnoreFileURL:error: below +typedef NS_ENUM(NSInteger, GTFileIgnoreState) { + GTFileIgnoreStateIgnoreCheckFailed = -1, + GTFileIgnoreStateShouldNotIgnore = 0, + GTFileIgnoreStateShouldIgnore = 1 +}; -/// Should the file be considered as ignored ? -- (BOOL)shouldFileBeIgnored:(NSURL *)fileURL success:(BOOL *)success error:(NSError **)error; +/// Convenience wrapper for shouldFileBeIgnored:success:error: +- (GTFileIgnoreState)shouldIgnoreFileURL:(NSURL *)fileURL error:(NSError **)error; @end + +NS_ASSUME_NONNULL_END diff --git a/ObjectiveGit/GTRepository+Status.m b/ObjectiveGit/GTRepository+Status.m index 346cf82b0..7f2559134 100644 --- a/ObjectiveGit/GTRepository+Status.m +++ b/ObjectiveGit/GTRepository+Status.m @@ -68,23 +68,23 @@ - (BOOL)enumerateFileStatusWithOptions:(NSDictionary *)options error:(NSError ** - (BOOL)isWorkingDirectoryClean { __block BOOL clean = YES; [self enumerateFileStatusWithOptions:nil error:NULL usingBlock:^(GTStatusDelta *headToIndex, GTStatusDelta *indexToWorkingDirectory, BOOL *stop) { - GTStatusDeltaStatus headToIndexStatus = headToIndex.status; - GTStatusDeltaStatus indexToWorkDirStatus = indexToWorkingDirectory.status; + GTDeltaType headToIndexStatus = headToIndex.status; + GTDeltaType indexToWorkDirStatus = indexToWorkingDirectory.status; // first, have items been deleted? - if (indexToWorkDirStatus == GTStatusDeltaStatusDeleted || headToIndexStatus == GTStatusDeltaStatusDeleted) { + if (indexToWorkDirStatus == GTDeltaTypeDeleted || headToIndexStatus == GTDeltaTypeDeleted) { clean = NO; *stop = YES; } // any untracked files? - if (indexToWorkDirStatus == GTStatusDeltaStatusAdded) { + if (indexToWorkDirStatus == GTDeltaTypeUntracked) { clean = NO; *stop = YES; } // next, have items been modified? - if (indexToWorkDirStatus == GTStatusDeltaStatusModified || headToIndexStatus == GTStatusDeltaStatusModified) { + if (indexToWorkDirStatus == GTDeltaTypeModified || headToIndexStatus == GTDeltaTypeModified) { clean = NO; *stop = YES; } @@ -122,7 +122,16 @@ - (BOOL)shouldFileBeIgnored:(NSURL *)fileURL success:(BOOL *)success error:(NSEr } if (success != NULL) *success = YES; - return (ignoreState == 0 ? YES : NO); + return (ignoreState == 1 ? YES : NO); +} + +- (GTFileIgnoreState)shouldIgnoreFileURL:(NSURL *)fileURL error:(NSError **)error { + BOOL success = NO; + BOOL ignore = [self shouldFileBeIgnored:fileURL success:&success error:error]; + if (success) { + return (ignore ? GTFileIgnoreStateShouldIgnore : GTFileIgnoreStateShouldNotIgnore); + } + return GTFileIgnoreStateIgnoreCheckFailed; } @end diff --git a/ObjectiveGit/GTRepository.h b/ObjectiveGit/GTRepository.h index 8c45d0ab3..b57430b50 100644 --- a/ObjectiveGit/GTRepository.h +++ b/ObjectiveGit/GTRepository.h @@ -34,6 +34,7 @@ #import "GTObject.h" #import "GTReference.h" #import "GTFilterList.h" +#import "GTCheckoutOptions.h" #import "git2/checkout.h" #import "git2/repository.h" #import "git2/transport.h" @@ -51,36 +52,9 @@ @class GTTag; @class GTTree; @class GTRemote; +@class GTNote; -/// Checkout strategies used by the various -checkout... methods -/// See git_checkout_strategy_t -typedef NS_OPTIONS(NSInteger, GTCheckoutStrategyType) { - GTCheckoutStrategyNone = GIT_CHECKOUT_NONE, - GTCheckoutStrategySafe = GIT_CHECKOUT_SAFE, - GTCheckoutStrategySafeCreate = GIT_CHECKOUT_SAFE_CREATE, - GTCheckoutStrategyForce = GIT_CHECKOUT_FORCE, - GTCheckoutStrategyAllowConflicts = GIT_CHECKOUT_ALLOW_CONFLICTS, - GTCheckoutStrategyRemoveUntracked = GIT_CHECKOUT_REMOVE_UNTRACKED, - GTCheckoutStrategyRemoveIgnored = GIT_CHECKOUT_REMOVE_IGNORED, - GTCheckoutStrategyUpdateOnly = GIT_CHECKOUT_UPDATE_ONLY, - GTCheckoutStrategyDontUpdateIndex = GIT_CHECKOUT_DONT_UPDATE_INDEX, - GTCheckoutStrategyNoRefresh = GIT_CHECKOUT_NO_REFRESH, - GTCheckoutStrategyDisablePathspecMatch = GIT_CHECKOUT_DISABLE_PATHSPEC_MATCH, - GTCheckoutStrategySkipLockedDirectories = GIT_CHECKOUT_SKIP_LOCKED_DIRECTORIES, -}; - -/// Checkout notification flags used by the various -checkout... methods -/// See git_checkout_notify_t -typedef NS_OPTIONS(NSInteger, GTCheckoutNotifyFlags) { - GTCheckoutNotifyNone = GIT_CHECKOUT_NOTIFY_NONE, - GTCheckoutNotifyConflict = GIT_CHECKOUT_NOTIFY_CONFLICT, - GTCheckoutNotifyDirty = GIT_CHECKOUT_NOTIFY_DIRTY, - GTCheckoutNotifyUpdated = GIT_CHECKOUT_NOTIFY_UPDATED, - GTCheckoutNotifyUntracked = GIT_CHECKOUT_NOTIFY_UNTRACKED, - GTCheckoutNotifyIgnored = GIT_CHECKOUT_NOTIFY_IGNORED, - - GTCheckoutNotifyAll = GIT_CHECKOUT_NOTIFY_ALL, -}; +NS_ASSUME_NONNULL_BEGIN /// Transport flags sent as options to +cloneFromURL... method typedef NS_OPTIONS(NSInteger, GTTransportFlags) { @@ -97,7 +71,10 @@ extern NSString * const GTRepositoryCloneOptionsBare; /// An `NSNumber` wrapped `BOOL`, if NO, don't checkout the remote HEAD. /// Default value is `YES`. -extern NSString * const GTRepositoryCloneOptionsCheckout; +extern NSString * const GTRepositoryCloneOptionsPerformCheckout; + +/// A `GTCheckoutOptions` object describing how to perform the checkout. +extern NSString * const GTRepositoryCloneOptionsCheckoutOptions; /// A `GTCredentialProvider`, that will be used to authenticate against the /// remote. @@ -106,6 +83,19 @@ extern NSString * const GTRepositoryCloneOptionsCredentialProvider; /// A BOOL indicating whether local clones should actually clone, or just link. extern NSString * const GTRepositoryCloneOptionsCloneLocal; +/// A NSURL pointing to a local file that contains PEM-encoded certificate chain. +extern NSString * const GTRepositoryCloneOptionsServerCertificateURL; + +/// Repository extended open control flags for +/// +initWithURL:flags:ceilingDirs:error:. +/// +/// See respository.h for documentation of each individual flag. +typedef NS_OPTIONS(NSInteger, GTRepositoryOpenFlags) { + GTRepositoryOpenNoSearch = GIT_REPOSITORY_OPEN_NO_SEARCH, + GTRepositoryOpenCrossFS = GIT_REPOSITORY_OPEN_CROSS_FS, + GTRepositoryOpenBare = GIT_REPOSITORY_OPEN_BARE, +}; + /// Initialization flags associated with `GTRepositoryInitOptionsFlags` for /// +initializeEmptyRepositoryAtFileURL:options:error:. /// @@ -146,12 +136,27 @@ extern NSString * const GTRepositoryInitOptionsInitialHEAD; /// initialization. extern NSString * const GTRepositoryInitOptionsOriginURLString; +/// The possible states for the repository to be in, based on the current ongoing operation. +typedef NS_ENUM(NSInteger, GTRepositoryStateType) { + GTRepositoryStateNone = GIT_REPOSITORY_STATE_NONE, + GTRepositoryStateMerge = GIT_REPOSITORY_STATE_MERGE, + GTRepositoryStateRevert = GIT_REPOSITORY_STATE_REVERT, + GTRepositoryStateCherryPick = GIT_REPOSITORY_STATE_CHERRYPICK, + GTRepositoryStateBisect = GIT_REPOSITORY_STATE_BISECT, + GTRepositoryStateRebase = GIT_REPOSITORY_STATE_REBASE, + GTRepositoryStateRebaseInteractive = GIT_REPOSITORY_STATE_REBASE_INTERACTIVE, + GTRepositoryStateRebaseMerge = GIT_REPOSITORY_STATE_REBASE_MERGE, + GTRepositoryStateApplyMailbox = GIT_REPOSITORY_STATE_APPLY_MAILBOX, + GTRepositoryStateApplyMailboxOrRebase = GIT_REPOSITORY_STATE_APPLY_MAILBOX_OR_REBASE, +}; + @interface GTRepository : NSObject /// The file URL for the repository's working directory. -@property (nonatomic, readonly, strong) NSURL *fileURL; +/// Returns nil for a bare repository. +@property (nonatomic, readonly, strong) NSURL * _Nullable fileURL; /// The file URL for the repository's .git directory. -@property (nonatomic, readonly, strong) NSURL *gitDirectoryURL; +@property (nonatomic, readonly, strong) NSURL * _Nullable gitDirectoryURL; /// Is this a bare repository (one without a working directory)? @property (nonatomic, readonly, getter = isBare) BOOL bare; @@ -173,49 +178,77 @@ extern NSString * const GTRepositoryInitOptionsOriginURLString; /// error - The error if one occurs. /// /// Returns the initialized repository, or nil if an error occurred. -+ (instancetype)initializeEmptyRepositoryAtFileURL:(NSURL *)fileURL options:(NSDictionary *)options error:(NSError **)error; ++ (instancetype _Nullable)initializeEmptyRepositoryAtFileURL:(NSURL *)fileURL options:(NSDictionary * _Nullable)options error:(NSError **)error; + +/// Convenience class initializer which uses the default options. +/// +/// localFileURL - The file URL for the new repository. Cannot be nil. +/// error - The error if one occurs. +/// +/// Returns the initialized repository, or nil if an error occurred. ++ (instancetype _Nullable)repositoryWithURL:(NSURL *)localFileURL error:(NSError **)error; + +/// Convenience initializer which uses the default options. +/// +/// localFileURL - The file URL for the new repository. Cannot be nil. +/// error - The error if one occurs. +/// +/// Returns the initialized repository, or nil if an error occurred. +- (instancetype _Nullable)initWithURL:(NSURL *)localFileURL error:(NSError **)error; + +/// Convenience initializer to find and open a repository with extended controls. +/// +/// localFileURL - The file URL for the new repository. Cannot be nil. +/// flags - A combination of the `GTRepositoryOpenFlags` flags. +/// ceilingDirURLs - An array of URLs at which the search for a containing +/// repository should terminate. Can be NULL. +/// error - The error if one occurs. +/// +/// Returns the initialized repository, or nil if an error occurred. +- (instancetype _Nullable)initWithURL:(NSURL *)localFileURL flags:(NSInteger)flags ceilingDirs:(NSArray * _Nullable)ceilingDirURLs error:(NSError **)error; -+ (id)repositoryWithURL:(NSURL *)localFileURL error:(NSError **)error; -- (id)initWithURL:(NSURL *)localFileURL error:(NSError **)error; +- (instancetype)init NS_UNAVAILABLE; -/// Initializes the receiver to wrap the given repository object. +/// Initializes the receiver to wrap the given repository object. Designated initializer. /// /// repository - The repository to wrap. The receiver will take over memory /// management of this object, so it must not be freed elsewhere /// after this method is invoked. This must not be nil. /// -/// Returns an initialized GTRepository. -- (id)initWithGitRepository:(git_repository *)repository; +/// Returns an initialized GTRepository, or nil if an erroe occurred. +- (instancetype _Nullable)initWithGitRepository:(git_repository *)repository NS_DESIGNATED_INITIALIZER; /// The underlying `git_repository` object. - (git_repository *)git_repository __attribute__((objc_returns_inner_pointer)); /// Clone a repository /// -/// originURL - The URL to clone from. -/// workdirURL - A URL to the desired working directory on the local machine. +/// originURL - The URL to clone from. Must not be nil. +/// workdirURL - A URL to the desired working directory on the local machine. Must not be nil. /// options - A dictionary consisting of the options: /// `GTRepositoryCloneOptionsTransportFlags`, /// `GTRepositoryCloneOptionsBare`, -/// `GTRepositoryCloneOptionsCheckout`, +/// `GTRepositoryCloneOptionsPerformCheckout`, +/// `GTRepositoryCloneOptionsCheckoutOptions`, /// `GTRepositoryCloneOptionsCredentialProvider`, -/// `GTRepositoryCloneOptionsCloneLocal` +/// `GTRepositoryCloneOptionsCloneLocal`, +/// `GTRepositoryCloneOptionsServerCertificateURL` /// error - A pointer to fill in case of trouble. /// transferProgressBlock - This block is called with network transfer updates. -/// checkoutProgressBlock - This block is called with checkout updates -/// (if `GTRepositoryCloneOptionsCheckout` is YES). +/// May be NULL. +/// May be NULL. /// /// returns nil (and fills the error parameter) if an error occurred, or a GTRepository object if successful. -+ (id)cloneFromURL:(NSURL *)originURL toWorkingDirectory:(NSURL *)workdirURL options:(NSDictionary *)options error:(NSError **)error transferProgressBlock:(void (^)(const git_transfer_progress *))transferProgressBlock checkoutProgressBlock:(void (^)(NSString *path, NSUInteger completedSteps, NSUInteger totalSteps))checkoutProgressBlock; ++ (instancetype _Nullable)cloneFromURL:(NSURL *)originURL toWorkingDirectory:(NSURL *)workdirURL options:(NSDictionary * _Nullable)options error:(NSError **)error transferProgressBlock:(void (^ _Nullable)(const git_transfer_progress *, BOOL *stop))transferProgressBlock; /// Lookup objects in the repo by oid or sha1 -- (id)lookUpObjectByOID:(GTOID *)oid objectType:(GTObjectType)type error:(NSError **)error; -- (id)lookUpObjectByOID:(GTOID *)oid error:(NSError **)error; -- (id)lookUpObjectBySHA:(NSString *)sha objectType:(GTObjectType)type error:(NSError **)error; -- (id)lookUpObjectBySHA:(NSString *)sha error:(NSError **)error; +- (id _Nullable)lookUpObjectByOID:(GTOID *)oid objectType:(GTObjectType)type error:(NSError **)error; +- (id _Nullable)lookUpObjectByOID:(GTOID *)oid error:(NSError **)error; +- (id _Nullable)lookUpObjectBySHA:(NSString *)sha objectType:(GTObjectType)type error:(NSError **)error; +- (id _Nullable)lookUpObjectBySHA:(NSString *)sha error:(NSError **)error; /// Lookup an object in the repo using a revparse spec -- (id)lookUpObjectByRevParse:(NSString *)spec error:(NSError **)error; +- (id _Nullable)lookUpObjectByRevParse:(NSString *)spec error:(NSError **)error; /// Finds the branch with the given name and type. /// @@ -229,7 +262,7 @@ extern NSString * const GTRepositoryInitOptionsOriginURLString; /// /// Returns the matching branch, or nil if no match was found or an error occurs. /// The latter two cases can be distinguished by checking `success`. -- (GTBranch *)lookUpBranchWithName:(NSString *)branchName type:(GTBranchType)branchType success:(BOOL *)success error:(NSError **)error; +- (GTBranch * _Nullable)lookUpBranchWithName:(NSString *)branchName type:(GTBranchType)branchType success:(BOOL * _Nullable)success error:(NSError **)error; /// List all references in the repository /// @@ -238,26 +271,81 @@ extern NSString * const GTRepositoryInitOptionsOriginURLString; /// /// returns an array of NSStrings holding the names of the references /// returns nil if an error occurred and fills the error parameter -- (NSArray *)referenceNamesWithError:(NSError **)error; +- (NSArray * _Nullable)referenceNamesWithError:(NSError **)error; -- (GTReference *)headReferenceWithError:(NSError **)error; +/// Get the HEAD reference. +/// +/// error - If not NULL, set to any error that occurs. +/// +/// Returns a GTReference or nil if an error occurs. +- (GTReference * _Nullable)headReferenceWithError:(NSError **)error; -/// Convenience methods to return branches in the repository -- (NSArray *)allBranchesWithError:(NSError **)error; +/// Move HEAD reference safely, since deleting and recreating HEAD is always wrong. +/// +/// reference - The new target reference for HEAD. +/// error - If not NULL, set to any error that occurs. +/// +/// Returns NO if an error occurs. +- (BOOL)moveHEADToReference:(GTReference *)reference error:(NSError **)error; -- (NSArray *)localBranchesWithError:(NSError **)error; -- (NSArray *)remoteBranchesWithError:(NSError **)error; -- (NSArray *)branchesWithPrefix:(NSString *)prefix error:(NSError **)error; +/// Move HEAD reference safely, since deleting and recreating HEAD is always wrong. +/// +/// commit - The commit which HEAD should point to. +/// error - If not NULL, set to any error that occurs. +/// +/// Returns NO if an error occurs. +- (BOOL)moveHEADToCommit:(GTCommit *)commit error:(NSError **)error; + +/// Get the local branches. +/// +/// error - If not NULL, set to any error that occurs. +/// +/// Returns an array of GTBranches or nil if an error occurs. +- (NSArray * _Nullable)localBranchesWithError:(NSError **)error; + +/// Get the remote branches. +/// +/// error - If not NULL, set to any error that occurs. +/// +/// Returns an array of GTBranches or nil if an error occurs. +- (NSArray * _Nullable)remoteBranchesWithError:(NSError **)error; + +/// Get branches with names sharing a given prefix. +/// +/// prefix - The prefix to use for filtering. Must not be nil. +/// error - If not NULL, set to any error that occurs. +/// +/// Returns an array of GTBranches or nil if an error occurs. +- (NSArray * _Nullable)branchesWithPrefix:(NSString *)prefix error:(NSError **)error; + +/// Get the local and remote branches and merge them together by combining local +/// branches with their remote branch, if they have one. +/// +/// error - If not NULL, set to any error that occurs. +/// +/// Returns an array of GTBranches or nil if an error occurs. +- (NSArray * _Nullable)branches:(NSError **)error; /// List all remotes in the repository /// /// error - will be filled if an error occurs /// /// returns an array of NSStrings holding the names of the remotes, or nil if an error occurred -- (NSArray *)remoteNamesWithError:(NSError **)error; +- (NSArray * _Nullable)remoteNamesWithError:(NSError **)error; -/// Convenience method to return all tags in the repository -- (NSArray *)allTagsWithError:(NSError **)error; +/// Delete the given remote by name +/// +/// error - If not NULL, set to any error that occurs. +/// +/// returns YES if the deletion succeeded, otherwise NO. +- (BOOL)deleteRemoteNamed:(NSString *)remoteName error:(NSError **)error; + +/// Get all tags in the repository. +/// +/// error - If not NULL, set to any error that occurs. +/// +/// Returns an array of GTTag or nil if an error occurs. +- (NSArray * _Nullable)allTagsWithError:(NSError **)error; /// Count all commits in the current branch (HEAD) /// @@ -270,55 +358,50 @@ extern NSString * const GTRepositoryInitOptionsOriginURLString; /// /// name - The full name for the new reference. This must not be nil. /// targetOID - The OID that the new ref should point to. This must not be nil. -/// signature - A signature for the committer creating this ref, used for -/// creating a reflog entry. This may be nil. /// message - A message to use when creating the reflog entry for this action. /// This may be nil. /// error - If not NULL, set to any error that occurs. /// /// Returns the created ref, or nil if an error occurred. -- (GTReference *)createReferenceNamed:(NSString *)name fromOID:(GTOID *)targetOID committer:(GTSignature *)signature message:(NSString *)message error:(NSError **)error; +- (GTReference * _Nullable)createReferenceNamed:(NSString *)name fromOID:(GTOID *)targetOID message:(NSString * _Nullable)message error:(NSError **)error; /// Creates a symbolic reference to another ref. /// /// name - The full name for the new reference. This must not be nil. /// targetRef - The ref that the new ref should point to. This must not be nil. -/// signature - A signature for the committer creating this ref, used for -/// creating a reflog entry. This may be nil. /// message - A message to use when creating the reflog entry for this action. /// This may be nil. /// error - If not NULL, set to any error that occurs. /// /// Returns the created ref, or nil if an error occurred. -- (GTReference *)createReferenceNamed:(NSString *)name fromReference:(GTReference *)targetRef committer:(GTSignature *)signature message:(NSString *)message error:(NSError **)error; +- (GTReference * _Nullable)createReferenceNamed:(NSString *)name fromReference:(GTReference *)targetRef message:(NSString * _Nullable)message error:(NSError **)error; /// Create a new local branch pointing to the given OID. /// /// name - The name for the new branch (e.g., `master`). This must not be /// nil. /// targetOID - The OID to create the new branch off. This must not be nil. -/// signature - A signature for the committer creating this branch, used for -/// creating a reflog entry. This may be nil. /// message - A message to use when creating the reflog entry for this action. /// This may be nil. /// error - If not NULL, set to any error that occurs. /// /// Returns the new branch, or nil if an error occurred. -- (GTBranch *)createBranchNamed:(NSString *)name fromOID:(GTOID *)targetOID committer:(GTSignature *)signature message:(NSString *)message error:(NSError **)error; +- (GTBranch * _Nullable)createBranchNamed:(NSString *)name fromOID:(GTOID *)targetOID message:(NSString * _Nullable)message error:(NSError **)error; /// Get the current branch. /// /// error(out) - will be filled if an error occurs /// /// returns the current branch or nil if an error occurred. -- (GTBranch *)currentBranchWithError:(NSError **)error; +- (GTBranch * _Nullable)currentBranchWithError:(NSError **)error; /// Find the commits that are on our local branch but not on the remote branch. /// -/// error(out) - will be filled if an error occurs +/// remoteBranch - The remote branch to use as a reference. Must not be nil. +/// error(out) - will be filled if an error occurs /// /// returns the local commits, an empty array if there is no remote branch, or nil if an error occurred -- (NSArray *)localCommitsRelativeToRemoteBranch:(GTBranch *)remoteBranch error:(NSError **)error; +- (NSArray * _Nullable)localCommitsRelativeToRemoteBranch:(GTBranch *)remoteBranch error:(NSError **)error; /// Retrieves git's "prepared message" for the next commit, like the default /// message pre-filled when committing after a conflicting merge. @@ -327,24 +410,14 @@ extern NSString * const GTRepositoryInitOptionsOriginURLString; /// /// Returns the message from disk, or nil if no prepared message exists or an /// error occurred. -- (NSString *)preparedMessageWithError:(NSError **)error; +- (NSString * _Nullable)preparedMessageWithError:(NSError **)error; /// The signature for the user at the current time, based on the repository and /// system configs. If the user's name or email have not been set, reasonable /// defaults will be used instead. Will never return nil. /// /// Returns the signature. -- (GTSignature *)userSignatureForNow; - -/// Reloads all cached information about the receiver's submodules. -/// -/// Existing GTSubmodule objects from this repository will be mutated as part of -/// this operation. -/// -/// error - If not NULL, set to any errors that occur. -/// -/// Returns whether the reload succeeded. -- (BOOL)reloadSubmodules:(NSError **)error; +- (GTSignature * _Nullable)userSignatureForNow; /// Enumerates over all the tracked submodules in the repository. /// @@ -354,7 +427,7 @@ extern NSString * const GTRepositoryInitOptionsOriginURLString; /// `error` will contain the error information. Setting `stop` to YES /// will cause enumeration to stop after the block returns. This must /// not be nil. -- (void)enumerateSubmodulesRecursively:(BOOL)recursive usingBlock:(void (^)(GTSubmodule *submodule, NSError *error, BOOL *stop))block; +- (void)enumerateSubmodulesRecursively:(BOOL)recursive usingBlock:(void (^)(GTSubmodule * _Nullable submodule, NSError *error, BOOL *stop))block; /// Looks up the top-level submodule with the given name. This will not recurse /// into submodule repositories. @@ -364,7 +437,7 @@ extern NSString * const GTRepositoryInitOptionsOriginURLString; /// /// Returns the first submodule that matches the given name, or nil if an error /// occurred locating or instantiating the GTSubmodule. -- (GTSubmodule *)submoduleWithName:(NSString *)name error:(NSError **)error; +- (GTSubmodule * _Nullable)submoduleWithName:(NSString *)name error:(NSError **)error; /// Finds the merge base between the commits pointed at by the given OIDs. /// @@ -373,36 +446,36 @@ extern NSString * const GTRepositoryInitOptionsOriginURLString; /// error - If not NULL, set to any error that occurs. /// /// Returns the merge base, or nil if none is found or an error occurred. -- (GTCommit *)mergeBaseBetweenFirstOID:(GTOID *)firstOID secondOID:(GTOID *)secondOID error:(NSError **)error; +- (GTCommit * _Nullable)mergeBaseBetweenFirstOID:(GTOID *)firstOID secondOID:(GTOID *)secondOID error:(NSError **)error; /// The object database backing the repository. /// /// error - The error if one occurred. /// /// Returns the object database, or nil if an error occurred. -- (GTObjectDatabase *)objectDatabaseWithError:(NSError **)error; +- (GTObjectDatabase * _Nullable)objectDatabaseWithError:(NSError **)error; /// The configuration for the repository. /// /// error - The error if one occurred. /// /// Returns the configuration, or nil if an error occurred. -- (GTConfiguration *)configurationWithError:(NSError **)error; +- (GTConfiguration * _Nullable)configurationWithError:(NSError **)error; /// The index for the repository. /// /// error - The error if one occurred. /// /// Returns the index, or nil if an error occurred. -- (GTIndex *)indexWithError:(NSError **)error; +- (GTIndex * _Nullable)indexWithError:(NSError **)error; /// Creates a new lightweight tag in this repository. /// /// name - Name for the tag; this name is validated /// for consistency. It should also not conflict with an -/// already existing tag name +/// already existing tag name. Must not be nil. /// target - Object to which this tag points. This object -/// must belong to this repository. +/// must belong to this repository. Must not be nil. /// error - Will be filled with a NSError instance on failuer. /// May be NULL. /// @@ -423,7 +496,7 @@ extern NSString * const GTRepositoryInitOptionsOriginURLString; /// May be NULL. /// /// Returns the object ID of the newly created tag or nil on error. -- (GTOID *)OIDByCreatingTagNamed:(NSString *)tagName target:(GTObject *)theTarget tagger:(GTSignature *)theTagger message:(NSString *)theMessage error:(NSError **)error; +- (GTOID * _Nullable)OIDByCreatingTagNamed:(NSString *)tagName target:(GTObject *)theTarget tagger:(GTSignature *)theTagger message:(NSString *)theMessage error:(NSError **)error; /// Creates an annotated tag in this repo. Existing tags are not overwritten. /// @@ -439,39 +512,44 @@ extern NSString * const GTRepositoryInitOptionsOriginURLString; /// May be NULL. /// /// Returns the newly created tag or nil on error. -- (GTTag *)createTagNamed:(NSString *)tagName target:(GTObject *)theTarget tagger:(GTSignature *)theTagger message:(NSString *)theMessage error:(NSError **)error; +- (GTTag * _Nullable)createTagNamed:(NSString *)tagName target:(GTObject *)theTarget tagger:(GTSignature *)theTagger message:(NSString *)theMessage error:(NSError **)error; /// Checkout a commit /// -/// targetCommit - The commit to checkout. -/// strategy - The checkout strategy to use. -/// notifyFlags - Flags that indicate which notifications should cause `notifyBlock` -/// to be called. +/// targetCommit - The commit to checkout. Must not be nil. +/// options - The checkout options to use. Can be nil. /// error - The error if one occurred. Can be NULL. -/// notifyBlock - The block to call back for notification handling. Can be nil. -/// progressBlock - The block to call back for progress updates. Can be nil. /// /// Returns YES if operation was successful, NO otherwise -- (BOOL)checkoutCommit:(GTCommit *)targetCommit strategy:(GTCheckoutStrategyType)strategy notifyFlags:(GTCheckoutNotifyFlags)notifyFlags error:(NSError **)error progressBlock:(void (^)(NSString *path, NSUInteger completedSteps, NSUInteger totalSteps))progressBlock notifyBlock:(int (^)(GTCheckoutNotifyFlags why, NSString *path, GTDiffFile *baseline, GTDiffFile *target, GTDiffFile *workdir))notifyBlock; +- (BOOL)checkoutCommit:(GTCommit *)targetCommit options:(GTCheckoutOptions * _Nullable)options error:(NSError **)error; /// Checkout a reference /// -/// targetCommit - The reference to checkout. -/// strategy - The checkout strategy to use. -/// notifyFlags - Flags that indicate which notifications should cause `notifyBlock` -/// to be called. -/// error - The error if one occurred. Can be NULL. -/// notifyBlock - The block to call back for notification handling. Can be nil. -/// progressBlock - The block to call back for progress updates. Can be nil. +/// targetReference - The reference to checkout. Must not be nil. +/// options - The checkout options to use. Can be nil. +/// error - The error if one occurred. Can be NULL. /// /// Returns YES if operation was successful, NO otherwise -- (BOOL)checkoutReference:(GTReference *)targetReference strategy:(GTCheckoutStrategyType)strategy notifyFlags:(GTCheckoutNotifyFlags)notifyFlags error:(NSError **)error progressBlock:(void (^)(NSString *path, NSUInteger completedSteps, NSUInteger totalSteps))progressBlock notifyBlock:(int (^)(GTCheckoutNotifyFlags why, NSString *path, GTDiffFile *baseline, GTDiffFile *target, GTDiffFile *workdir))notifyBlock; +- (BOOL)checkoutReference:(GTReference *)targetReference options:(GTCheckoutOptions * _Nullable)options error:(NSError **)error; -/// Convenience wrapper for checkoutCommit:strategy:notifyFlags:error:notifyBlock:progressBlock without notifications -- (BOOL)checkoutCommit:(GTCommit *)target strategy:(GTCheckoutStrategyType)strategy error:(NSError **)error progressBlock:(void (^)(NSString *path, NSUInteger completedSteps, NSUInteger totalSteps))progressBlock; +/// Checkout an index +/// +/// index - The index to checkout. Must not be nil. +/// options - The checkout options to use. Can be nil. +/// error - The error if one occurred. Can be NULL. +/// +/// Returns YES if operation was successful, NO otherwise +- (BOOL)checkoutIndex:(GTIndex *)index options:(GTCheckoutOptions * _Nullable)options error:(NSError **)error; -/// Convenience wrapper for checkoutReference:strategy:notifyFlags:error:notifyBlock:progressBlock without notifications -- (BOOL)checkoutReference:(GTReference *)target strategy:(GTCheckoutStrategyType)strategy error:(NSError **)error progressBlock:(void (^)(NSString *path, NSUInteger completedSteps, NSUInteger totalSteps))progressBlock; +/// Checkout a tree +/// +/// targetTree - The tree to checkout. +/// options - The checkout options to use. Can be nil. +/// error - The error if one occurred. Can be NULL. +/// +/// Returns YES if operation was successful, NO otherwise +/// Note: this operation will NOT update HEAD to newly checked out tree. +- (BOOL)checkoutTree:(GTTree *)targetTree options:(GTCheckoutOptions * _Nullable)options error:(NSError **)error; /// Flush the gitattributes cache. - (void)flushAttributesCache; @@ -494,6 +572,89 @@ extern NSString * const GTRepositoryInitOptionsOriginURLString; /// Returns the loaded filter list, or nil if an error occurs or there are no /// filters to apply to the given path. The latter two cases can be /// distinguished using the value of `success`. -- (GTFilterList *)filterListWithPath:(NSString *)path blob:(GTBlob *)blob mode:(GTFilterSourceMode)mode options:(GTFilterListOptions)options success:(BOOL *)success error:(NSError **)error; +- (GTFilterList * _Nullable)filterListWithPath:(NSString *)path blob:(GTBlob * _Nullable)blob mode:(GTFilterSourceMode)mode options:(GTFilterListOptions)options success:(BOOL * _Nullable)success error:(NSError **)error; + +/// Calculates how far ahead/behind the commit represented by `headOID` is, +/// relative to the commit represented by `baseOID`. +/// +/// ahead - Must not be NULL. +/// behind - Must not be NULL. +/// headOID - Must not be nil. +/// baseOID - Must not be nil. +/// error - If not NULL, set to any error that occurs. +/// +/// Returns whether `ahead` and `behind` were successfully calculated. +- (BOOL)calculateAhead:(size_t *)ahead behind:(size_t *)behind ofOID:(GTOID *)headOID relativeToOID:(GTOID *)baseOID error:(NSError **)error; + +/// Creates an enumerator for walking the unique commits, as determined by a +/// pushing a starting OID and hiding the relative OID. +/// +/// fromOID - The starting OID. +/// relativeOID - The OID to hide. +/// error - The error if one occurred. +/// +/// Returns the enumerator or nil if an error occurred. +- (GTEnumerator * _Nullable)enumeratorForUniqueCommitsFromOID:(GTOID *)fromOID relativeToOID:(GTOID *)relativeOID error:(NSError **)error; + +/// Determines the status of a git repository--i.e., whether an operation +/// (merge, cherry-pick, etc) is in progress. +/// +/// state - A pointer to set the retrieved state. Must not be NULL. +/// error - The error if one occurred. +/// +/// Returns YES if operation was successful, NO otherwise +- (BOOL)calculateState:(GTRepositoryStateType *)state withError:(NSError **)error; + +/// Remove all the metadata associated with an ongoing command like merge, +/// revert, cherry-pick, etc. For example: MERGE_HEAD, MERGE_MSG, etc. +/// +/// error - The error if one occurred. +/// +/// Returns YES if operation was successful, NO otherwise +- (BOOL)cleanupStateWithError:(NSError * _Nullable __autoreleasing *)error; + +/// Creates a new note in this repo (using a default notes reference, e.g. "refs/notes/commits") +/// +/// note - Note text. +/// theTarget - Object (usually a commit) to which this note refers to. +/// This object must belong to this repository. +/// referenceName - Name for the notes reference in the repo, or nil for default ("refs/notes/commits") +/// author - Signature of the author for this note, and +/// of the note creation time +/// committer - Signature of the committer for this note. +/// overwrite - If set to YES, the note will be overwritten if it already exists. +/// error - Will be filled with a NSError object in case of error. +/// May be NULL. +/// +/// Returns the newly created note or nil on error. +- (GTNote * _Nullable)createNote:(NSString *)note target:(GTObject *)theTarget referenceName:(NSString * _Nullable)referenceName author:(GTSignature *)author committer:(GTSignature *)committer overwriteIfExists:(BOOL)overwrite error:(NSError **)error; + +/// Removes a note attached to object in this repo +/// +/// parentObject - Object (usually a commit) to which the note to be removed is attached to. +/// This object must belong to this repository. +/// referenceName - Name for the notes reference in the repo, or nil for default ("refs/notes/commits") +/// author - Signature of the author for this note removal, and +/// of the note removal time +/// committer - Signature of the committer for this note removal. +/// error - Will be filled with a NSError object in case of error. +/// May be NULL. +/// +/// Returns the YES on success and NO on error. +- (BOOL)removeNoteFromObject:(GTObject *)parentObject referenceName:(NSString * _Nullable)referenceName author:(GTSignature *)author committer:(GTSignature *)committer error:(NSError **)error; + +/// Enumerates through all stored notes in this repo +/// +/// referenceName - Name for the notes reference in the repo, or nil for default ("refs/notes/commits") +/// error - Will be filled with a NSError object in case of error. +/// May be NULL. +/// block - A block to be called on each encountered note object. The block accepts +/// a reference to `note`, an `object` that is annotated with the note. +/// If the block sets `stop` to YES, the iterator is finished. +/// +/// Returns YES on overall success or NO on error of any kind. +- (BOOL)enumerateNotesWithReferenceName:(NSString * _Nullable)referenceName error:(NSError **)error usingBlock:(void (^)(GTNote * _Nullable note, GTObject * _Nullable object, NSError * _Nullable error, BOOL *stop))block; @end + +NS_ASSUME_NONNULL_END diff --git a/ObjectiveGit/GTRepository.m b/ObjectiveGit/GTRepository.m index fd7ac4c49..133216cd4 100644 --- a/ObjectiveGit/GTRepository.m +++ b/ObjectiveGit/GTRepository.m @@ -31,6 +31,7 @@ #import "GTBlob.h" #import "GTBranch.h" +#import "GTCheckoutOptions.h" #import "GTCommit.h" #import "GTConfiguration+Private.h" #import "GTConfiguration.h" @@ -51,14 +52,20 @@ #import "NSArray+StringArray.h" #import "NSError+Git.h" #import "NSString+Git.h" +#import "GTRepository+References.h" +#import "GTNote.h" + +#import "EXTScope.h" #import "git2.h" NSString * const GTRepositoryCloneOptionsBare = @"GTRepositoryCloneOptionsBare"; -NSString * const GTRepositoryCloneOptionsCheckout = @"GTRepositoryCloneOptionsCheckout"; +NSString * const GTRepositoryCloneOptionsPerformCheckout = @"GTRepositoryCloneOptionsPerformCheckout"; +NSString * const GTRepositoryCloneOptionsCheckoutOptions = @"GTRepositoryCloneOptionsCheckoutOptions"; NSString * const GTRepositoryCloneOptionsTransportFlags = @"GTRepositoryCloneOptionsTransportFlags"; NSString * const GTRepositoryCloneOptionsCredentialProvider = @"GTRepositoryCloneOptionsCredentialProvider"; NSString * const GTRepositoryCloneOptionsCloneLocal = @"GTRepositoryCloneOptionsCloneLocal"; +NSString * const GTRepositoryCloneOptionsServerCertificateURL = @"GTRepositoryCloneOptionsServerCertificateURL"; NSString * const GTRepositoryInitOptionsFlags = @"GTRepositoryInitOptionsFlags"; NSString * const GTRepositoryInitOptionsMode = @"GTRepositoryInitOptionsMode"; NSString * const GTRepositoryInitOptionsWorkingDirectoryPath = @"GTRepositoryInitOptionsWorkingDirectoryPath"; @@ -89,6 +96,9 @@ @interface GTRepository () @implementation GTRepository - (NSString *)description { + if (self.isBare) { + return [NSString stringWithFormat:@"<%@: %p> (bare) gitDirectoryURL: %@", self.class, self, self.gitDirectoryURL]; + } return [NSString stringWithFormat:@"<%@: %p> fileURL: %@", self.class, self, self.fileURL]; } @@ -106,21 +116,6 @@ - (void)dealloc { #pragma mark API -+ (BOOL)isAGitDirectory:(NSURL *)directory { - NSFileManager *fm = [[NSFileManager alloc] init]; - BOOL isDir = NO; - NSURL *headFileURL = [directory URLByAppendingPathComponent:@"HEAD"]; - - if ([fm fileExistsAtPath:headFileURL.path isDirectory:&isDir] && !isDir) { - NSURL *objectsDir = [directory URLByAppendingPathComponent:@"objects"]; - if ([fm fileExistsAtPath:objectsDir.path isDirectory:&isDir] && isDir) { - return YES; - } - } - - return NO; -} - + (instancetype)initializeEmptyRepositoryAtFileURL:(NSURL *)localFileURL options:(NSDictionary *)optionsDict error:(NSError **)error { if (!localFileURL.isFileURL || localFileURL.path == nil) { if (error != NULL) *error = [NSError errorWithDomain:NSCocoaErrorDomain code:NSFileWriteUnsupportedSchemeError userInfo:@{ NSLocalizedDescriptionKey: NSLocalizedString(@"Invalid file path URL to initialize repository.", @"") }]; @@ -151,11 +146,16 @@ + (instancetype)initializeEmptyRepositoryAtFileURL:(NSURL *)localFileURL options return [[self alloc] initWithGitRepository:repository]; } -+ (id)repositoryWithURL:(NSURL *)localFileURL error:(NSError **)error { ++ (instancetype)repositoryWithURL:(NSURL *)localFileURL error:(NSError **)error { return [[self alloc] initWithURL:localFileURL error:error]; } -- (id)initWithGitRepository:(git_repository *)repository { +- (instancetype)init { + NSAssert(NO, @"Call to an unavailable initializer."); + return nil; +} + +- (instancetype)initWithGitRepository:(git_repository *)repository { NSParameterAssert(repository != nil); self = [super init]; @@ -166,7 +166,7 @@ - (id)initWithGitRepository:(git_repository *)repository { return self; } -- (id)initWithURL:(NSURL *)localFileURL error:(NSError **)error { +- (instancetype)initWithURL:(NSURL *)localFileURL error:(NSError **)error { if (![localFileURL isFileURL] || localFileURL.path == nil) { if (error != NULL) *error = [NSError errorWithDomain:NSCocoaErrorDomain code:NSFileReadUnsupportedSchemeError userInfo:@{ NSLocalizedDescriptionKey: NSLocalizedString(@"Invalid file path URL to open.", @"") }]; return nil; @@ -182,22 +182,48 @@ - (id)initWithURL:(NSURL *)localFileURL error:(NSError **)error { return [self initWithGitRepository:r]; } +- (instancetype)initWithURL:(NSURL *)localFileURL flags:(NSInteger)flags ceilingDirs:(NSArray *)ceilingDirURLs error:(NSError **)error { + if (!localFileURL.isFileURL || localFileURL.path == nil) { + if (error != NULL) *error = [NSError errorWithDomain:NSCocoaErrorDomain code:NSFileReadUnsupportedSchemeError userInfo:@{ NSLocalizedDescriptionKey: NSLocalizedString(@"Invalid file path URL to open.", @"") }]; + return nil; + } + + // Concatenate URL paths. + NSMutableString *ceilingDirsString; + if (ceilingDirURLs.count > 0) { + ceilingDirsString = [[NSMutableString alloc] init]; + [ceilingDirURLs enumerateObjectsUsingBlock:^(NSURL * _Nonnull url, NSUInteger idx, BOOL * _Nonnull stop) { + if (idx < ceilingDirURLs.count - 1) { + [ceilingDirsString appendString:[NSString stringWithFormat:@"%@%c", url.path, GIT_PATH_LIST_SEPARATOR]]; + } else { + NSString *path = url.path; + NSAssert(path != nil, @"Unexpected nil path component"); + [ceilingDirsString appendString:path]; + } + }]; + } -typedef void(^GTTransferProgressBlock)(const git_transfer_progress *progress); + git_repository *r; + int gitError = git_repository_open_ext(&r, localFileURL.path.fileSystemRepresentation, (unsigned int)flags, ceilingDirsString.fileSystemRepresentation); + if (gitError < GIT_OK) { + if (error != NULL) *error = [NSError git_errorFor:gitError description:@"Failed to open repository at URL %@.", localFileURL]; + return nil; + } -static void checkoutProgressCallback(const char *path, size_t completedSteps, size_t totalSteps, void *payload) { - if (payload == NULL) return; - void (^block)(NSString *, NSUInteger, NSUInteger) = (__bridge id)payload; - NSString *nsPath = (path != NULL ? [NSString stringWithUTF8String:path] : nil); - block(nsPath, completedSteps, totalSteps); + return [self initWithGitRepository:r]; } + +typedef void(^GTTransferProgressBlock)(const git_transfer_progress *progress, BOOL *stop); + static int transferProgressCallback(const git_transfer_progress *progress, void *payload) { if (payload == NULL) return 0; struct GTClonePayload *pld = payload; if (pld->transferProgressBlock == NULL) return 0; - pld->transferProgressBlock(progress); - return 0; + + BOOL stop = NO; + pld->transferProgressBlock(progress, &stop); + return (stop ? GIT_EUSER : 0); } struct GTClonePayload { @@ -208,35 +234,33 @@ static int transferProgressCallback(const git_transfer_progress *progress, void static int remoteCreate(git_remote **remote, git_repository *repo, const char *name, const char *url, void *payload) { int error; - struct GTRemoteCreatePayload *pld = payload; - git_remote_callbacks *callbacks = &pld->remoteCallbacks; - if ((error = git_remote_create(remote, repo, name, url)) < 0) return error; - return git_remote_set_callbacks(*remote, callbacks); + return GIT_OK; } struct GTRemoteCreatePayload { git_remote_callbacks remoteCallbacks; }; -+ (id)cloneFromURL:(NSURL *)originURL toWorkingDirectory:(NSURL *)workdirURL options:(NSDictionary *)options error:(NSError **)error transferProgressBlock:(void (^)(const git_transfer_progress *))transferProgressBlock checkoutProgressBlock:(void (^)(NSString *path, NSUInteger completedSteps, NSUInteger totalSteps))checkoutProgressBlock { ++ (instancetype _Nullable)cloneFromURL:(NSURL *)originURL toWorkingDirectory:(NSURL *)workdirURL options:(NSDictionary * _Nullable)options error:(NSError **)error transferProgressBlock:(void (^ _Nullable)(const git_transfer_progress *, BOOL *stop))transferProgressBlock { git_clone_options cloneOptions = GIT_CLONE_OPTIONS_INIT; NSNumber *bare = options[GTRepositoryCloneOptionsBare]; cloneOptions.bare = (bare == nil ? 0 : bare.boolValue); - NSNumber *checkout = options[GTRepositoryCloneOptionsCheckout]; - BOOL withCheckout = (checkout == nil ? YES : checkout.boolValue); + NSNumber *checkout = options[GTRepositoryCloneOptionsPerformCheckout]; + BOOL doCheckout = (checkout != nil ? [checkout boolValue] : YES); + + GTCheckoutOptions *checkoutOptions = options[GTRepositoryCloneOptionsCheckoutOptions]; + if (checkoutOptions == nil && doCheckout) { + checkoutOptions = [GTCheckoutOptions checkoutOptionsWithStrategy:GTCheckoutStrategySafe]; + } - if (withCheckout) { - git_checkout_options checkoutOptions = GIT_CHECKOUT_OPTIONS_INIT; - checkoutOptions.checkout_strategy = GIT_CHECKOUT_SAFE_CREATE; - checkoutOptions.progress_cb = checkoutProgressCallback; - checkoutOptions.progress_payload = (__bridge void *)checkoutProgressBlock; - cloneOptions.checkout_opts = checkoutOptions; + if (checkoutOptions != nil) { + cloneOptions.checkout_opts = *(checkoutOptions.git_checkoutOptions); } GTCredentialProvider *provider = options[GTRepositoryCloneOptionsCredentialProvider]; @@ -244,28 +268,34 @@ + (id)cloneFromURL:(NSURL *)originURL toWorkingDirectory:(NSURL *)workdirURL opt .credProvider = {provider}, }; - cloneOptions.remote_callbacks.version = GIT_REMOTE_CALLBACKS_VERSION; + git_fetch_options fetchOptions = GIT_FETCH_OPTIONS_INIT; + fetchOptions.callbacks.version = GIT_REMOTE_CALLBACKS_VERSION; if (provider) { - cloneOptions.remote_callbacks.credentials = GTCredentialAcquireCallback; + fetchOptions.callbacks.credentials = GTCredentialAcquireCallback; } payload.transferProgressBlock = transferProgressBlock; - cloneOptions.remote_callbacks.transfer_progress = transferProgressCallback; - cloneOptions.remote_callbacks.payload = &payload; - - struct GTRemoteCreatePayload remoteCreatePayload; - remoteCreatePayload.remoteCallbacks = cloneOptions.remote_callbacks; - + fetchOptions.callbacks.transfer_progress = transferProgressCallback; + fetchOptions.callbacks.payload = &payload; + cloneOptions.fetch_opts = fetchOptions; cloneOptions.remote_cb = remoteCreate; - cloneOptions.remote_cb_payload = &remoteCreatePayload; BOOL localClone = [options[GTRepositoryCloneOptionsCloneLocal] boolValue]; if (localClone) { cloneOptions.local = GIT_CLONE_NO_LOCAL; } + NSURL *serverCertificateURL = options[GTRepositoryCloneOptionsServerCertificateURL]; + if (serverCertificateURL) { + int gitError = git_libgit2_opts(GIT_OPT_SET_SSL_CERT_LOCATIONS, serverCertificateURL.fileSystemRepresentation, NULL); + if (gitError < GIT_OK) { + if (error != NULL) *error = [NSError git_errorFor:gitError description:@"Failed to configure the server certificate at %@", serverCertificateURL]; + return nil; + } + } + // If our originURL is local, convert to a path before handing down. const char *remoteURL = NULL; if (originURL.isFileURL) { @@ -287,17 +317,17 @@ + (id)cloneFromURL:(NSURL *)originURL toWorkingDirectory:(NSURL *)workdirURL opt - (id)lookUpObjectByGitOid:(const git_oid *)oid objectType:(GTObjectType)type error:(NSError **)error { git_object *obj; - int gitError = git_object_lookup(&obj, self.git_repository, oid, (git_otype)type); + int gitError = git_object_lookup(&obj, self.git_repository, oid, (git_object_t)type); if (gitError < GIT_OK) { if (error != NULL) { char oid_str[GIT_OID_HEXSZ+1]; git_oid_tostr(oid_str, sizeof(oid_str), oid); - *error = [NSError git_errorFor:gitError description:@"Failed to lookup object %s in repository.", oid_str]; + *error = [NSError git_errorFor:gitError description:@"Failed to lookup object" userInfo:@{GTGitErrorOID: [GTOID oidWithGitOid:oid]} failureReason:@"The object %s couldn't be found in the repository.", oid_str]; } return nil; } - return [GTObject objectWithObj:obj inRepository:self]; + return [GTObject objectWithObj:obj inRepository:self]; } - (id)lookUpObjectByGitOid:(const git_oid *)oid error:(NSError **)error { @@ -349,36 +379,77 @@ - (GTBranch *)lookUpBranchWithName:(NSString *)branchName type:(GTBranchType)bra if (ref == NULL) return nil; GTReference *gtRef = [[GTReference alloc] initWithGitReference:ref repository:self]; - return [[GTBranch alloc] initWithReference:gtRef repository:self]; + return [[GTBranch alloc] initWithReference:gtRef]; } - (GTReference *)headReferenceWithError:(NSError **)error { git_reference *headRef; int gitError = git_repository_head(&headRef, self.git_repository); if (gitError != GIT_OK) { - if (error != NULL) *error = [NSError git_errorFor:gitError description:@"Failed to get HEAD"]; + NSString *unborn = @""; + if (gitError == GIT_EUNBORNBRANCH) { + unborn = @" (unborn)"; + } + if (error != NULL) *error = [NSError git_errorFor:gitError description:@"Failed to get HEAD%@", unborn]; return nil; } return [[GTReference alloc] initWithGitReference:headRef repository:self]; } +typedef void (^GTRepositoryBranchEnumerationBlock)(GTBranch *branch, BOOL *stop); + +- (BOOL)enumerateBranchesWithType:(GTBranchType)type error:(NSError **)error usingBlock:(GTRepositoryBranchEnumerationBlock)block { + git_branch_iterator *iter = NULL; + git_reference *gitRef = NULL; + int gitError = git_branch_iterator_new(&iter, self.git_repository, (git_branch_t)type); + if (gitError != GIT_OK) { + if (error) *error = [NSError git_errorFor:gitError description:@"Branch enumeration failed"]; + return NO; + } + + @onExit { + git_branch_iterator_free(iter); + }; + + git_branch_t branchType; + while ((gitError = git_branch_next(&gitRef, &branchType, iter)) == GIT_OK) { + GTReference *ref = [[GTReference alloc] initWithGitReference:gitRef repository:self]; + GTBranch *branch = [GTBranch branchWithReference:ref]; + BOOL stop = NO; + block(branch, &stop); + if (stop) break; + } + + if (gitError != GIT_OK && gitError != GIT_ITEROVER) { + if (error) *error = [NSError git_errorFor:gitError description:@"Branch enumeration failed"]; + return NO; + } + + return YES; +} + - (NSArray *)localBranchesWithError:(NSError **)error { - return [self branchesWithPrefix:[GTBranch localNamePrefix] error:error]; + NSMutableArray *localBranches = [NSMutableArray array]; + BOOL success = [self enumerateBranchesWithType:GTBranchTypeLocal error:error usingBlock:^(GTBranch *branch, BOOL *stop) { + [localBranches addObject:branch]; + }]; + + if (success != YES) return nil; + + return [localBranches copy]; } - (NSArray *)remoteBranchesWithError:(NSError **)error { - NSArray *remoteBranches = [self branchesWithPrefix:[GTBranch remoteNamePrefix] error:error]; - if (remoteBranches == nil) return nil; + NSMutableArray *remoteBranches = [NSMutableArray array]; + BOOL success = [self enumerateBranchesWithType:GTBranchTypeRemote error:error usingBlock:^(GTBranch *branch, BOOL *stop) { + if (![branch.shortName isEqualToString:@"HEAD"]) + [remoteBranches addObject:branch]; + }]; - NSMutableArray *filteredList = [NSMutableArray arrayWithCapacity:remoteBranches.count]; - for (GTBranch *branch in remoteBranches) { - if (![branch.shortName isEqualToString:@"HEAD"]) { - [filteredList addObject:branch]; - } - } + if (success != YES) return nil; - return filteredList; + return [remoteBranches copy]; } - (NSArray *)branchesWithPrefix:(NSString *)prefix error:(NSError **)error { @@ -389,10 +460,10 @@ - (NSArray *)branchesWithPrefix:(NSString *)prefix error:(NSError **)error { for (NSString *refName in references) { if (![refName hasPrefix:prefix]) continue; - GTReference *ref = [[GTReference alloc] initByLookingUpReferenceNamed:refName inRepository:self error:error]; + GTReference *ref = [self lookUpReferenceWithName:refName error:error]; if (ref == nil) continue; - GTBranch *branch = [[GTBranch alloc] initWithReference:ref repository:self]; + GTBranch *branch = [[GTBranch alloc] initWithReference:ref]; if (branch == nil) continue; [branches addObject:branch]; @@ -401,28 +472,23 @@ - (NSArray *)branchesWithPrefix:(NSString *)prefix error:(NSError **)error { return branches; } -- (NSArray *)allBranchesWithError:(NSError **)error { - NSMutableArray *allBranches = [NSMutableArray array]; +- (NSArray *)branches:(NSError **)error { NSArray *localBranches = [self localBranchesWithError:error]; - NSArray *remoteBranches = [self remoteBranchesWithError:error]; - if (localBranches == nil || remoteBranches == nil) return nil; + if (localBranches == nil) return nil; - [allBranches addObjectsFromArray:localBranches]; + NSMutableArray *remoteBranches = [[self remoteBranchesWithError:error] mutableCopy]; + if (remoteBranches == nil) return nil; - // we want to add the remote branches that we don't already have as a local branch - NSMutableDictionary *shortNamesToBranches = [NSMutableDictionary dictionary]; + NSMutableArray *branches = [NSMutableArray array]; for (GTBranch *branch in localBranches) { - [shortNamesToBranches setObject:branch forKey:branch.shortName]; + GTBranch *trackingBranch = [branch trackingBranchWithError:NULL success:NULL]; + if (trackingBranch != nil) [remoteBranches removeObject:trackingBranch]; + [branches addObject:branch]; } - for (GTBranch *branch in remoteBranches) { - GTBranch *localBranch = [shortNamesToBranches objectForKey:branch.shortName]; - if (localBranch == nil) { - [allBranches addObject:branch]; - } - } + [branches addObjectsFromArray:remoteBranches]; - return allBranches; + return branches; } - (NSArray *)remoteNamesWithError:(NSError **)error { @@ -440,6 +506,16 @@ - (NSArray *)remoteNamesWithError:(NSError **)error { return remoteNames; } +- (BOOL)deleteRemoteNamed:(NSString *)remoteName error:(NSError **)error { + int gitError = git_remote_delete(self.git_repository, [remoteName cStringUsingEncoding:NSUTF8StringEncoding]); + if (gitError < GIT_OK) { + if (error != NULL) *error = [NSError git_errorFor:gitError description:@"Failed to delete remote."]; + return NO; + } + + return YES; +} + struct GTRepositoryTagEnumerationInfo { __unsafe_unretained GTRepository *myself; __unsafe_unretained GTRepositoryTagEnumerationBlock block; @@ -450,7 +526,9 @@ static int GTRepositoryForeachTagCallback(const char *name, git_oid *oid, void * GTTag *tag = (GTTag *)[info->myself lookUpObjectByGitOid:oid objectType:GTObjectTypeTag error:NULL]; BOOL stop = NO; - info->block(tag, &stop); + if (tag != nil) { + info->block(tag, &stop); + } return stop ? GIT_EUSER : 0; } @@ -486,12 +564,12 @@ - (NSUInteger)numberOfCommitsInCurrentBranch:(NSError **)error { return [currentBranch numberOfCommitsWithError:error]; } -- (GTReference *)createReferenceNamed:(NSString *)name fromOID:(GTOID *)targetOID committer:(GTSignature *)signature message:(NSString *)message error:(NSError **)error { +- (GTReference *)createReferenceNamed:(NSString *)name fromOID:(GTOID *)targetOID message:(NSString *)message error:(NSError **)error { NSParameterAssert(name != nil); NSParameterAssert(targetOID != nil); git_reference *ref; - int gitError = git_reference_create(&ref, self.git_repository, name.UTF8String, targetOID.git_oid, 0, signature.git_signature, message.UTF8String); + int gitError = git_reference_create(&ref, self.git_repository, name.UTF8String, targetOID.git_oid, 0, message.UTF8String); if (gitError != GIT_OK) { if (error != NULL) *error = [NSError git_errorFor:gitError description:@"Failed to create direct reference to %@", targetOID]; return nil; @@ -500,13 +578,13 @@ - (GTReference *)createReferenceNamed:(NSString *)name fromOID:(GTOID *)targetOI return [[GTReference alloc] initWithGitReference:ref repository:self]; } -- (GTReference *)createReferenceNamed:(NSString *)name fromReference:(GTReference *)targetRef committer:(GTSignature *)signature message:(NSString *)message error:(NSError **)error { +- (GTReference *)createReferenceNamed:(NSString *)name fromReference:(GTReference *)targetRef message:(NSString *)message error:(NSError **)error { NSParameterAssert(name != nil); NSParameterAssert(targetRef != nil); NSParameterAssert(targetRef.name != nil); git_reference *ref; - int gitError = git_reference_symbolic_create(&ref, self.git_repository, name.UTF8String, targetRef.name.UTF8String, 0, signature.git_signature, message.UTF8String); + int gitError = git_reference_symbolic_create(&ref, self.git_repository, name.UTF8String, targetRef.name.UTF8String, 0, message.UTF8String); if (gitError != GIT_OK) { if (error != NULL) *error = [NSError git_errorFor:gitError description:@"Failed to create symbolic reference to %@", targetRef]; return nil; @@ -515,14 +593,14 @@ - (GTReference *)createReferenceNamed:(NSString *)name fromReference:(GTReferenc return [[GTReference alloc] initWithGitReference:ref repository:self]; } -- (GTBranch *)createBranchNamed:(NSString *)name fromOID:(GTOID *)targetOID committer:(GTSignature *)signature message:(NSString *)message error:(NSError **)error { +- (GTBranch *)createBranchNamed:(NSString *)name fromOID:(GTOID *)targetOID message:(NSString *)message error:(NSError **)error { NSParameterAssert(name != nil); NSParameterAssert(targetOID != nil); - GTReference *newRef = [self createReferenceNamed:[GTBranch.localNamePrefix stringByAppendingString:name] fromOID:targetOID committer:signature message:message error:error]; + GTReference *newRef = [self createReferenceNamed:[GTBranch.localNamePrefix stringByAppendingString:name] fromOID:targetOID message:message error:error]; if (newRef == nil) return nil; - return [GTBranch branchWithReference:newRef repository:self]; + return [GTBranch branchWithReference:newRef]; } - (BOOL)isEmpty { @@ -533,7 +611,7 @@ - (GTBranch *)currentBranchWithError:(NSError **)error { GTReference *head = [self headReferenceWithError:error]; if (head == nil) return nil; - return [GTBranch branchWithReference:head repository:self]; + return [GTBranch branchWithReference:head]; } - (NSArray *)localCommitsRelativeToRemoteBranch:(GTBranch *)remoteBranch error:(NSError **)error { @@ -559,18 +637,22 @@ - (NSArray *)referenceNamesWithError:(NSError **)error { } - (NSURL *)fileURL { - const char *path = git_repository_workdir(self.git_repository); + const char *cPath = git_repository_workdir(self.git_repository); // bare repository, you may be looking for gitDirectoryURL - if (path == NULL) return nil; + if (cPath == NULL) return nil; - return [NSURL fileURLWithPath:@(path) isDirectory:YES]; + NSString *path = @(cPath); + NSAssert(path, @"workdir is nil"); + return [NSURL fileURLWithPath:path isDirectory:YES]; } - (NSURL *)gitDirectoryURL { - const char *path = git_repository_path(self.git_repository); - if (path == NULL) return nil; + const char *cPath = git_repository_path(self.git_repository); + if (cPath == NULL) return nil; - return [NSURL fileURLWithPath:@(path) isDirectory:YES]; + NSString *path = @(cPath); + NSAssert(path, @"gitdirectory is nil"); + return [NSURL fileURLWithPath:path isDirectory:YES]; } - (BOOL)isBare { @@ -585,7 +667,7 @@ - (BOOL)isHEADUnborn { return (BOOL)git_repository_head_unborn(self.git_repository); } -- (NSString *)preparedMessageWithError:(NSError **)error { +- (NSString *)preparedMessageWithError:(NSError * __autoreleasing *)error { void (^setErrorFromCode)(int) = ^(int errorCode) { if (errorCode == 0 || errorCode == GIT_ENOTFOUND) { // Not an error. @@ -601,13 +683,13 @@ - (NSString *)preparedMessageWithError:(NSError **)error { int errorCode = git_repository_message(&msg, self.git_repository); if (errorCode != GIT_OK) { setErrorFromCode(errorCode); - git_buf_free(&msg); + git_buf_dispose(&msg); return nil; } NSString *message = [[NSString alloc] initWithBytes:msg.ptr length:msg.size encoding:NSUTF8StringEncoding]; - git_buf_free(&msg); + git_buf_dispose(&msg); return message; } @@ -659,7 +741,9 @@ static int submoduleEnumerationCallback(git_submodule *git_submodule, const char NSError *error; // Use -submoduleWithName:error: so that we get a git_submodule that we own. - GTSubmodule *submodule = [info->parentRepository submoduleWithName:@(name) error:&error]; + NSString *submoduleName = @(name); + NSCAssert(submoduleName, @"submodule name is nil"); + GTSubmodule *submodule = [info->parentRepository submoduleWithName:submoduleName error:&error]; BOOL stop = NO; info->block(submodule, error, &stop); @@ -672,16 +756,6 @@ static int submoduleEnumerationCallback(git_submodule *git_submodule, const char return 0; } -- (BOOL)reloadSubmodules:(NSError **)error { - int gitError = git_submodule_reload_all(self.git_repository, 0); - if (gitError != GIT_OK) { - if (error != NULL) *error = [NSError git_errorFor:gitError description:@"Failed to reload submodules."]; - return NO; - } - - return YES; -} - - (void)enumerateSubmodulesRecursively:(BOOL)recursive usingBlock:(void (^)(GTSubmodule *submodule, NSError *error, BOOL *stop))block { NSParameterAssert(block != nil); @@ -711,24 +785,33 @@ - (GTSubmodule *)submoduleWithName:(NSString *)name error:(NSError **)error { #pragma mark User ++ (NSString *)defaultUserName { + NSString *name = NSFullUserName(); + if (name.length == 0) name = NSUserName(); + if (name.length == 0) name = @"nobody"; + return name; +} + ++ (NSString *)defaultEmail { + NSString *username = NSUserName(); + if (username.length == 0) username = @"nobody"; + NSString *domain = NSProcessInfo.processInfo.hostName ?: @"nowhere.local"; + return [NSString stringWithFormat:@"%@@%@", username, domain]; +} + - (GTSignature *)userSignatureForNow { GTConfiguration *configuration = [self configurationWithError:NULL]; NSString *name = [configuration stringForKey:@"user.name"]; - if (name.length == 0) { - name = NSFullUserName(); - if (name.length == 0) name = NSUserName(); - if (name.length == 0) name = @"nobody"; - } + if (name.length == 0) name = self.class.defaultUserName; NSString *email = [configuration stringForKey:@"user.email"]; - if (email == nil) { - NSString *username = NSUserName(); - if (username.length == 0) username = @"nobody"; - NSString *domain = NSProcessInfo.processInfo.hostName ?: @"nowhere.local"; - email = [NSString stringWithFormat:@"%@@%@", username, domain]; - } + if (email.length == 0) email = self.class.defaultEmail; + + NSDate *now = [NSDate date]; + GTSignature *signature = [[GTSignature alloc] initWithName:name email:email time:now]; + if (signature != nil) return signature; - return [[GTSignature alloc] initWithName:name email:email time:[NSDate date]]; + return [[GTSignature alloc] initWithName:self.class.defaultUserName email:self.class.defaultEmail time:now]; } #pragma mark Tagging @@ -765,26 +848,10 @@ - (GTTag *)createTagNamed:(NSString *)tagName target:(GTObject *)theTarget tagge #pragma mark Checkout -// The type of block passed to -checkout:strategy:progressBlock:notifyBlock:notifyFlags:error: for progress reporting -typedef void (^GTCheckoutProgressBlock)(NSString *path, NSUInteger completedSteps, NSUInteger totalSteps); - -// The type of block passed to -checkout:strategy:progressBlock:notifyBlock:notifyFlags:error: for notification reporting -typedef int (^GTCheckoutNotifyBlock)(GTCheckoutNotifyFlags why, NSString *path, GTDiffFile *baseline, GTDiffFile *target, GTDiffFile *workdir); - -static int checkoutNotifyCallback(git_checkout_notify_t why, const char *path, const git_diff_file *baseline, const git_diff_file *target, const git_diff_file *workdir, void *payload) { - if (payload == NULL) return 0; - GTCheckoutNotifyBlock block = (__bridge id)payload; - NSString *nsPath = (path != NULL ? @(path) : nil); - GTDiffFile *gtBaseline = (baseline != NULL ? [[GTDiffFile alloc] initWithGitDiffFile:*baseline] : nil); - GTDiffFile *gtTarget = (target != NULL ? [[GTDiffFile alloc] initWithGitDiffFile:*target] : nil); - GTDiffFile *gtWorkdir = (workdir != NULL ? [[GTDiffFile alloc] initWithGitDiffFile:*workdir] : nil); - return block((GTCheckoutNotifyFlags)why, nsPath, gtBaseline, gtTarget, gtWorkdir); -} - - (BOOL)moveHEADToReference:(GTReference *)reference error:(NSError **)error { NSParameterAssert(reference != nil); - int gitError = git_repository_set_head(self.git_repository, reference.name.UTF8String, [self userSignatureForNow].git_signature, NULL); + int gitError = git_repository_set_head(self.git_repository, reference.name.UTF8String); if (gitError != GIT_OK) { if (error != NULL) *error = [NSError git_errorFor:gitError description:@"Failed to move HEAD to reference %@", reference.name]; } @@ -795,7 +862,7 @@ - (BOOL)moveHEADToReference:(GTReference *)reference error:(NSError **)error { - (BOOL)moveHEADToCommit:(GTCommit *)commit error:(NSError **)error { NSParameterAssert(commit != nil); - int gitError = git_repository_set_head_detached(self.git_repository, commit.OID.git_oid, [self userSignatureForNow].git_signature, NULL); + int gitError = git_repository_set_head_detached(self.git_repository, commit.OID.git_oid); if (gitError != GIT_OK) { if (error != NULL) *error = [NSError git_errorFor:gitError description:@"Failed to move HEAD to commit %@", commit.SHA]; } @@ -803,46 +870,40 @@ - (BOOL)moveHEADToCommit:(GTCommit *)commit error:(NSError **)error { return gitError == GIT_OK; } -- (BOOL)performCheckoutWithStrategy:(GTCheckoutStrategyType)strategy notifyFlags:(GTCheckoutNotifyFlags)notifyFlags error:(NSError **)error progressBlock:(GTCheckoutProgressBlock)progressBlock notifyBlock:(GTCheckoutNotifyBlock)notifyBlock { - - git_checkout_options checkoutOptions = GIT_CHECKOUT_OPTIONS_INIT; - - checkoutOptions.checkout_strategy = strategy; - checkoutOptions.progress_cb = checkoutProgressCallback; - checkoutOptions.progress_payload = (__bridge void *)progressBlock; - - checkoutOptions.notify_cb = checkoutNotifyCallback; - checkoutOptions.notify_flags = notifyFlags; - checkoutOptions.notify_payload = (__bridge void *)notifyBlock; - - int gitError = git_checkout_head(self.git_repository, &checkoutOptions); +- (BOOL)performCheckout:(GTObject *)target options:(GTCheckoutOptions * _Nullable)options error:(NSError **)error { + int gitError = git_checkout_tree(self.git_repository, target.git_object, options.git_checkoutOptions); if (gitError < GIT_OK) { if (error != NULL) *error = [NSError git_errorFor:gitError description:@"Failed to checkout tree."]; } - return gitError == GIT_OK; } -- (BOOL)checkoutCommit:(GTCommit *)targetCommit strategy:(GTCheckoutStrategyType)strategy notifyFlags:(GTCheckoutNotifyFlags)notifyFlags error:(NSError **)error progressBlock:(GTCheckoutProgressBlock)progressBlock notifyBlock:(GTCheckoutNotifyBlock)notifyBlock { - BOOL success = [self moveHEADToCommit:targetCommit error:error]; +- (BOOL)checkoutCommit:(GTCommit *)targetCommit options:(GTCheckoutOptions *)options error:(NSError **)error { + BOOL success = [self performCheckout:targetCommit options:options error:error]; if (success == NO) return NO; - - return [self performCheckoutWithStrategy:strategy notifyFlags:notifyFlags error:error progressBlock:progressBlock notifyBlock:notifyBlock]; + return [self moveHEADToCommit:targetCommit error:error]; } -- (BOOL)checkoutReference:(GTReference *)targetReference strategy:(GTCheckoutStrategyType)strategy notifyFlags:(GTCheckoutNotifyFlags)notifyFlags error:(NSError **)error progressBlock:(GTCheckoutProgressBlock)progressBlock notifyBlock:(GTCheckoutNotifyBlock)notifyBlock { - BOOL success = [self moveHEADToReference:targetReference error:error]; +- (BOOL)checkoutReference:(GTReference *)targetReference options:(GTCheckoutOptions *)options error:(NSError **)error { + GTOID *targetOID = [targetReference targetOID]; + GTObject *target = [self lookUpObjectByOID:targetOID error:error]; + if (target == nil) return NO; + BOOL success = [self performCheckout:target options:options error:error]; if (success == NO) return NO; - - return [self performCheckoutWithStrategy:strategy notifyFlags:notifyFlags error:error progressBlock:progressBlock notifyBlock:notifyBlock]; + return [self moveHEADToReference:targetReference error:error]; } -- (BOOL)checkoutCommit:(GTCommit *)target strategy:(GTCheckoutStrategyType)strategy error:(NSError **)error progressBlock:(GTCheckoutProgressBlock)progressBlock { - return [self checkoutCommit:target strategy:strategy notifyFlags:GTCheckoutNotifyNone error:error progressBlock:progressBlock notifyBlock:nil]; +- (BOOL)checkoutTree:(GTTree *)targetTree options:(GTCheckoutOptions * _Nullable)options error:(NSError **)error { + return [self performCheckout:targetTree options:options error:error]; } -- (BOOL)checkoutReference:(GTReference *)target strategy:(GTCheckoutStrategyType)strategy error:(NSError **)error progressBlock:(GTCheckoutProgressBlock)progressBlock { - return [self checkoutReference:target strategy:strategy notifyFlags:GTCheckoutNotifyNone error:error progressBlock:progressBlock notifyBlock:nil]; +- (BOOL)checkoutIndex:(GTIndex *)index options:(GTCheckoutOptions *)options error:(NSError **)error { + int gitError = git_checkout_index(self.git_repository, index.git_index, options.git_checkoutOptions); + if (gitError < GIT_OK) { + if (error != NULL) *error = [NSError git_errorFor:gitError description:@"Failed to checkout index."]; + return NO; + } + return YES; } - (void)flushAttributesCache { @@ -869,4 +930,121 @@ - (GTFilterList *)filterListWithPath:(NSString *)path blob:(GTBlob *)blob mode:( } } +- (BOOL)calculateAhead:(size_t *)ahead behind:(size_t *)behind ofOID:(GTOID *)headOID relativeToOID:(GTOID *)baseOID error:(NSError **)error { + NSParameterAssert(headOID != nil); + NSParameterAssert(baseOID != nil); + + int errorCode = git_graph_ahead_behind(ahead, behind, self.git_repository, headOID.git_oid, baseOID.git_oid); + if (errorCode != GIT_OK) { + if (error != NULL) *error = [NSError git_errorFor:errorCode description:@"Failed to calculate ahead/behind count of %@ relative to %@", headOID, baseOID]; + + return NO; + } + + return YES; +} + +- (GTEnumerator *)enumeratorForUniqueCommitsFromOID:(GTOID *)fromOID relativeToOID:(GTOID *)relativeOID error:(NSError **)error { + NSParameterAssert(fromOID != nil); + NSParameterAssert(relativeOID != nil); + + GTEnumerator *enumerator = [[GTEnumerator alloc] initWithRepository:self error:error]; + if (enumerator == nil) return nil; + + BOOL success = [enumerator pushSHA:fromOID.SHA error:error]; + if (!success) return nil; + + success = [enumerator hideSHA:relativeOID.SHA error:error]; + if (!success) return nil; + + return enumerator; +} + +- (BOOL)calculateState:(GTRepositoryStateType *)state withError:(NSError **)error { + NSParameterAssert(state != NULL); + + int result = git_repository_state(self.git_repository); + if (result < 0) { + if (error != NULL) *error = [NSError git_errorFor:result description:@"Failed to calculate repository state"]; + return NO; + } + + *state = result; + return YES; +} + +- (BOOL)cleanupStateWithError:(NSError **)error { + int errorCode = git_repository_state_cleanup(self.git_repository); + if (errorCode != GIT_OK) { + if (error != NULL) *error = [NSError git_errorFor:errorCode description:@"Failed to clean up repository state"]; + } + return YES; +} + +#pragma mark Notes + +- (GTNote *)createNote:(NSString *)note target:(GTObject *)theTarget referenceName:(NSString *)referenceName author:(GTSignature *)author committer:(GTSignature *)committer overwriteIfExists:(BOOL)overwrite error:(NSError **)error { + git_oid oid; + + int gitError = git_note_create(&oid, self.git_repository, referenceName.UTF8String, author.git_signature, committer.git_signature, theTarget.OID.git_oid, [note UTF8String], overwrite ? 1 : 0); + if (gitError != GIT_OK) { + if (error != NULL) *error = [NSError git_errorFor:gitError description:@"Failed to create a note in repository"]; + + return nil; + } + + return [[GTNote alloc] initWithTargetOID:theTarget.OID repository:self referenceName:referenceName error:error]; +} + +- (BOOL)removeNoteFromObject:(GTObject *)parentObject referenceName:(NSString *)referenceName author:(GTSignature *)author committer:(GTSignature *)committer error:(NSError **)error { + int gitError = git_note_remove(self.git_repository, referenceName.UTF8String, author.git_signature, committer.git_signature, parentObject.OID.git_oid); + if (gitError != GIT_OK) { + if (error != NULL) *error = [NSError git_errorFor:gitError description:@"Failed to delete note from %@", parentObject]; + return NO; + } + + return YES; +} + +- (BOOL)enumerateNotesWithReferenceName:(NSString *)referenceName error:(NSError **)error usingBlock:(void (^)(GTNote *note, GTObject *object, NSError *error, BOOL *stop))block { + git_note_iterator *iter = NULL; + + int gitError = git_note_iterator_new(&iter, self.git_repository, referenceName.UTF8String); + + if (gitError != GIT_OK) { + if (error != NULL) *error = [NSError git_errorFor:gitError description:@"Failed to enumerate notes"]; + return NO; + } + + @onExit { + git_note_iterator_free(iter); + }; + + git_oid note_id; + git_oid object_id; + BOOL success = YES; + int iterError = GIT_OK; + + while ((iterError = git_note_next(¬e_id, &object_id, iter)) == GIT_OK) { + NSError *lookupErr = nil; + + GTNote *note = [[GTNote alloc] initWithTargetOID:[GTOID oidWithGitOid:&object_id] repository:self referenceName:referenceName error:&lookupErr]; + GTObject *obj = nil; + + if (note != nil) obj = [self lookUpObjectByGitOid:&object_id error:&lookupErr]; + + BOOL stop = NO; + block(note, obj, lookupErr, &stop); + if (stop) { + break; + } + } + + if (iterError != GIT_OK && iterError != GIT_ITEROVER) { + if (error != NULL) *error = [NSError git_errorFor:iterError description:@"Iterator error"]; + } + + return success; +} + @end diff --git a/ObjectiveGit/GTSignature.h b/ObjectiveGit/GTSignature.h index ce984273c..566fe1e8f 100644 --- a/ObjectiveGit/GTSignature.h +++ b/ObjectiveGit/GTSignature.h @@ -30,27 +30,29 @@ #import "GTObject.h" +NS_ASSUME_NONNULL_BEGIN + /// A git signature. @interface GTSignature : NSObject /// The name of the person. -@property (nonatomic, readonly, copy) NSString *name; +@property (nonatomic, readonly, copy) NSString * _Nullable name; /// The email of the person. -@property (nonatomic, readonly, copy) NSString *email; +@property (nonatomic, readonly, copy) NSString * _Nullable email; /// The time when the action happened. -@property (nonatomic, readonly, strong) NSDate *time; +@property (nonatomic, readonly, strong) NSDate * _Nullable time; /// The time zone that `time` should be interpreted relative to. -@property (nonatomic, readonly, copy) NSTimeZone *timeZone; +@property (nonatomic, readonly, copy) NSTimeZone * _Nullable timeZone; /// Initializes the receiver with the given signature. /// /// git_signature - The signature to wrap. This must not be NULL. /// /// Returns an initialized GTSignature, or nil if an error occurs. -- (id)initWithGitSignature:(const git_signature *)git_signature; +- (instancetype _Nullable)initWithGitSignature:(const git_signature *)git_signature; /// Initializes the receiver with the given information. /// @@ -60,9 +62,11 @@ /// zone. This may be nil. /// /// Returns an initialized GTSignature, or nil if an error occurs. -- (id)initWithName:(NSString *)name email:(NSString *)email time:(NSDate *)time; +- (instancetype _Nullable)initWithName:(NSString *)name email:(NSString *)email time:(NSDate * _Nullable)time; /// The underlying `git_signature` object. - (const git_signature *)git_signature __attribute__((objc_returns_inner_pointer)); @end + +NS_ASSUME_NONNULL_END diff --git a/ObjectiveGit/GTSignature.m b/ObjectiveGit/GTSignature.m index 34a6506ec..f79aeeadc 100644 --- a/ObjectiveGit/GTSignature.m +++ b/ObjectiveGit/GTSignature.m @@ -48,7 +48,7 @@ - (void)dealloc { } } -- (id)initWithGitSignature:(const git_signature *)git_signature { +- (instancetype)initWithGitSignature:(const git_signature *)git_signature { NSParameterAssert(git_signature != NULL); self = [super init]; @@ -60,7 +60,7 @@ - (id)initWithGitSignature:(const git_signature *)git_signature { return self; } -- (id)initWithName:(NSString *)name email:(NSString *)email time:(NSDate *)time { +- (instancetype)initWithName:(NSString *)name email:(NSString *)email time:(NSDate *)time { NSParameterAssert(name != nil); NSParameterAssert(email != nil); @@ -111,10 +111,14 @@ - (NSString *)email { } - (NSDate *)time { + if (self.git_signature == NULL) return nil; + return [NSDate gt_dateFromGitTime:self.git_signature->when]; } - (NSTimeZone *)timeZone { + if (self.git_signature == NULL) return nil; + return [NSTimeZone gt_timeZoneFromGitTime:self.git_signature->when]; } diff --git a/ObjectiveGit/GTStatusDelta.h b/ObjectiveGit/GTStatusDelta.h index 7717f2426..17299cba1 100644 --- a/ObjectiveGit/GTStatusDelta.h +++ b/ObjectiveGit/GTStatusDelta.h @@ -8,35 +8,23 @@ #import #import "git2/diff.h" +#import @class GTDiffFile; -/// An enum representing the status of the file. -/// -/// See diff.h for documentation of individual flags. -typedef NS_ENUM(NSInteger, GTStatusDeltaStatus) { - GTStatusDeltaStatusUnmodified = GIT_DELTA_UNMODIFIED, - GTStatusDeltaStatusAdded = GIT_DELTA_ADDED, - GTStatusDeltaStatusDeleted = GIT_DELTA_DELETED, - GTStatusDeltaStatusModified = GIT_DELTA_MODIFIED, - GTStatusDeltaStatusRenamed = GIT_DELTA_RENAMED, - GTStatusDeltaStatusCopied = GIT_DELTA_COPIED, - GTStatusDeltaStatusIgnored = GIT_DELTA_IGNORED, - GTStatusDeltaStatusUntracked = GIT_DELTA_UNTRACKED, - GTStatusDeltaStatusTypeChange = GIT_DELTA_TYPECHANGE, -}; +NS_ASSUME_NONNULL_BEGIN /// Represents the status of a file in a repository. @interface GTStatusDelta : NSObject /// The file as it was prior to the change represented by this status delta. -@property (nonatomic, readonly, copy) GTDiffFile *oldFile; +@property (nonatomic, readonly, copy) GTDiffFile * _Nullable oldFile; /// The file after the change represented by this status delta -@property (nonatomic, readonly, copy) GTDiffFile *newFile __attribute__((ns_returns_not_retained)); +@property (nonatomic, readonly, copy) GTDiffFile * _Nullable newFile __attribute__((ns_returns_not_retained)); /// The status of the file. -@property (nonatomic, readonly) GTStatusDeltaStatus status; +@property (nonatomic, readonly) GTDeltaType status; /// A float between 0 and 1 describing how similar the old and new /// files are (where 0 is not at all and 1 is identical). @@ -45,7 +33,11 @@ typedef NS_ENUM(NSInteger, GTStatusDeltaStatus) { /// `GTStatusDeltaStatusCopied`. @property (nonatomic, readonly) double similarity; +- (instancetype)init NS_UNAVAILABLE; + /// Designated initializer. -- (instancetype)initWithGitDiffDelta:(const git_diff_delta *)delta; +- (instancetype _Nullable)initWithGitDiffDelta:(const git_diff_delta *)delta NS_DESIGNATED_INITIALIZER; @end + +NS_ASSUME_NONNULL_END diff --git a/ObjectiveGit/GTStatusDelta.m b/ObjectiveGit/GTStatusDelta.m index 230691451..c1538675b 100644 --- a/ObjectiveGit/GTStatusDelta.m +++ b/ObjectiveGit/GTStatusDelta.m @@ -12,13 +12,18 @@ @implementation GTStatusDelta +- (instancetype)init { + NSAssert(NO, @"Call to an unavailable initializer."); + return nil; +} + - (instancetype)initWithGitDiffDelta:(const git_diff_delta *)delta { self = [super init]; if (self == nil || delta == NULL) return nil; _oldFile = [[GTDiffFile alloc] initWithGitDiffFile:delta->old_file]; _newFile = [[GTDiffFile alloc] initWithGitDiffFile:delta->new_file]; - _status = (GTStatusDeltaStatus)delta->status; + _status = (GTDeltaType)delta->status; _similarity = (double)(delta->similarity / 100.0); return self; diff --git a/ObjectiveGit/GTSubmodule.h b/ObjectiveGit/GTSubmodule.h index 5e0103cd3..1e55fe16f 100644 --- a/ObjectiveGit/GTSubmodule.h +++ b/ObjectiveGit/GTSubmodule.h @@ -19,7 +19,7 @@ /// /// These flags are mutually exclusive. typedef NS_ENUM(NSInteger, GTSubmoduleIgnoreRule) { - GTSubmoduleIgnoreReset = GIT_SUBMODULE_IGNORE_RESET, + GTSubmoduleIgnoreUnspecified = GIT_SUBMODULE_IGNORE_UNSPECIFIED, GTSubmoduleIgnoreNone = GIT_SUBMODULE_IGNORE_NONE, GTSubmoduleIgnoreUntracked = GIT_SUBMODULE_IGNORE_UNTRACKED, GTSubmoduleIgnoreDirty = GIT_SUBMODULE_IGNORE_DIRTY, @@ -51,6 +51,8 @@ typedef NS_OPTIONS(NSInteger, GTSubmoduleStatus) { GTSubmoduleStatusUntrackedFilesInWorkingDirectory = GIT_SUBMODULE_STATUS_WD_UNTRACKED }; +NS_ASSUME_NONNULL_BEGIN + /// Represents a submodule within its parent repository. @interface GTSubmodule : NSObject @@ -58,25 +60,23 @@ typedef NS_OPTIONS(NSInteger, GTSubmoduleStatus) { @property (nonatomic, strong, readonly) GTRepository *parentRepository; /// The current ignore rule for this submodule. -/// -/// Setting this property will only update the rule in memory, not on disk. -@property (nonatomic, assign) GTSubmoduleIgnoreRule ignoreRule; +@property (nonatomic, readonly, assign) GTSubmoduleIgnoreRule ignoreRule; /// The OID that the submodule is pinned to in the parent repository's index. /// /// If the submodule is not in the index, this will be nil. -@property (nonatomic, strong, readonly) GTOID *indexOID; +@property (nonatomic, strong, readonly) GTOID * _Nullable indexOID; /// The OID that the submodule is pinned to in the parent repository's HEAD /// commit. /// /// If the submodule is not in HEAD, this will be nil. -@property (nonatomic, strong, readonly) GTOID *HEADOID; +@property (nonatomic, strong, readonly) GTOID * _Nullable HEADOID; /// The OID that is checked out in the submodule repository. /// /// If the submodule is not checked out, this will be nil. -@property (nonatomic, strong, readonly) GTOID *workingDirectoryOID; +@property (nonatomic, strong, readonly) GTOID * _Nullable workingDirectoryOID; /// The name of this submodule. @property (nonatomic, copy, readonly) NSString *name; @@ -88,7 +88,9 @@ typedef NS_OPTIONS(NSInteger, GTSubmoduleStatus) { /// `.git/config` or `.gitmodules` file. @property (nonatomic, copy, readonly) NSString *URLString; -/// Initializes the receiver to wrap the given submodule object. +- (instancetype)init NS_UNAVAILABLE; + +/// Initializes the receiver to wrap the given submodule object. Designated initializer. /// /// submodule - The submodule to wrap. The receiver will not own this object, so /// it must not be freed while the GTSubmodule is alive. This must @@ -97,7 +99,7 @@ typedef NS_OPTIONS(NSInteger, GTSubmoduleStatus) { /// nil. /// /// Returns an initialized GTSubmodule, or nil if an error occurs. -- (id)initWithGitSubmodule:(git_submodule *)submodule parentRepository:(GTRepository *)repository; +- (instancetype _Nullable)initWithGitSubmodule:(git_submodule *)submodule parentRepository:(GTRepository *)repository NS_DESIGNATED_INITIALIZER; /// The underlying `git_submodule` object. - (git_submodule *)git_submodule __attribute__((objc_returns_inner_pointer)); @@ -109,6 +111,16 @@ typedef NS_OPTIONS(NSInteger, GTSubmoduleStatus) { /// Returns whether reloading succeeded. - (BOOL)reload:(NSError **)error; +/// Write a new ignore rule to disk and get the resulting submodule. The +/// receiver will not have the new ignore rule. To update the receiver, call +/// `-reload:`. +/// +/// ignoreRule - The ignore rule. +/// error - The error if one occurred. +/// +/// Returns the updated submodule or nil if an error occurred. +- (GTSubmodule * _Nullable)submoduleByUpdatingIgnoreRule:(GTSubmoduleIgnoreRule)ignoreRule error:(NSError **)error; + /// Synchronizes the submodule repository's configuration files with the settings /// from the parent repository. /// @@ -120,13 +132,19 @@ typedef NS_OPTIONS(NSInteger, GTSubmoduleStatus) { /// If the submodule is not currently checked out, this will fail. /// /// Returns the opened repository, or nil if an error occurs. -- (GTRepository *)submoduleRepository:(NSError **)error; +- (GTRepository * _Nullable)submoduleRepository:(NSError **)error; -/// Determines the status for the submodule. -/// -/// Returns the status, or `GTSubmoduleStatusUnknown` if an error occurs. +/// Calls `-statusWithIgnoreRule:error:` with the submodule's ignore rule. - (GTSubmoduleStatus)status:(NSError **)error; +/// Determine the status for the submodule using the given ignore rule. +/// +/// ignoreRule - The ignore rule to use in calculating status. +/// error - The error if one occurred. +/// +/// Returns the status or `GTSubmoduleStatusUnknown` if an error occurred. +- (GTSubmoduleStatus)statusWithIgnoreRule:(GTSubmoduleIgnoreRule)ignoreRule error:(NSError **)error; + /// Initializes the submodule by copying its information into the parent /// repository's `.git/config` file. This is equivalent to `git submodule init` /// on the command line. @@ -148,3 +166,5 @@ typedef NS_OPTIONS(NSInteger, GTSubmoduleStatus) { - (BOOL)addToIndex:(NSError **)error; @end + +NS_ASSUME_NONNULL_END diff --git a/ObjectiveGit/GTSubmodule.m b/ObjectiveGit/GTSubmodule.m index 01e573a16..5d61b20c2 100644 --- a/ObjectiveGit/GTSubmodule.m +++ b/ObjectiveGit/GTSubmodule.m @@ -25,8 +25,16 @@ - (GTSubmoduleIgnoreRule)ignoreRule { return (GTSubmoduleIgnoreRule)git_submodule_ignore(self.git_submodule); } -- (void)setIgnoreRule:(GTSubmoduleIgnoreRule)ignoreRule { - git_submodule_set_ignore(self.git_submodule, (git_submodule_ignore_t)ignoreRule); +- (GTSubmodule *)submoduleByUpdatingIgnoreRule:(GTSubmoduleIgnoreRule)ignoreRule error:(NSError **)error { + int result = git_submodule_set_ignore(self.parentRepository.git_repository, git_submodule_name(self.git_submodule), (git_submodule_ignore_t)ignoreRule); + if (result != GIT_OK) { + if (error != NULL) { + *error = [NSError git_errorFor:result description:@"Couldn't set submodule ignore rule."]; + } + return nil; + } + + return [self.parentRepository submoduleWithName:self.name error:error]; } - (GTOID *)indexOID { @@ -52,23 +60,32 @@ - (GTOID *)workingDirectoryOID { - (NSString *)name { const char *cName = git_submodule_name(self.git_submodule); - if (cName == NULL) return nil; + NSAssert(cName != NULL, @"Unexpected nil submodule name"); - return @(cName); + NSString *name = @(cName); + NSAssert(name, @"name is nil"); + + return name; } - (NSString *)path { const char *cPath = git_submodule_path(self.git_submodule); - if (cPath == NULL) return nil; + NSAssert(cPath != NULL, @"Unexpected nil submodule path"); + + NSString *path = @(cPath); + NSAssert(path, @"message is nil"); - return @(cPath); + return path; } - (NSString *)URLString { const char *cURL = git_submodule_url(self.git_submodule); - if (cURL == NULL) return nil; + NSAssert(cURL != NULL, @"Unexpected nil submodule URL"); + + NSString *URL = @(cURL); + NSAssert(URL, @"URL is nil"); - return @(cURL); + return URL; } #pragma mark Lifecycle @@ -79,7 +96,12 @@ - (void)dealloc { } } -- (id)initWithGitSubmodule:(git_submodule *)submodule parentRepository:(GTRepository *)repository { +- (instancetype)init { + NSAssert(NO, @"Call to an unavailable initializer."); + return nil; +} + +- (instancetype)initWithGitSubmodule:(git_submodule *)submodule parentRepository:(GTRepository *)repository { NSParameterAssert(submodule != NULL); NSParameterAssert(repository != nil); @@ -94,9 +116,9 @@ - (id)initWithGitSubmodule:(git_submodule *)submodule parentRepository:(GTReposi #pragma mark Inspection -- (GTSubmoduleStatus)status:(NSError **)error { +- (GTSubmoduleStatus)statusWithIgnoreRule:(GTSubmoduleIgnoreRule)ignoreRule error:(NSError **)error { unsigned status; - int gitError = git_submodule_status(&status, self.git_submodule); + int gitError = git_submodule_status(&status, self.parentRepository.git_repository, git_submodule_name(self.git_submodule), (git_submodule_ignore_t)ignoreRule); if (gitError != GIT_OK) { if (error != NULL) *error = [NSError git_errorFor:gitError description:@"Failed to get submodule %@ status.", self.name]; return GTSubmoduleStatusUnknown; @@ -105,6 +127,10 @@ - (GTSubmoduleStatus)status:(NSError **)error { return status; } +- (GTSubmoduleStatus)status:(NSError **)error { + return [self statusWithIgnoreRule:self.ignoreRule error:error]; +} + #pragma mark Manipulation - (BOOL)reload:(NSError **)error { diff --git a/ObjectiveGit/GTTag.h b/ObjectiveGit/GTTag.h index 73f696a3c..bd7318e64 100644 --- a/ObjectiveGit/GTTag.h +++ b/ObjectiveGit/GTTag.h @@ -32,10 +32,12 @@ @class GTSignature; @class GTRepository; +NS_ASSUME_NONNULL_BEGIN + @interface GTTag : GTObject {} /// The author of the tag. -@property (nonatomic, readonly, strong) GTSignature *tagger; +@property (nonatomic, readonly, strong) GTSignature * _Nullable tagger; /// The description given when the tag was created. @property (nonatomic, readonly, strong) NSString *message; @@ -44,20 +46,25 @@ @property (nonatomic, readonly, strong) NSString *name; /// The 'tagged' object. -@property (nonatomic, readonly, strong) GTObject *target; +@property (nonatomic, readonly, strong) GTObject * _Nullable target; /// The type of the 'tagged' object. @property (nonatomic, readonly) GTObjectType targetType; /// Recursively peel a tag until a non tag GTObject is found /// -/// errro - Will be filled with a NSError object on failure. +/// error - Will be filled with a NSError object on failure. /// May be NULL. /// /// Returns the found object or nil on error. -- (id)objectByPeelingTagError:(NSError **)error; +- (id _Nullable)objectByPeelingTagError:(NSError **)error; + +/// Delete the receiver. +- (BOOL)delete:(NSError **)error; /// The underlying `git_object` as a `git_tag` object. - (git_tag *)git_tag __attribute__((objc_returns_inner_pointer)); @end + +NS_ASSUME_NONNULL_END diff --git a/ObjectiveGit/GTTag.m b/ObjectiveGit/GTTag.m index aa3312454..e2cd31a94 100644 --- a/ObjectiveGit/GTTag.m +++ b/ObjectiveGit/GTTag.m @@ -47,11 +47,15 @@ - (NSString *)description { #pragma mark API - (NSString *)message { - return @(git_tag_message(self.git_tag)); + NSString *message = @(git_tag_message(self.git_tag)); + NSAssert(message, @"message is nil"); + return message; } - (NSString *)name { - return @(git_tag_name(self.git_tag)); + NSString *name = @(git_tag_name(self.git_tag)); + NSAssert(name, @"message is nil"); + return name; } - (GTObject *)target { @@ -84,4 +88,13 @@ - (id)objectByPeelingTagError:(NSError **)error { return [[GTObject alloc] initWithObj:target inRepository:self.repository]; } +- (BOOL)delete:(NSError **)error { + int gitError = git_tag_delete(self.repository.git_repository, self.name.UTF8String); + if (gitError != GIT_OK) { + if (error) *error = [NSError git_errorFor:gitError description:@"Tag deletion failed"]; + return NO; + } + return YES; +} + @end diff --git a/ObjectiveGit/GTTree.h b/ObjectiveGit/GTTree.h index b27f508eb..80ceb507f 100644 --- a/ObjectiveGit/GTTree.h +++ b/ObjectiveGit/GTTree.h @@ -39,30 +39,39 @@ typedef NS_ENUM(NSInteger, GTTreeEnumerationOptions) { GTTreeEnumerationOptionPost = GIT_TREEWALK_POST, // Walk the tree in post-order (subdirectories come last) }; +NS_ASSUME_NONNULL_BEGIN + @interface GTTree : GTObject /// The number of entries in the tree. @property (nonatomic, readonly) NSUInteger entryCount; /// The contents of the tree, as an array of whose objects are of type `GTTreeEntry` -@property (nonatomic, strong, readonly) NSArray *entries; +@property (nonatomic, strong, readonly) NSArray * _Nullable entries; /// The underlying `git_object` as a `git_tree` object. - (git_tree *)git_tree __attribute__((objc_returns_inner_pointer)); -/// Get a entry at the specified index +/// Get an entry at the specified index /// /// index - index to retreive entry from /// /// returns a GTTreeEntry or nil if there is nothing at the index -- (GTTreeEntry *)entryAtIndex:(NSUInteger)index; +- (GTTreeEntry * _Nullable)entryAtIndex:(NSUInteger)index; -/// Get a entry by name +/// Get an entry by name /// /// name - the name of the entry /// /// returns a GTTreeEntry or nil if there is nothing with the specified name -- (GTTreeEntry *)entryWithName:(NSString *)name; +- (GTTreeEntry * _Nullable)entryWithName:(NSString *)name; + +/// Get an entry by path +/// +/// path - the path of the entry relative to the repository root +/// +/// returns a GTTreeEntry or nil if there is nothing with the specified path +- (GTTreeEntry * _Nullable)entryWithPath:(NSString *)path error:(NSError **)error; /// Enumerates the contents of the tree /// @@ -89,6 +98,8 @@ typedef NS_ENUM(NSInteger, GTTreeEnumerationOptions) { /// /// Returns an index which represents the result of the merge, or nil if an error /// occurred. -- (GTIndex *)merge:(GTTree *)otherTree ancestor:(GTTree *)ancestorTree error:(NSError **)error; +- (GTIndex * _Nullable)merge:(GTTree *)otherTree ancestor:(GTTree * _Nullable)ancestorTree error:(NSError **)error; @end + +NS_ASSUME_NONNULL_END diff --git a/ObjectiveGit/GTTree.m b/ObjectiveGit/GTTree.m index cba186322..97b7aa6c3 100644 --- a/ObjectiveGit/GTTree.m +++ b/ObjectiveGit/GTTree.m @@ -56,16 +56,29 @@ - (NSUInteger)entryCount { return (NSUInteger)git_tree_entrycount(self.git_tree); } -- (GTTreeEntry *)createEntryWithEntry:(const git_tree_entry *)entry { - return (entry != NULL ? [GTTreeEntry entryWithEntry:entry parentTree:self] : nil); +- (GTTreeEntry *)createEntryWithEntry:(const git_tree_entry *)entry error:(NSError **)error { + return (entry != NULL ? [GTTreeEntry entryWithEntry:entry parentTree:self error:nil] : nil); } - (GTTreeEntry *)entryAtIndex:(NSUInteger)index { - return [self createEntryWithEntry:git_tree_entry_byindex(self.git_tree, index)]; + return [self createEntryWithEntry:git_tree_entry_byindex(self.git_tree, index) error:nil]; } - (GTTreeEntry *)entryWithName:(NSString *)name { - return [self createEntryWithEntry:git_tree_entry_byname(self.git_tree, name.UTF8String)]; + return [self createEntryWithEntry:git_tree_entry_byname(self.git_tree, name.UTF8String) error:nil]; +} + +- (GTTreeEntry *)entryWithPath:(NSString *)path error:(NSError **)error { + git_tree_entry *internalEntry = NULL; + int gitError = git_tree_entry_bypath(&internalEntry, self.git_tree, path.UTF8String); + if (gitError != GIT_OK) { + if (error != NULL) *error = [NSError git_errorFor:gitError description:@"Failed to get tree entry %@", path]; + return nil; + } + + GTTreeEntry *entry = [self createEntryWithEntry:internalEntry error:error]; + git_tree_entry_free(internalEntry); + return entry; } - (git_tree *)git_tree { @@ -79,7 +92,7 @@ static int treewalk_cb(const char *root, const git_tree_entry *git_entry, void * NSString *rootString = @(root); GTTreeEntry *parentEntry = enumerationStruct->directoryStructure[rootString]; GTTree *parentTree = parentEntry != nil ? parentEntry.tree : enumerationStruct->myself; - GTTreeEntry *entry = [GTTreeEntry entryWithEntry:git_entry parentTree:parentTree]; + GTTreeEntry *entry = [GTTreeEntry entryWithEntry:git_entry parentTree:parentTree error:nil]; if (entry.type == GTObjectTypeTree) { NSString *path = [rootString stringByAppendingPathComponent:entry.name]; diff --git a/ObjectiveGit/GTTreeBuilder.h b/ObjectiveGit/GTTreeBuilder.h index 41a7cfde8..cfa5f8842 100644 --- a/ObjectiveGit/GTTreeBuilder.h +++ b/ObjectiveGit/GTTreeBuilder.h @@ -45,6 +45,8 @@ typedef NS_ENUM(NSInteger, GTFileMode) { @class GTRepository; @class GTOID; +NS_ASSUME_NONNULL_BEGIN + /// A tree builder is used to create or modify trees in memory and write them as /// tree objects to a repository. @interface GTTreeBuilder : NSObject @@ -52,13 +54,16 @@ typedef NS_ENUM(NSInteger, GTFileMode) { /// Get the number of entries listed in a treebuilder. @property (nonatomic, readonly) NSUInteger entryCount; -/// Initializes the receiver, optionally from an existing tree. +- (instancetype)init NS_UNAVAILABLE; + +/// Initializes the receiver, optionally from an existing tree. Designated initializer. /// -/// treeOrNil - Source tree (or nil) -/// error - The error if one occurred. +/// treeOrNil - Source tree (or nil) +/// repository - The repository in which to build the tree. Must not be nil. +/// error - The error if one occurred. /// /// Returns the initialized object, or nil if an error occurred. -- (id)initWithTree:(GTTree *)treeOrNil error:(NSError **)error; +- (instancetype _Nullable)initWithTree:(GTTree * _Nullable)treeOrNil repository:(GTRepository *)repository error:(NSError **)error NS_DESIGNATED_INITIALIZER; /// The underlying `git_treebuilder` object. - (git_treebuilder *)git_treebuilder __attribute__((objc_returns_inner_pointer)); @@ -69,7 +74,7 @@ typedef NS_ENUM(NSInteger, GTFileMode) { /// Filter the entries in the tree. /// /// filterBlock - A block which returns YES for entries which should be filtered -/// from the index. +/// from the index. Must not be nil. - (void)filter:(BOOL (^)(const git_tree_entry *entry))filterBlock; /// Get an entry from the builder from its file name. @@ -77,7 +82,7 @@ typedef NS_ENUM(NSInteger, GTFileMode) { /// fileName - File name for the object in the index. Cannot be nil. /// /// Returns the matching entry or nil if it doesn't exist. -- (GTTreeEntry *)entryWithFileName:(NSString *)fileName; +- (GTTreeEntry * _Nullable)entryWithFileName:(NSString *)fileName; /// Adds or updates the entry for the file name with the given data. When the /// tree is written, a blob will be inserted into the object database containing @@ -89,7 +94,7 @@ typedef NS_ENUM(NSInteger, GTFileMode) { /// error - The error if one occurred. /// /// Returns the added entry, or nil if an error occurred -- (GTTreeEntry *)addEntryWithData:(NSData *)data fileName:(NSString *)fileName fileMode:(GTFileMode)fileMode error:(NSError **)error; +- (GTTreeEntry * _Nullable)addEntryWithData:(NSData *)data fileName:(NSString *)fileName fileMode:(GTFileMode)fileMode error:(NSError **)error; /// Add or update an entry to the builder. /// @@ -106,11 +111,11 @@ typedef NS_ENUM(NSInteger, GTFileMode) { /// the type of the pointed at object. /// /// Returns the added entry, or nil if an error occurred. -- (GTTreeEntry *)addEntryWithOID:(GTOID *)oid fileName:(NSString *)fileName fileMode:(GTFileMode)fileMode error:(NSError **)error; +- (GTTreeEntry * _Nullable)addEntryWithOID:(GTOID *)oid fileName:(NSString *)fileName fileMode:(GTFileMode)fileMode error:(NSError **)error; /// Remove an entry from the builder by its file name. /// -/// fileName - File name for the object in the tree. +/// fileName - File name for the object in the tree. Must not be nil. /// error - The error if one occurred. /// /// Returns YES if the entry was removed, or NO if an error occurred. @@ -118,10 +123,11 @@ typedef NS_ENUM(NSInteger, GTFileMode) { /// Write the contents of the tree builder as a tree object. /// -/// repository - Repository in which to write the tree. -/// error - The error if one occurred. +/// error - The error if one occurred. /// /// Returns the written tree, or nil if an error occurred. -- (GTTree *)writeTreeToRepository:(GTRepository *)repository error:(NSError **)error; +- (GTTree * _Nullable)writeTree:(NSError **)error; @end + +NS_ASSUME_NONNULL_END diff --git a/ObjectiveGit/GTTreeBuilder.m b/ObjectiveGit/GTTreeBuilder.m index 04a1ecf2c..d53118e9d 100644 --- a/ObjectiveGit/GTTreeBuilder.m +++ b/ObjectiveGit/GTTreeBuilder.m @@ -41,13 +41,7 @@ @interface GTTreeBuilder () @property (nonatomic, assign, readonly) git_treebuilder *git_treebuilder; - -// Data to be written with the tree, keyed by the file name. This should only be -// accessed while synchronized on self. -// -// This is needed because we don't want to add the entries to the object -// database until the tree's been written. -@property (nonatomic, strong, readonly) NSMutableDictionary *fileNameToPendingData; +@property (nonatomic, strong, readonly) GTRepository *repository; @end @@ -61,18 +55,24 @@ - (NSUInteger)entryCount { #pragma mark Lifecycle -- (id)initWithTree:(GTTree *)treeOrNil error:(NSError **)error { +- (instancetype)init { + NSAssert(NO, @"Call to an unavailable initializer."); + return nil; +} + +- (instancetype)initWithTree:(GTTree *)treeOrNil repository:(GTRepository *)repository error:(NSError **)error { + NSParameterAssert(repository != nil); + self = [super init]; if (self == nil) return nil; - int status = git_treebuilder_create(&_git_treebuilder, treeOrNil.git_tree); + int status = git_treebuilder_new(&_git_treebuilder, repository.git_repository, treeOrNil.git_tree); if (status != GIT_OK) { if (error != NULL) *error = [NSError git_errorFor:status description:@"Failed to create tree builder with tree %@.", treeOrNil.SHA]; return nil; } - _fileNameToPendingData = [NSMutableDictionary dictionary]; - + _repository = repository; return self; } @@ -86,7 +86,7 @@ - (void)dealloc { #pragma mark Modification - (void)clear { - git_treebuilder_clear(self.git_treebuilder); + git_treebuilder_clear(self.git_treebuilder); } static int filter_callback(const git_tree_entry *entry, void *payload) { @@ -105,20 +105,19 @@ - (GTTreeEntry *)entryWithFileName:(NSString *)fileName { const git_tree_entry *entry = git_treebuilder_get(self.git_treebuilder, fileName.UTF8String); if (entry == NULL) return nil; - - return [GTTreeEntry entryWithEntry:entry parentTree:nil]; + + return [GTTreeEntry entryWithEntry:entry parentTree:nil error:nil]; } - (GTTreeEntry *)addEntryWithData:(NSData *)data fileName:(NSString *)fileName fileMode:(GTFileMode)fileMode error:(NSError **)error { NSParameterAssert(data != nil); NSParameterAssert(fileName != nil); - GTOID *OID = [GTOID OIDByHashingData:data type:GTObjectTypeBlob error:error]; - if (OID == nil) return nil; + GTObjectDatabase *odb = [self.repository objectDatabaseWithError:error]; + if (odb == nil) return nil; - @synchronized (self) { - self.fileNameToPendingData[fileName] = data; - } + GTOID *OID = [odb writeData:data type:GTObjectTypeBlob error:error]; + if (OID == nil) return nil; return [self addEntryWithOID:OID fileName:fileName fileMode:fileMode error:error]; } @@ -129,13 +128,13 @@ - (GTTreeEntry *)addEntryWithOID:(GTOID *)oid fileName:(NSString *)fileName file const git_tree_entry *entry = NULL; int status = git_treebuilder_insert(&entry, self.git_treebuilder, fileName.UTF8String, oid.git_oid, (git_filemode_t)fileMode); - + if (status != GIT_OK) { if (error != NULL) *error = [NSError git_errorFor:status description:@"Failed to add entry %@ to tree builder.", oid.SHA]; return nil; } - - return [GTTreeEntry entryWithEntry:entry parentTree:nil]; + + return [GTTreeEntry entryWithEntry:entry parentTree:nil error:error]; } - (BOOL)removeEntryWithFileName:(NSString *)fileName error:(NSError **)error { @@ -144,53 +143,25 @@ - (BOOL)removeEntryWithFileName:(NSString *)fileName error:(NSError **)error { if (error != NULL) *error = [NSError git_errorFor:status description:@"Failed to remove entry with name %@ from tree builder.", fileName]; } - @synchronized (self) { - [self.fileNameToPendingData removeObjectForKey:fileName]; - } - return status == GIT_OK; } -- (BOOL)writePendingDataToRepository:(GTRepository *)repository error:(NSError **)error { - NSDictionary *copied; - @synchronized (self) { - copied = [self.fileNameToPendingData copy]; - [self.fileNameToPendingData removeAllObjects]; - } - - if (copied.count != 0) { - GTObjectDatabase *odb = [repository objectDatabaseWithError:error]; - if (odb == nil) return NO; - - for (NSString *fileName in copied) { - NSData *data = copied[fileName]; - GTOID *dataOID = [odb writeData:data type:GTObjectTypeBlob error:error]; - if (dataOID == nil) return NO; - } - } - - return YES; -} - -- (GTTree *)writeTreeToRepository:(GTRepository *)repository error:(NSError **)error { - BOOL success = [self writePendingDataToRepository:repository error:error]; - if (!success) return nil; - +- (GTTree *)writeTree:(NSError **)error { git_oid treeOid; - int status = git_treebuilder_write(&treeOid, repository.git_repository, self.git_treebuilder); + int status = git_treebuilder_write(&treeOid, self.git_treebuilder); if (status != GIT_OK) { if (error != NULL) *error = [NSError git_errorFor:status description:@"Failed to write tree in repository."]; return nil; } - + git_object *object = NULL; - status = git_object_lookup(&object, repository.git_repository, &treeOid, GIT_OBJ_TREE); + status = git_object_lookup(&object, self.repository.git_repository, &treeOid, GIT_OBJECT_TREE); if (status != GIT_OK) { if (error != NULL) *error = [NSError git_errorFor:status description:@"Failed to lookup tree in repository."]; return nil; } - - return [GTObject objectWithObj:object inRepository:repository]; + + return [GTObject objectWithObj:object inRepository:self.repository]; } @end diff --git a/ObjectiveGit/GTTreeEntry.h b/ObjectiveGit/GTTreeEntry.h index 67e3c1027..f90bc135a 100644 --- a/ObjectiveGit/GTTreeEntry.h +++ b/ObjectiveGit/GTTreeEntry.h @@ -31,17 +31,21 @@ @class GTTree; +NS_ASSUME_NONNULL_BEGIN + @interface GTTreeEntry : NSObject -/// Initializer and convience methods. -- (instancetype)initWithEntry:(const git_tree_entry *)theEntry parentTree:(GTTree *)parent; -+ (instancetype)entryWithEntry:(const git_tree_entry *)theEntry parentTree:(GTTree *)parent; +/// Initializes the receiver. +- (instancetype _Nullable)initWithEntry:(const git_tree_entry *)theEntry parentTree:(GTTree * _Nullable)parent error:(NSError **)error; + +/// Convience class initializer. ++ (instancetype _Nullable)entryWithEntry:(const git_tree_entry *)theEntry parentTree:(GTTree * _Nullable)parent error:(NSError **)error; /// The underlying `git_tree_entry`. -- (const git_tree_entry *)git_tree_entry __attribute__((objc_returns_inner_pointer)); +- (git_tree_entry *)git_tree_entry __attribute__((objc_returns_inner_pointer)); -/// The entry's parent tree. This may be nil if nil is passed in to -initWithEntry: -@property (nonatomic, strong, readonly) GTTree *tree; +/// The entry's parent tree. This may be nil if nil parentTree is passed in to -initWithEntry: +@property (nonatomic, strong, readonly) GTTree * _Nullable tree; /// The filename of the entry @property (nonatomic, copy, readonly) NSString *name; @@ -50,27 +54,29 @@ @property (nonatomic, readonly) NSInteger attributes; /// The SHA hash of the entry -@property (nonatomic, copy, readonly) NSString *SHA; +@property (nonatomic, copy, readonly) NSString * _Nullable SHA; /// The type of GTObject that -object: will return. @property (nonatomic, readonly) GTObjectType type; /// The OID of the entry. -@property (nonatomic, strong, readonly) GTOID *OID; +@property (nonatomic, strong, readonly) GTOID * _Nullable OID; /// Convert the entry into an GTObject /// /// error - will be filled if an error occurs /// /// Returns this entry as a GTObject or nil if an error occurred. -- (GTObject *)GTObject:(NSError **)error; +- (GTObject * _Nullable)GTObject:(NSError **)error; @end @interface GTObject (GTTreeEntry) -+ (instancetype)objectWithTreeEntry:(GTTreeEntry *)treeEntry error:(NSError **)error; -- (instancetype)initWithTreeEntry:(GTTreeEntry *)treeEntry error:(NSError **)error; ++ (instancetype _Nullable)objectWithTreeEntry:(GTTreeEntry *)treeEntry error:(NSError **)error; +- (instancetype _Nullable)initWithTreeEntry:(GTTreeEntry *)treeEntry error:(NSError **)error; @end + +NS_ASSUME_NONNULL_END diff --git a/ObjectiveGit/GTTreeEntry.m b/ObjectiveGit/GTTreeEntry.m index b29bb4cf2..946b1f06f 100644 --- a/ObjectiveGit/GTTreeEntry.m +++ b/ObjectiveGit/GTTreeEntry.m @@ -38,7 +38,7 @@ #import "git2/errors.h" @interface GTTreeEntry () -@property (nonatomic, assign, readonly) const git_tree_entry *git_tree_entry; +@property (nonatomic, assign, readonly) git_tree_entry *git_tree_entry; @end @implementation GTTreeEntry @@ -64,23 +64,39 @@ - (BOOL)isEqualToEntry:(GTTreeEntry *)treeEntry { return git_tree_entry_cmp(self.git_tree_entry, treeEntry.git_tree_entry) == 0 ? YES : NO; } +- (void)dealloc { + git_tree_entry_free(_git_tree_entry); +} + #pragma mark API -- (instancetype)initWithEntry:(const git_tree_entry *)theEntry parentTree:(GTTree *)parent { +- (instancetype)initWithEntry:(const git_tree_entry *)theEntry parentTree:(GTTree *)parent error:(NSError **)error { NSParameterAssert(theEntry != NULL); - if((self = [super init])) { - _git_tree_entry = theEntry; - _tree = parent; + + self = [super init]; + if (self == nil) return nil; + + git_tree_entry *copyOfEntry = nil; + int gitError = git_tree_entry_dup(©OfEntry, theEntry); + if (gitError != GIT_OK) { + if (error != NULL) *error = [NSError git_errorFor:gitError description:@"Failed to duplicate tree entry."]; + return nil; } + + _git_tree_entry = copyOfEntry; + _tree = parent; + return self; } -+ (instancetype)entryWithEntry:(const git_tree_entry *)theEntry parentTree:(GTTree *)parent { - return [[self alloc] initWithEntry:theEntry parentTree:parent]; ++ (instancetype)entryWithEntry:(const git_tree_entry *)theEntry parentTree:(GTTree *)parent error:(NSError **)error { + return [[self alloc] initWithEntry:theEntry parentTree:parent error:error]; } - (NSString *)name { - return @(git_tree_entry_name(self.git_tree_entry)); + NSString *name = @(git_tree_entry_name(self.git_tree_entry)); + NSAssert(name, @"name was nil"); + return name; } - (NSInteger)attributes { diff --git a/ObjectiveGit/ObjectiveGit.h b/ObjectiveGit/ObjectiveGit.h index 0108166a0..5c8cba5bc 100644 --- a/ObjectiveGit/ObjectiveGit.h +++ b/ObjectiveGit/ObjectiveGit.h @@ -37,8 +37,11 @@ FOUNDATION_EXPORT const unsigned char ObjectiveGitVersionString[]; #import #import #import +#import #import #import +#import +#import #import #import #import @@ -67,6 +70,8 @@ FOUNDATION_EXPORT const unsigned char ObjectiveGitVersionString[]; #import #import #import +#import +#import #import #import diff --git a/ObjectiveGit/ObjectiveGit.m b/ObjectiveGit/ObjectiveGit.m index c2942cda4..b44bca615 100644 --- a/ObjectiveGit/ObjectiveGit.m +++ b/ObjectiveGit/ObjectiveGit.m @@ -6,9 +6,9 @@ // Copyright (c) 2012 GitHub, Inc. All rights reserved. // -#import "git2/threads.h" +#import "git2/global.h" __attribute__((constructor)) -static void GTSetupThreads(void) { - git_threads_init(); +static void GTSetup(void) { + git_libgit2_init(); } diff --git a/ObjectiveGitFramework.xcodeproj/project.pbxproj b/ObjectiveGitFramework.xcodeproj/project.pbxproj index a726d3e6a..26da37c95 100644 --- a/ObjectiveGitFramework.xcodeproj/project.pbxproj +++ b/ObjectiveGitFramework.xcodeproj/project.pbxproj @@ -3,7 +3,7 @@ archiveVersion = 1; classes = { }; - objectVersion = 46; + objectVersion = 52; objects = { /* Begin PBXAggregateTarget section */ @@ -11,7 +11,7 @@ isa = PBXAggregateTarget; buildConfigurationList = 6A28265417C69CB400C6A948 /* Build configuration list for PBXAggregateTarget "OpenSSL-iOS" */; buildPhases = ( - 6A28265317C69CB400C6A948 /* ShellScript */, + 6A28265317C69CB400C6A948 /* OpenSSL-iOS */, ); dependencies = ( ); @@ -22,7 +22,7 @@ isa = PBXAggregateTarget; buildConfigurationList = 6A3C609217D5963700382DFF /* Build configuration list for PBXAggregateTarget "libssh2-iOS" */; buildPhases = ( - 6A3C609117D5963700382DFF /* ShellScript */, + 6A3C609117D5963700382DFF /* libssh2-iOS */, ); dependencies = ( 6A3C609D17D5964E00382DFF /* PBXTargetDependency */, @@ -34,7 +34,7 @@ isa = PBXAggregateTarget; buildConfigurationList = D0A330EE16027F1E00A616FA /* Build configuration list for PBXAggregateTarget "libgit2" */; buildPhases = ( - D0A330F116027F2300A616FA /* ShellScript */, + D0A330F116027F2300A616FA /* libgit2 */, ); dependencies = ( ); @@ -45,10 +45,9 @@ isa = PBXAggregateTarget; buildConfigurationList = D0A330F316027F3700A616FA /* Build configuration list for PBXAggregateTarget "libgit2-iOS" */; buildPhases = ( - D0A330F616027F3B00A616FA /* ShellScript */, + D0A330F616027F3B00A616FA /* libgit2-iOS */, ); dependencies = ( - 6A28265B17C69D6300C6A948 /* PBXTargetDependency */, 6A3C609F17D5965700382DFF /* PBXTargetDependency */, ); name = "libgit2-iOS"; @@ -61,6 +60,12 @@ 2089E43C17D9A58000F451DA /* GTTagSpec.m in Sources */ = {isa = PBXBuildFile; fileRef = 2089E43B17D9A58000F451DA /* GTTagSpec.m */; }; 20F43DE318A2F668007D3621 /* GTRepository+Blame.h in Headers */ = {isa = PBXBuildFile; fileRef = 20F43DE118A2F667007D3621 /* GTRepository+Blame.h */; settings = {ATTRIBUTES = (Public, ); }; }; 20F43DE618A2F668007D3621 /* GTRepository+Blame.m in Sources */ = {isa = PBXBuildFile; fileRef = 20F43DE218A2F667007D3621 /* GTRepository+Blame.m */; }; + 23BB67C11C7DF60300A37A66 /* GTRepository+PullSpec.m in Sources */ = {isa = PBXBuildFile; fileRef = F8EFA0361B405020000FF7D0 /* GTRepository+PullSpec.m */; }; + 23BB67C21C7DF60400A37A66 /* GTRepository+PullSpec.m in Sources */ = {isa = PBXBuildFile; fileRef = F8EFA0361B405020000FF7D0 /* GTRepository+PullSpec.m */; }; + 23F39FAD1C86DB1C00849F3C /* GTRepository+Merging.h in Headers */ = {isa = PBXBuildFile; fileRef = 23F39FAB1C86DB1C00849F3C /* GTRepository+Merging.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 23F39FAE1C86DB1C00849F3C /* GTRepository+Merging.m in Sources */ = {isa = PBXBuildFile; fileRef = 23F39FAC1C86DB1C00849F3C /* GTRepository+Merging.m */; }; + 23F39FAF1C86DD0A00849F3C /* GTRepository+Merging.h in Headers */ = {isa = PBXBuildFile; fileRef = 23F39FAB1C86DB1C00849F3C /* GTRepository+Merging.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 23F39FB01C86E01800849F3C /* GTRepository+Merging.m in Sources */ = {isa = PBXBuildFile; fileRef = 23F39FAC1C86DB1C00849F3C /* GTRepository+Merging.m */; }; 3011D86B1668E48500CE3409 /* GTDiffFile.h in Headers */ = {isa = PBXBuildFile; fileRef = 3011D8691668E48500CE3409 /* GTDiffFile.h */; settings = {ATTRIBUTES = (Public, ); }; }; 3011D86D1668E48500CE3409 /* GTDiffFile.m in Sources */ = {isa = PBXBuildFile; fileRef = 3011D86A1668E48500CE3409 /* GTDiffFile.m */; }; 3011D8711668E78500CE3409 /* GTDiffHunk.h in Headers */ = {isa = PBXBuildFile; fileRef = 3011D86F1668E78500CE3409 /* GTDiffHunk.h */; settings = {ATTRIBUTES = (Public, ); }; }; @@ -82,12 +87,23 @@ 30DCBA7317B4791A009B0EBD /* NSArray+StringArray.m in Sources */ = {isa = PBXBuildFile; fileRef = 30DCBA7017B4791A009B0EBD /* NSArray+StringArray.m */; }; 30FDC07F16835A8100654BF0 /* GTDiffLine.h in Headers */ = {isa = PBXBuildFile; fileRef = 30FDC07D16835A8100654BF0 /* GTDiffLine.h */; settings = {ATTRIBUTES = (Public, ); }; }; 30FDC08116835A8100654BF0 /* GTDiffLine.m in Sources */ = {isa = PBXBuildFile; fileRef = 30FDC07E16835A8100654BF0 /* GTDiffLine.m */; }; - 4D103ADD1819CFAA0029DB24 /* libiconv.dylib in Frameworks */ = {isa = PBXBuildFile; fileRef = 4D103ADC1819CFAA0029DB24 /* libiconv.dylib */; }; 4D123240178E009E0048F785 /* GTRepositoryCommittingSpec.m in Sources */ = {isa = PBXBuildFile; fileRef = 4D12323F178E009E0048F785 /* GTRepositoryCommittingSpec.m */; }; 4D1C40D8182C006D00BE2960 /* GTBlobSpec.m in Sources */ = {isa = PBXBuildFile; fileRef = 4D1C40D7182C006D00BE2960 /* GTBlobSpec.m */; }; 4D79C0EE17DF9F4D00997DE4 /* GTCredential.h in Headers */ = {isa = PBXBuildFile; fileRef = 4D79C0EC17DF9F4D00997DE4 /* GTCredential.h */; settings = {ATTRIBUTES = (Public, ); }; }; 4D79C0EF17DF9F4D00997DE4 /* GTCredential.m in Sources */ = {isa = PBXBuildFile; fileRef = 4D79C0ED17DF9F4D00997DE4 /* GTCredential.m */; }; + 4D9BCD25206D84B2003CD3CE /* libgit2.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 4D9BCD23206D84AD003CD3CE /* libgit2.a */; }; + 4DB9711D2645CA3700D14944 /* Quick.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 4DB970A32645C8BB00D14944 /* Quick.framework */; }; + 4DB9711F2645CA5200D14944 /* ZipArchive.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 4DB971172645C8F300D14944 /* ZipArchive.framework */; }; + 4DB971202645CA5D00D14944 /* Quick.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 4DB970AD2645C8BB00D14944 /* Quick.framework */; }; + 4DB971212645CA6600D14944 /* Nimble.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 4DB971062645C8F300D14944 /* Nimble.framework */; }; + 4DB971222645CA6D00D14944 /* ZipArchive.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 4DB971152645C8F300D14944 /* ZipArchive.framework */; }; 4DBA4A3217DA73CE006CD5F5 /* GTRemoteSpec.m in Sources */ = {isa = PBXBuildFile; fileRef = 4DBA4A3117DA73CE006CD5F5 /* GTRemoteSpec.m */; }; + 4DC55AE51AD859AD0032563C /* GTCheckoutOptions.h in Headers */ = {isa = PBXBuildFile; fileRef = 4DC55AE31AD859AD0032563C /* GTCheckoutOptions.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 4DC55AE61AD859AD0032563C /* GTCheckoutOptions.h in Headers */ = {isa = PBXBuildFile; fileRef = 4DC55AE31AD859AD0032563C /* GTCheckoutOptions.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 4DC55AE71AD859AD0032563C /* GTCheckoutOptions.m in Sources */ = {isa = PBXBuildFile; fileRef = 4DC55AE41AD859AD0032563C /* GTCheckoutOptions.m */; }; + 4DC55AE81AD859AD0032563C /* GTCheckoutOptions.m in Sources */ = {isa = PBXBuildFile; fileRef = 4DC55AE41AD859AD0032563C /* GTCheckoutOptions.m */; }; + 4DD769A92645D214007599B8 /* Nimble.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 4DB971022645C8F300D14944 /* Nimble.framework */; }; + 4DD7422C25D3F8CB009D9A17 /* libgit2-mac.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 4DD7422B25D3F8CB009D9A17 /* libgit2-mac.a */; }; 4DFFB15B183AA8D600D1565E /* GTRepository+RemoteOperations.h in Headers */ = {isa = PBXBuildFile; fileRef = 4DFFB159183AA8D600D1565E /* GTRepository+RemoteOperations.h */; settings = {ATTRIBUTES = (Public, ); }; }; 4DFFB15C183AA8D600D1565E /* GTRepository+RemoteOperations.m in Sources */ = {isa = PBXBuildFile; fileRef = 4DFFB15A183AA8D600D1565E /* GTRepository+RemoteOperations.m */; }; 55C8055013861FE7004DCB0F /* GTObjectDatabase.m in Sources */ = {isa = PBXBuildFile; fileRef = 55C8054D13861F34004DCB0F /* GTObjectDatabase.m */; }; @@ -101,7 +117,6 @@ 6EEB51A2199D62B9001D72C0 /* GTFetchHeadEntry.m in Sources */ = {isa = PBXBuildFile; fileRef = 6EEB51A0199D62B9001D72C0 /* GTFetchHeadEntry.m */; }; 79262F1013C697C100A4B1EA /* git2 in Copy git2 Headers */ = {isa = PBXBuildFile; fileRef = 79262F0E13C697BE00A4B1EA /* git2 */; }; 79262F8B13C69B1600A4B1EA /* git2.h in Headers */ = {isa = PBXBuildFile; fileRef = 79262F8A13C69B1600A4B1EA /* git2.h */; settings = {ATTRIBUTES = (Public, ); }; }; - 8803DA871313145700E6E818 /* libz.dylib in Frameworks */ = {isa = PBXBuildFile; fileRef = 8803DA861313145700E6E818 /* libz.dylib */; }; 880EE66118AE700500B82455 /* GTFilter.h in Headers */ = {isa = PBXBuildFile; fileRef = 880EE65F18AE700500B82455 /* GTFilter.h */; settings = {ATTRIBUTES = (Public, ); }; }; 880EE66318AE700500B82455 /* GTFilter.m in Sources */ = {isa = PBXBuildFile; fileRef = 880EE66018AE700500B82455 /* GTFilter.m */; }; 882154691714740500D76B76 /* GTReflog.h in Headers */ = {isa = PBXBuildFile; fileRef = 882154671714740500D76B76 /* GTReflog.h */; settings = {ATTRIBUTES = (Public, ); }; }; @@ -116,8 +131,6 @@ 88328128173D8A64006D7DCF /* GTTreeSpec.m in Sources */ = {isa = PBXBuildFile; fileRef = 88328127173D8A64006D7DCF /* GTTreeSpec.m */; }; 883CD6AB1600EBC600F57354 /* GTRemote.h in Headers */ = {isa = PBXBuildFile; fileRef = 883CD6A91600EBC600F57354 /* GTRemote.h */; settings = {ATTRIBUTES = (Public, ); }; }; 883CD6AC1600EBC600F57354 /* GTRemote.m in Sources */ = {isa = PBXBuildFile; fileRef = 883CD6AA1600EBC600F57354 /* GTRemote.m */; }; - 884C8A3719FF4B4D0017E98D /* libz.dylib in Frameworks */ = {isa = PBXBuildFile; fileRef = 884C8A3619FF4B4D0017E98D /* libz.dylib */; }; - 884C8A3919FF4B6D0017E98D /* libiconv.dylib in Frameworks */ = {isa = PBXBuildFile; fileRef = 884C8A3819FF4B6D0017E98D /* libiconv.dylib */; }; 884C8A3A19FF4B890017E98D /* EXTScope.m in Sources */ = {isa = PBXBuildFile; fileRef = 306123AA17EA5261006591D4 /* EXTScope.m */; }; 886E622A18AEBF75000611A0 /* GTFilterSource.h in Headers */ = {isa = PBXBuildFile; fileRef = 886E622818AEBF75000611A0 /* GTFilterSource.h */; settings = {ATTRIBUTES = (Public, ); }; }; 886E622C18AEBF75000611A0 /* GTFilterSource.m in Sources */ = {isa = PBXBuildFile; fileRef = 886E622918AEBF75000611A0 /* GTFilterSource.m */; }; @@ -129,6 +142,10 @@ 889923FB19FF5DD40092A9A6 /* git2 in Headers */ = {isa = PBXBuildFile; fileRef = 889923F919FF5DD40092A9A6 /* git2 */; settings = {ATTRIBUTES = (Public, ); }; }; 88A994BA16FCE7D400402C7B /* GTBranchSpec.m in Sources */ = {isa = PBXBuildFile; fileRef = 88A994B916FCE7D400402C7B /* GTBranchSpec.m */; }; 88A994CB16FCED1D00402C7B /* QuickSpec+GTFixtures.m in Sources */ = {isa = PBXBuildFile; fileRef = 88A994CA16FCED1D00402C7B /* QuickSpec+GTFixtures.m */; }; + 88B2131C1B20E785005CF2C5 /* GTRepository+References.h in Headers */ = {isa = PBXBuildFile; fileRef = 88B2131A1B20E785005CF2C5 /* GTRepository+References.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 88B2131D1B20E785005CF2C5 /* GTRepository+References.h in Headers */ = {isa = PBXBuildFile; fileRef = 88B2131A1B20E785005CF2C5 /* GTRepository+References.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 88B2131E1B20E785005CF2C5 /* GTRepository+References.m in Sources */ = {isa = PBXBuildFile; fileRef = 88B2131B1B20E785005CF2C5 /* GTRepository+References.m */; }; + 88B2131F1B20E785005CF2C5 /* GTRepository+References.m in Sources */ = {isa = PBXBuildFile; fileRef = 88B2131B1B20E785005CF2C5 /* GTRepository+References.m */; }; 88BC0E5018EF4F3600C7D0E6 /* GTRepository+Reset.h in Headers */ = {isa = PBXBuildFile; fileRef = 88BC0E4E18EF4F3600C7D0E6 /* GTRepository+Reset.h */; settings = {ATTRIBUTES = (Public, ); }; }; 88BC0E5218EF4F3600C7D0E6 /* GTRepository+Reset.m in Sources */ = {isa = PBXBuildFile; fileRef = 88BC0E4F18EF4F3600C7D0E6 /* GTRepository+Reset.m */; }; 88C0BC5917038CF3009E99AA /* GTConfigurationSpec.m in Sources */ = {isa = PBXBuildFile; fileRef = 88C0BC5817038CF3009E99AA /* GTConfigurationSpec.m */; }; @@ -147,7 +164,6 @@ 88F6D9FA1320467100CC0BA8 /* GTCommit.h in Headers */ = {isa = PBXBuildFile; fileRef = BD6C22A41314609A00992935 /* GTCommit.h */; settings = {ATTRIBUTES = (Public, ); }; }; 88F6D9FB1320467500CC0BA8 /* GTObject.h in Headers */ = {isa = PBXBuildFile; fileRef = BD6C22A71314625800992935 /* GTObject.h */; settings = {ATTRIBUTES = (Public, ); }; }; 88F6D9FC1320467800CC0BA8 /* GTSignature.h in Headers */ = {isa = PBXBuildFile; fileRef = BD6C254313148DC900992935 /* GTSignature.h */; settings = {ATTRIBUTES = (Public, ); }; }; - 8DC2EF530486A6940098B216 /* InfoPlist.strings in Resources */ = {isa = PBXBuildFile; fileRef = 089C1666FE841158C02AAC07 /* InfoPlist.strings */; }; 8DC2EF570486A6940098B216 /* Cocoa.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 1058C7B1FEA5585E11CA2CBB /* Cocoa.framework */; }; AA046112134F4D2000DF526B /* GTOdbObject.h in Headers */ = {isa = PBXBuildFile; fileRef = AA046110134F4D2000DF526B /* GTOdbObject.h */; settings = {ATTRIBUTES = (Public, ); }; }; AA046114134F4D2000DF526B /* GTOdbObject.m in Sources */ = {isa = PBXBuildFile; fileRef = AA046111134F4D2000DF526B /* GTOdbObject.m */; }; @@ -175,6 +191,7 @@ BDFAF9C4131C1845000508BC /* GTIndex.m in Sources */ = {isa = PBXBuildFile; fileRef = BDFAF9C2131C1845000508BC /* GTIndex.m */; }; BDFAF9C9131C1868000508BC /* GTIndexEntry.h in Headers */ = {isa = PBXBuildFile; fileRef = BDFAF9C7131C1868000508BC /* GTIndexEntry.h */; settings = {ATTRIBUTES = (Public, ); }; }; BDFAF9CA131C1868000508BC /* GTIndexEntry.m in Sources */ = {isa = PBXBuildFile; fileRef = BDFAF9C8131C1868000508BC /* GTIndexEntry.m */; }; + BEF7E4E01A3A47690035BB8E /* git2 in Copy git2 Headers again */ = {isa = PBXBuildFile; fileRef = 79262F0E13C697BE00A4B1EA /* git2 */; }; D00F6816175D373C004DB9D6 /* GTReferenceSpec.m in Sources */ = {isa = PBXBuildFile; fileRef = D00F6815175D373C004DB9D6 /* GTReferenceSpec.m */; }; D015F7CA17F695E800AD5E1F /* GTRepository+Stashing.h in Headers */ = {isa = PBXBuildFile; fileRef = D015F7C817F695E800AD5E1F /* GTRepository+Stashing.h */; settings = {ATTRIBUTES = (Public, ); }; }; D015F7CC17F695E800AD5E1F /* GTRepository+Stashing.m in Sources */ = {isa = PBXBuildFile; fileRef = D015F7C917F695E800AD5E1F /* GTRepository+Stashing.m */; }; @@ -287,14 +304,12 @@ D040AF78177B9A9E001AD9EB /* GTSignatureSpec.m in Sources */ = {isa = PBXBuildFile; fileRef = D040AF77177B9A9E001AD9EB /* GTSignatureSpec.m */; }; D05FC5E219FAD039008C9348 /* libcrypto.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 6A1F2FD317C6A8F3003DFADE /* libcrypto.a */; }; D05FC5E319FAD03C008C9348 /* libssl.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 6A1F2FD417C6A8F3003DFADE /* libssl.a */; }; - D05FC5E419FAD040008C9348 /* libssh2-ios.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 6A502B8617D6892D00BAF4A5 /* libssh2-ios.a */; }; + D05FC5E419FAD040008C9348 /* libssh2.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 6A502B8617D6892D00BAF4A5 /* libssh2.a */; }; D06D9E011755D10000558C17 /* GTEnumeratorSpec.m in Sources */ = {isa = PBXBuildFile; fileRef = D06D9E001755D10000558C17 /* GTEnumeratorSpec.m */; }; D0751CD918BE520400134314 /* GTFilterListSpec.m in Sources */ = {isa = PBXBuildFile; fileRef = D0751CD818BE520400134314 /* GTFilterListSpec.m */; }; D09C2E361755F16200065E36 /* GTSubmodule.h in Headers */ = {isa = PBXBuildFile; fileRef = D09C2E341755F16200065E36 /* GTSubmodule.h */; settings = {ATTRIBUTES = (Public, ); }; }; D09C2E381755F16200065E36 /* GTSubmodule.m in Sources */ = {isa = PBXBuildFile; fileRef = D09C2E351755F16200065E36 /* GTSubmodule.m */; }; D09C2E51175602A500065E36 /* fixtures.zip in Resources */ = {isa = PBXBuildFile; fileRef = D09C2E50175602A500065E36 /* fixtures.zip */; }; - D0A0128A19F98475007F1914 /* Quick.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = D0A0128819F98475007F1914 /* Quick.framework */; }; - D0A0128C19F9853D007F1914 /* Nimble.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = D0A0128B19F9853D007F1914 /* Nimble.framework */; }; D0A0129519F99EF8007F1914 /* NSDate+GTTimeAdditions.h in Headers */ = {isa = PBXBuildFile; fileRef = 30B1E7EC1703522100D0814D /* NSDate+GTTimeAdditions.h */; settings = {ATTRIBUTES = (Public, ); }; }; D0A0129719F9A660007F1914 /* SwiftSpec.swift in Sources */ = {isa = PBXBuildFile; fileRef = D0A0129619F9A660007F1914 /* SwiftSpec.swift */; }; D0AC906C172F941F00347DC4 /* GTRepositorySpec.m in Sources */ = {isa = PBXBuildFile; fileRef = D0AC906B172F941F00347DC4 /* GTRepositorySpec.m */; }; @@ -306,15 +321,275 @@ DD3D9513182A81E1004AF532 /* GTBlame.m in Sources */ = {isa = PBXBuildFile; fileRef = DD3D9511182A81E1004AF532 /* GTBlame.m */; }; DD3D951C182AB25C004AF532 /* GTBlameHunk.h in Headers */ = {isa = PBXBuildFile; fileRef = DD3D951A182AB25C004AF532 /* GTBlameHunk.h */; settings = {ATTRIBUTES = (Public, ); }; }; DD3D951D182AB25C004AF532 /* GTBlameHunk.m in Sources */ = {isa = PBXBuildFile; fileRef = DD3D951B182AB25C004AF532 /* GTBlameHunk.m */; }; + F81B6B50207B032800AB0836 /* XCTest.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = F8D63871207AE62A00D1FD32 /* XCTest.framework */; }; + F81B6B59207B0D3B00AB0836 /* SwiftSpec.swift in Sources */ = {isa = PBXBuildFile; fileRef = D0A0129619F9A660007F1914 /* SwiftSpec.swift */; }; + F84277BE207B104A008AB8E8 /* XCTest.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = F8D63872207AE63A00D1FD32 /* XCTest.framework */; }; + F86949AA1BF1B79E00A989D3 /* GTUtilityFunctions.m in Sources */ = {isa = PBXBuildFile; fileRef = F8EFA0391B4059ED000FF7D0 /* GTUtilityFunctions.m */; }; + F879D8311B4B788F002D5C07 /* Libgit2FeaturesSpec.m in Sources */ = {isa = PBXBuildFile; fileRef = F879D82F1B4B77F4002D5C07 /* Libgit2FeaturesSpec.m */; }; + F879D83C1B4B7F7D002D5C07 /* ObjectiveGit.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = D01B6ED319F82E2000D411BC /* ObjectiveGit.framework */; }; + F879D8441B4B80C7002D5C07 /* Libgit2FeaturesSpec.m in Sources */ = {isa = PBXBuildFile; fileRef = F879D82F1B4B77F4002D5C07 /* Libgit2FeaturesSpec.m */; }; + F8D007701B4F7CA8009A8DAF /* NSErrorGitSpec.m in Sources */ = {isa = PBXBuildFile; fileRef = D0F4E28917C7F24200BBDE30 /* NSErrorGitSpec.m */; }; + F8D007711B4F7CB0009A8DAF /* NSDataGitSpec.m in Sources */ = {isa = PBXBuildFile; fileRef = D01EFD9F195DEF2200838D24 /* NSDataGitSpec.m */; }; + F8D007721B4F7CB6009A8DAF /* NSArray+StringArraySpec.m in Sources */ = {isa = PBXBuildFile; fileRef = 307623AA17C6C8BD00E2CDF1 /* NSArray+StringArraySpec.m */; }; + F8D007731B4F7CC3009A8DAF /* GTSignatureSpec.m in Sources */ = {isa = PBXBuildFile; fileRef = D040AF77177B9A9E001AD9EB /* GTSignatureSpec.m */; }; + F8D007741B4F7CCC009A8DAF /* GTOIDSpec.m in Sources */ = {isa = PBXBuildFile; fileRef = D040AF6F177B9779001AD9EB /* GTOIDSpec.m */; }; + F8D007761B4F7D10009A8DAF /* GTTimeAdditionsSpec.m in Sources */ = {isa = PBXBuildFile; fileRef = 30B1E7FF1703871900D0814D /* GTTimeAdditionsSpec.m */; }; + F8D0078C1B4FA03B009A8DAF /* GTBlobSpec.m in Sources */ = {isa = PBXBuildFile; fileRef = 4D1C40D7182C006D00BE2960 /* GTBlobSpec.m */; }; + F8D0078D1B4FA03B009A8DAF /* GTBranchSpec.m in Sources */ = {isa = PBXBuildFile; fileRef = 88A994B916FCE7D400402C7B /* GTBranchSpec.m */; }; + F8D0078E1B4FA03B009A8DAF /* GTCommitSpec.m in Sources */ = {isa = PBXBuildFile; fileRef = 88F05AA416011FFD00B7AD1D /* GTCommitSpec.m */; }; + F8D0078F1B4FA03B009A8DAF /* GTConfigurationSpec.m in Sources */ = {isa = PBXBuildFile; fileRef = 88C0BC5817038CF3009E99AA /* GTConfigurationSpec.m */; }; + F8D007901B4FA03B009A8DAF /* GTDiffSpec.m in Sources */ = {isa = PBXBuildFile; fileRef = 30865A90167F503400B1AB6E /* GTDiffSpec.m */; }; + F8D007911B4FA03B009A8DAF /* GTEnumeratorSpec.m in Sources */ = {isa = PBXBuildFile; fileRef = D06D9E001755D10000558C17 /* GTEnumeratorSpec.m */; }; + F8D007921B4FA03B009A8DAF /* GTIndexSpec.m in Sources */ = {isa = PBXBuildFile; fileRef = 8832811E173D8816006D7DCF /* GTIndexSpec.m */; }; + F8D007931B4FA03B009A8DAF /* GTObjectSpec.m in Sources */ = {isa = PBXBuildFile; fileRef = 88F05AA816011FFD00B7AD1D /* GTObjectSpec.m */; }; + F8D007941B4FA03B009A8DAF /* GTReferenceSpec.m in Sources */ = {isa = PBXBuildFile; fileRef = D00F6815175D373C004DB9D6 /* GTReferenceSpec.m */; }; + F8D007951B4FA03B009A8DAF /* GTReflogSpec.m in Sources */ = {isa = PBXBuildFile; fileRef = 88215482171499BE00D76B76 /* GTReflogSpec.m */; }; + F8D007961B4FA03B009A8DAF /* GTRemotePushSpec.m in Sources */ = {isa = PBXBuildFile; fileRef = F8E4A2901A170CA6006485A8 /* GTRemotePushSpec.m */; }; + F8D007971B4FA03B009A8DAF /* GTRemoteSpec.m in Sources */ = {isa = PBXBuildFile; fileRef = 4DBA4A3117DA73CE006CD5F5 /* GTRemoteSpec.m */; }; + F8D007981B4FA03B009A8DAF /* GTBlameSpec.m in Sources */ = {isa = PBXBuildFile; fileRef = 200578C418932A82001C06C3 /* GTBlameSpec.m */; }; + F8D007991B4FA03B009A8DAF /* GTRepositorySpec.m in Sources */ = {isa = PBXBuildFile; fileRef = D0AC906B172F941F00347DC4 /* GTRepositorySpec.m */; }; + F8D0079A1B4FA03B009A8DAF /* GTRepositoryCommittingSpec.m in Sources */ = {isa = PBXBuildFile; fileRef = 4D12323F178E009E0048F785 /* GTRepositoryCommittingSpec.m */; }; + F8D0079B1B4FA03B009A8DAF /* GTSubmoduleSpec.m in Sources */ = {isa = PBXBuildFile; fileRef = D03B7C401756AB370034A610 /* GTSubmoduleSpec.m */; }; + F8D0079C1B4FA03B009A8DAF /* GTTagSpec.m in Sources */ = {isa = PBXBuildFile; fileRef = 2089E43B17D9A58000F451DA /* GTTagSpec.m */; }; + F8D0079D1B4FA03B009A8DAF /* GTTreeBuilderSpec.m in Sources */ = {isa = PBXBuildFile; fileRef = 5BE612921745EEBC00266D8C /* GTTreeBuilderSpec.m */; }; + F8D0079E1B4FA03B009A8DAF /* GTTreeSpec.m in Sources */ = {isa = PBXBuildFile; fileRef = 88328127173D8A64006D7DCF /* GTTreeSpec.m */; }; + F8D0079F1B4FA03B009A8DAF /* GTObjectDatabaseSpec.m in Sources */ = {isa = PBXBuildFile; fileRef = 88948AC81779243600809CDA /* GTObjectDatabaseSpec.m */; }; + F8D007A01B4FA03B009A8DAF /* GTRepository+StatusSpec.m in Sources */ = {isa = PBXBuildFile; fileRef = 30A269AC17B4878C000FE64E /* GTRepository+StatusSpec.m */; }; + F8D007A11B4FA03B009A8DAF /* GTRepositoryStashingSpec.m in Sources */ = {isa = PBXBuildFile; fileRef = D015F7D417F6965400AD5E1F /* GTRepositoryStashingSpec.m */; }; + F8D007A21B4FA03B009A8DAF /* GTFilterSpec.m in Sources */ = {isa = PBXBuildFile; fileRef = 886E623618AECD86000611A0 /* GTFilterSpec.m */; }; + F8D007A31B4FA03B009A8DAF /* GTFilterListSpec.m in Sources */ = {isa = PBXBuildFile; fileRef = D0751CD818BE520400134314 /* GTFilterListSpec.m */; }; + F8D007A41B4FA03B009A8DAF /* GTRepositoryResetSpec.m in Sources */ = {isa = PBXBuildFile; fileRef = 88234B2518F2FE260039972E /* GTRepositoryResetSpec.m */; }; + F8D007A51B4FA03B009A8DAF /* GTDiffDeltaSpec.m in Sources */ = {isa = PBXBuildFile; fileRef = 8870390A1975E3F2004118D7 /* GTDiffDeltaSpec.m */; }; + F8D007A61B4FA03B009A8DAF /* GTRepositoryAttributesSpec.m in Sources */ = {isa = PBXBuildFile; fileRef = 88E353051982EA6B0051001F /* GTRepositoryAttributesSpec.m */; }; + F8D007A71B4FA040009A8DAF /* QuickSpec+GTFixtures.m in Sources */ = {isa = PBXBuildFile; fileRef = 88A994CA16FCED1D00402C7B /* QuickSpec+GTFixtures.m */; }; + F8D007A81B4FA045009A8DAF /* fixtures.zip in Resources */ = {isa = PBXBuildFile; fileRef = D09C2E50175602A500065E36 /* fixtures.zip */; }; + F8D1BDEE1B31FE7C00CDEC90 /* GTRepository+Pull.h in Headers */ = {isa = PBXBuildFile; fileRef = F8D1BDEC1B31FE7C00CDEC90 /* GTRepository+Pull.h */; settings = {ATTRIBUTES = (Public, ); }; }; + F8D1BDEF1B31FE7C00CDEC90 /* GTRepository+Pull.h in Headers */ = {isa = PBXBuildFile; fileRef = F8D1BDEC1B31FE7C00CDEC90 /* GTRepository+Pull.h */; settings = {ATTRIBUTES = (Public, ); }; }; + F8D1BDF01B31FE7C00CDEC90 /* GTRepository+Pull.m in Sources */ = {isa = PBXBuildFile; fileRef = F8D1BDED1B31FE7C00CDEC90 /* GTRepository+Pull.m */; }; + F8D1BDF11B31FE7C00CDEC90 /* GTRepository+Pull.m in Sources */ = {isa = PBXBuildFile; fileRef = F8D1BDED1B31FE7C00CDEC90 /* GTRepository+Pull.m */; }; + F8D6385C207AC74A00D1FD32 /* libiconv.tbd in Frameworks */ = {isa = PBXBuildFile; fileRef = F8D6385B207AC74A00D1FD32 /* libiconv.tbd */; }; + F8D6385D207AC75100D1FD32 /* libz.tbd in Frameworks */ = {isa = PBXBuildFile; fileRef = 23BB67BB1C7DF45300A37A66 /* libz.tbd */; }; + F8D6385F207ACAE600D1FD32 /* libz.tbd in Frameworks */ = {isa = PBXBuildFile; fileRef = F8D6385E207ACAE600D1FD32 /* libz.tbd */; }; + F8D63861207ACAF700D1FD32 /* libiconv.tbd in Frameworks */ = {isa = PBXBuildFile; fileRef = F8D63860207ACAF600D1FD32 /* libiconv.tbd */; }; + F8E4A2911A170CA6006485A8 /* GTRemotePushSpec.m in Sources */ = {isa = PBXBuildFile; fileRef = F8E4A2901A170CA6006485A8 /* GTRemotePushSpec.m */; }; + F8EFA03A1B4059ED000FF7D0 /* GTUtilityFunctions.m in Sources */ = {isa = PBXBuildFile; fileRef = F8EFA0391B4059ED000FF7D0 /* GTUtilityFunctions.m */; }; + F964D5F11CE9D9B200F1D8DD /* GTNote.h in Headers */ = {isa = PBXBuildFile; fileRef = F964D5EF1CE9D9B200F1D8DD /* GTNote.h */; settings = {ATTRIBUTES = (Public, ); }; }; + F964D5F21CE9D9B200F1D8DD /* GTNote.h in Headers */ = {isa = PBXBuildFile; fileRef = F964D5EF1CE9D9B200F1D8DD /* GTNote.h */; settings = {ATTRIBUTES = (Public, ); }; }; + F964D5F31CE9D9B200F1D8DD /* GTNote.m in Sources */ = {isa = PBXBuildFile; fileRef = F964D5F01CE9D9B200F1D8DD /* GTNote.m */; }; + F964D5F51CE9D9B200F1D8DD /* GTNote.m in Sources */ = {isa = PBXBuildFile; fileRef = F964D5F01CE9D9B200F1D8DD /* GTNote.m */; }; + F9D1D4251CEB7BA6009E5855 /* GTNoteSpec.m in Sources */ = {isa = PBXBuildFile; fileRef = F9D1D4221CEB79D1009E5855 /* GTNoteSpec.m */; }; /* End PBXBuildFile section */ /* Begin PBXContainerItemProxy section */ - 6A28265A17C69D6300C6A948 /* PBXContainerItemProxy */ = { + 3D6123BD1A6432F6008F831A /* PBXContainerItemProxy */ = { isa = PBXContainerItemProxy; containerPortal = 0867D690FE84028FC02AAC07 /* Project object */; proxyType = 1; - remoteGlobalIDString = 6A28265217C69CB400C6A948; - remoteInfo = "OpenSSL-iOS"; + remoteGlobalIDString = D0A330ED16027F1E00A616FA; + remoteInfo = libgit2; + }; + 4DB970A22645C8BB00D14944 /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = 4DB970912645C8BA00D14944 /* Quick.xcodeproj */; + proxyType = 2; + remoteGlobalIDString = DAEB6B8E1943873100289F44; + remoteInfo = "Quick-macOS"; + }; + 4DB970A42645C8BB00D14944 /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = 4DB970912645C8BA00D14944 /* Quick.xcodeproj */; + proxyType = 2; + remoteGlobalIDString = DAEB6B991943873100289F44; + remoteInfo = "Quick - macOSTests"; + }; + 4DB970A62645C8BB00D14944 /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = 4DB970912645C8BA00D14944 /* Quick.xcodeproj */; + proxyType = 2; + remoteGlobalIDString = CD89D17B247A673100C1F086; + remoteInfo = QuickIssue853RegressionTests; + }; + 4DB970A82645C8BB00D14944 /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = 4DB970912645C8BA00D14944 /* Quick.xcodeproj */; + proxyType = 2; + remoteGlobalIDString = DA5663E81A4C8D8500193C88; + remoteInfo = "QuickFocused - macOSTests"; + }; + 4DB970AA2645C8BB00D14944 /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = 4DB970912645C8BA00D14944 /* Quick.xcodeproj */; + proxyType = 2; + remoteGlobalIDString = 64076CF51D6D7C2000E2B499; + remoteInfo = "QuickAfterSuite - macOSTests"; + }; + 4DB970AC2645C8BB00D14944 /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = 4DB970912645C8BA00D14944 /* Quick.xcodeproj */; + proxyType = 2; + remoteGlobalIDString = 5A5D117C19473F2100F6D13D; + remoteInfo = "Quick-iOS"; + }; + 4DB970AE2645C8BB00D14944 /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = 4DB970912645C8BA00D14944 /* Quick.xcodeproj */; + proxyType = 2; + remoteGlobalIDString = 5A5D118619473F2100F6D13D; + remoteInfo = "Quick - iOSTests"; + }; + 4DB970B02645C8BB00D14944 /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = 4DB970912645C8BA00D14944 /* Quick.xcodeproj */; + proxyType = 2; + remoteGlobalIDString = DA9876B21A4C70EB0004AA17; + remoteInfo = "QuickFocused - iOSTests"; + }; + 4DB970B22645C8BB00D14944 /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = 4DB970912645C8BA00D14944 /* Quick.xcodeproj */; + proxyType = 2; + remoteGlobalIDString = 64076D081D6D7CD600E2B499; + remoteInfo = "QuickAfterSuite - iOSTests"; + }; + 4DB970B42645C8BB00D14944 /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = 4DB970912645C8BA00D14944 /* Quick.xcodeproj */; + proxyType = 2; + remoteGlobalIDString = 1F118CD51BDCA4AB005013A2; + remoteInfo = "Quick-tvOS"; + }; + 4DB970B62645C8BB00D14944 /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = 4DB970912645C8BA00D14944 /* Quick.xcodeproj */; + proxyType = 2; + remoteGlobalIDString = 1F118CDE1BDCA4AB005013A2; + remoteInfo = "Quick - tvOSTests"; + }; + 4DB970B82645C8BB00D14944 /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = 4DB970912645C8BA00D14944 /* Quick.xcodeproj */; + proxyType = 2; + remoteGlobalIDString = 1F118CF01BDCA4BB005013A2; + remoteInfo = "QuickFocused - tvOSTests"; + }; + 4DB970BA2645C8BB00D14944 /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = 4DB970912645C8BA00D14944 /* Quick.xcodeproj */; + proxyType = 2; + remoteGlobalIDString = 64076D1A1D6D7CEA00E2B499; + remoteInfo = "QuickAfterSuite - tvOSTests"; + }; + 4DB971012645C8F300D14944 /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = 4DB970F72645C8F300D14944 /* Nimble.xcodeproj */; + proxyType = 2; + remoteGlobalIDString = 1F925EAD195C0D6300ED456B; + remoteInfo = "Nimble-macOS"; + }; + 4DB971032645C8F300D14944 /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = 4DB970F72645C8F300D14944 /* Nimble.xcodeproj */; + proxyType = 2; + remoteGlobalIDString = 1F925EB7195C0D6300ED456B; + remoteInfo = "Nimble-macOSTests"; + }; + 4DB971052645C8F300D14944 /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = 4DB970F72645C8F300D14944 /* Nimble.xcodeproj */; + proxyType = 2; + remoteGlobalIDString = 1F1A74291940169200FFFC47; + remoteInfo = "Nimble-iOS"; + }; + 4DB971072645C8F300D14944 /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = 4DB970F72645C8F300D14944 /* Nimble.xcodeproj */; + proxyType = 2; + remoteGlobalIDString = 1F1A74341940169200FFFC47; + remoteInfo = "Nimble-iOSTests"; + }; + 4DB971092645C8F300D14944 /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = 4DB970F72645C8F300D14944 /* Nimble.xcodeproj */; + proxyType = 2; + remoteGlobalIDString = 1F5DF1551BDCA0CE00C3A531; + remoteInfo = "Nimble-tvOS"; + }; + 4DB9710B2645C8F300D14944 /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = 4DB970F72645C8F300D14944 /* Nimble.xcodeproj */; + proxyType = 2; + remoteGlobalIDString = 1F5DF15E1BDCA0CE00C3A531; + remoteInfo = "Nimble-tvOSTests"; + }; + 4DB971142645C8F300D14944 /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = 4DB9710D2645C8F300D14944 /* ZipArchive.xcodeproj */; + proxyType = 2; + remoteGlobalIDString = B423AE1A1C0DF76A0004A2F1; + remoteInfo = "ZipArchive-iOS"; + }; + 4DB971162645C8F300D14944 /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = 4DB9710D2645C8F300D14944 /* ZipArchive.xcodeproj */; + proxyType = 2; + remoteGlobalIDString = AFF75A241C37279600F450AC; + remoteInfo = "ZipArchive-Mac"; + }; + 4DB971182645C8F300D14944 /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = 4DB9710D2645C8F300D14944 /* ZipArchive.xcodeproj */; + proxyType = 2; + remoteGlobalIDString = 37952C261F63B50D00DD6677; + remoteInfo = "ZipArchive-tvos"; + }; + 4DB9711A2645C8F300D14944 /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = 4DB9710D2645C8F300D14944 /* ZipArchive.xcodeproj */; + proxyType = 2; + remoteGlobalIDString = 37952C5E1F63BB7100DD6677; + remoteInfo = "ZipArchive-watchos"; + }; + 4DD769842645D15D007599B8 /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = 4DB970912645C8BA00D14944 /* Quick.xcodeproj */; + proxyType = 1; + remoteGlobalIDString = DAEB6B8D1943873100289F44; + remoteInfo = "Quick-macOS"; + }; + 4DD769862645D15D007599B8 /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = 4DB970F72645C8F300D14944 /* Nimble.xcodeproj */; + proxyType = 1; + remoteGlobalIDString = 1F925EAC195C0D6300ED456B; + remoteInfo = "Nimble-macOS"; + }; + 4DD769882645D15D007599B8 /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = 4DB9710D2645C8F300D14944 /* ZipArchive.xcodeproj */; + proxyType = 1; + remoteGlobalIDString = AFF75A231C37279600F450AC; + remoteInfo = "ZipArchive-Mac"; + }; + 4DD769A32645D16B007599B8 /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = 4DB970912645C8BA00D14944 /* Quick.xcodeproj */; + proxyType = 1; + remoteGlobalIDString = 5A5D117B19473F2100F6D13D; + remoteInfo = "Quick-iOS"; + }; + 4DD769A52645D16B007599B8 /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = 4DB970F72645C8F300D14944 /* Nimble.xcodeproj */; + proxyType = 1; + remoteGlobalIDString = 1F1A74281940169200FFFC47; + remoteInfo = "Nimble-iOS"; + }; + 4DD769A72645D16B007599B8 /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = 4DB9710D2645C8F300D14944 /* ZipArchive.xcodeproj */; + proxyType = 1; + remoteGlobalIDString = B423AE191C0DF76A0004A2F1; + remoteInfo = "ZipArchive-iOS"; }; 6A3C609C17D5964E00382DFF /* PBXContainerItemProxy */ = { isa = PBXContainerItemProxy; @@ -344,12 +619,12 @@ remoteGlobalIDString = D0A330F216027F3600A616FA; remoteInfo = "libgit2-iOS"; }; - D0A330F716027F4900A616FA /* PBXContainerItemProxy */ = { + F879D83D1B4B7F7D002D5C07 /* PBXContainerItemProxy */ = { isa = PBXContainerItemProxy; containerPortal = 0867D690FE84028FC02AAC07 /* Project object */; proxyType = 1; - remoteGlobalIDString = D0A330ED16027F1E00A616FA; - remoteInfo = libgit2; + remoteGlobalIDString = D01B6ED219F82E2000D411BC; + remoteInfo = "ObjectiveGit-iOS"; }; /* End PBXContainerItemProxy section */ @@ -365,15 +640,28 @@ name = "Copy git2 Headers"; runOnlyForDeploymentPostprocessing = 0; }; + BEF7E4DF1A3A47450035BB8E /* Copy git2 Headers again */ = { + isa = PBXCopyFilesBuildPhase; + buildActionMask = 2147483647; + dstPath = Headers/git2/sys; + dstSubfolderSpec = 1; + files = ( + BEF7E4E01A3A47690035BB8E /* git2 in Copy git2 Headers again */, + ); + name = "Copy git2 Headers again"; + runOnlyForDeploymentPostprocessing = 0; + }; /* End PBXCopyFilesBuildPhase section */ /* Begin PBXFileReference section */ - 089C1667FE841158C02AAC07 /* English */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.plist.strings; name = English; path = English.lproj/InfoPlist.strings; sourceTree = ""; }; 1058C7B1FEA5585E11CA2CBB /* Cocoa.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = Cocoa.framework; path = /System/Library/Frameworks/Cocoa.framework; sourceTree = ""; }; 200578C418932A82001C06C3 /* GTBlameSpec.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = GTBlameSpec.m; sourceTree = ""; }; 2089E43B17D9A58000F451DA /* GTTagSpec.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = GTTagSpec.m; sourceTree = ""; }; 20F43DE118A2F667007D3621 /* GTRepository+Blame.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = "GTRepository+Blame.h"; sourceTree = ""; }; 20F43DE218A2F667007D3621 /* GTRepository+Blame.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = "GTRepository+Blame.m"; sourceTree = ""; }; + 23BB67BB1C7DF45300A37A66 /* libz.tbd */ = {isa = PBXFileReference; lastKnownFileType = "sourcecode.text-based-dylib-definition"; name = libz.tbd; path = usr/lib/libz.tbd; sourceTree = SDKROOT; }; + 23F39FAB1C86DB1C00849F3C /* GTRepository+Merging.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = "GTRepository+Merging.h"; sourceTree = ""; }; + 23F39FAC1C86DB1C00849F3C /* GTRepository+Merging.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = "GTRepository+Merging.m"; sourceTree = ""; }; 3011D8691668E48500CE3409 /* GTDiffFile.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = GTDiffFile.h; sourceTree = ""; }; 3011D86A1668E48500CE3409 /* GTDiffFile.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = GTDiffFile.m; sourceTree = ""; }; 3011D86F1668E78500CE3409 /* GTDiffHunk.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = GTDiffHunk.h; sourceTree = ""; }; @@ -399,14 +687,25 @@ 30DCBA7017B4791A009B0EBD /* NSArray+StringArray.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = "NSArray+StringArray.m"; sourceTree = ""; }; 30FDC07D16835A8100654BF0 /* GTDiffLine.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = GTDiffLine.h; sourceTree = ""; }; 30FDC07E16835A8100654BF0 /* GTDiffLine.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = GTDiffLine.m; sourceTree = ""; }; - 4D103ADC1819CFAA0029DB24 /* libiconv.dylib */ = {isa = PBXFileReference; lastKnownFileType = "compiled.mach-o.dylib"; name = libiconv.dylib; path = usr/lib/libiconv.dylib; sourceTree = SDKROOT; }; 4D12323F178E009E0048F785 /* GTRepositoryCommittingSpec.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = GTRepositoryCommittingSpec.m; sourceTree = ""; }; 4D1C40D7182C006D00BE2960 /* GTBlobSpec.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = GTBlobSpec.m; sourceTree = ""; }; 4D79C0EC17DF9F4D00997DE4 /* GTCredential.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = GTCredential.h; sourceTree = ""; }; 4D79C0ED17DF9F4D00997DE4 /* GTCredential.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = GTCredential.m; sourceTree = ""; }; 4D79C0F617DFAA7100997DE4 /* GTCredential+Private.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = "GTCredential+Private.h"; sourceTree = ""; }; - 4D8DADBE181A7D9F001B1202 /* libgit2 */ = {isa = PBXFileReference; lastKnownFileType = folder; name = libgit2; path = External/libgit2; sourceTree = ""; }; + 4D9BCD23206D84AD003CD3CE /* libgit2.a */ = {isa = PBXFileReference; lastKnownFileType = archive.ar; name = libgit2.a; path = External/build/lib/libgit2.a; sourceTree = ""; }; + 4DB97074264596AE00D14944 /* macOS-Application.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = "macOS-Application.xcconfig"; sourceTree = ""; }; + 4DB97075264596AE00D14944 /* macOS-Framework.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = "macOS-Framework.xcconfig"; sourceTree = ""; }; + 4DB97076264596AE00D14944 /* macOS-StaticLibrary.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = "macOS-StaticLibrary.xcconfig"; sourceTree = ""; }; + 4DB97077264596AE00D14944 /* macOS-Base.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = "macOS-Base.xcconfig"; sourceTree = ""; }; + 4DB97078264596AE00D14944 /* macOS-XCTest.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = "macOS-XCTest.xcconfig"; sourceTree = ""; }; + 4DB97079264596AE00D14944 /* macOS-DynamicLibrary.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = "macOS-DynamicLibrary.xcconfig"; sourceTree = ""; }; + 4DB970912645C8BA00D14944 /* Quick.xcodeproj */ = {isa = PBXFileReference; lastKnownFileType = "wrapper.pb-project"; name = Quick.xcodeproj; path = Carthage/Checkouts/Quick/Quick.xcodeproj; sourceTree = ""; }; + 4DB970F72645C8F300D14944 /* Nimble.xcodeproj */ = {isa = PBXFileReference; lastKnownFileType = "wrapper.pb-project"; name = Nimble.xcodeproj; path = Carthage/Checkouts/Nimble/Nimble.xcodeproj; sourceTree = ""; }; + 4DB9710D2645C8F300D14944 /* ZipArchive.xcodeproj */ = {isa = PBXFileReference; lastKnownFileType = "wrapper.pb-project"; name = ZipArchive.xcodeproj; path = Carthage/Checkouts/ZipArchive/ZipArchive.xcodeproj; sourceTree = ""; }; 4DBA4A3117DA73CE006CD5F5 /* GTRemoteSpec.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = GTRemoteSpec.m; sourceTree = ""; }; + 4DC55AE31AD859AD0032563C /* GTCheckoutOptions.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = GTCheckoutOptions.h; sourceTree = ""; }; + 4DC55AE41AD859AD0032563C /* GTCheckoutOptions.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = GTCheckoutOptions.m; sourceTree = ""; }; + 4DD7422B25D3F8CB009D9A17 /* libgit2-mac.a */ = {isa = PBXFileReference; lastKnownFileType = archive.ar; name = "libgit2-mac.a"; path = "External/libgit2-mac.a"; sourceTree = ""; }; 4DE864341794A37E00371A65 /* GTRepository+Private.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = "GTRepository+Private.h"; sourceTree = ""; }; 4DFFB159183AA8D600D1565E /* GTRepository+RemoteOperations.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = "GTRepository+RemoteOperations.h"; sourceTree = ""; }; 4DFFB15A183AA8D600D1565E /* GTRepository+RemoteOperations.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = "GTRepository+RemoteOperations.m"; sourceTree = ""; }; @@ -417,15 +716,13 @@ 5BE612861745EE3300266D8C /* GTTreeBuilder.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = GTTreeBuilder.h; sourceTree = ""; }; 5BE612871745EE3300266D8C /* GTTreeBuilder.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = GTTreeBuilder.m; sourceTree = ""; }; 5BE612921745EEBC00266D8C /* GTTreeBuilderSpec.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = GTTreeBuilderSpec.m; sourceTree = ""; }; - 6A1F2FD317C6A8F3003DFADE /* libcrypto.a */ = {isa = PBXFileReference; lastKnownFileType = archive.ar; name = libcrypto.a; path = "External/ios-openssl/lib/libcrypto.a"; sourceTree = ""; }; - 6A1F2FD417C6A8F3003DFADE /* libssl.a */ = {isa = PBXFileReference; lastKnownFileType = archive.ar; name = libssl.a; path = "External/ios-openssl/lib/libssl.a"; sourceTree = ""; }; - 6A3C60A017D5987600382DFF /* update_libssh2_ios */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.script.sh; name = update_libssh2_ios; path = script/update_libssh2_ios; sourceTree = SOURCE_ROOT; }; - 6A502B8617D6892D00BAF4A5 /* libssh2-ios.a */ = {isa = PBXFileReference; lastKnownFileType = archive.ar; name = "libssh2-ios.a"; path = "External/libssh2-ios/lib/libssh2-ios.a"; sourceTree = ""; }; + 6A1F2FD317C6A8F3003DFADE /* libcrypto.a */ = {isa = PBXFileReference; lastKnownFileType = archive.ar; name = libcrypto.a; path = External/build/lib/libcrypto.a; sourceTree = ""; }; + 6A1F2FD417C6A8F3003DFADE /* libssl.a */ = {isa = PBXFileReference; lastKnownFileType = archive.ar; name = libssl.a; path = External/build/lib/libssl.a; sourceTree = ""; }; + 6A502B8617D6892D00BAF4A5 /* libssh2.a */ = {isa = PBXFileReference; lastKnownFileType = archive.ar; name = libssh2.a; path = External/build/lib/libssh2.a; sourceTree = ""; }; 6EEB519F199D62B9001D72C0 /* GTFetchHeadEntry.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = GTFetchHeadEntry.h; sourceTree = ""; }; 6EEB51A0199D62B9001D72C0 /* GTFetchHeadEntry.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = GTFetchHeadEntry.m; sourceTree = ""; }; 79262F0E13C697BE00A4B1EA /* git2 */ = {isa = PBXFileReference; lastKnownFileType = folder; name = git2; path = External/libgit2/include/git2; sourceTree = ""; }; 79262F8A13C69B1600A4B1EA /* git2.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = git2.h; path = External/libgit2/include/git2.h; sourceTree = ""; }; - 8803DA861313145700E6E818 /* libz.dylib */ = {isa = PBXFileReference; lastKnownFileType = "compiled.mach-o.dylib"; name = libz.dylib; path = usr/lib/libz.dylib; sourceTree = SDKROOT; }; 880EE65F18AE700500B82455 /* GTFilter.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = GTFilter.h; sourceTree = ""; }; 880EE66018AE700500B82455 /* GTFilter.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = GTFilter.m; sourceTree = ""; }; 882154671714740500D76B76 /* GTReflog.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = GTReflog.h; sourceTree = ""; }; @@ -443,20 +740,21 @@ 883CD6A91600EBC600F57354 /* GTRemote.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = GTRemote.h; sourceTree = ""; }; 883CD6AA1600EBC600F57354 /* GTRemote.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = GTRemote.m; sourceTree = ""; }; 883CD6AE1600F01000F57354 /* GTConfiguration+Private.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = "GTConfiguration+Private.h"; sourceTree = ""; }; - 884C8A3619FF4B4D0017E98D /* libz.dylib */ = {isa = PBXFileReference; lastKnownFileType = "compiled.mach-o.dylib"; name = libz.dylib; path = Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS8.1.sdk/usr/lib/libz.dylib; sourceTree = DEVELOPER_DIR; }; - 884C8A3819FF4B6D0017E98D /* libiconv.dylib */ = {isa = PBXFileReference; lastKnownFileType = "compiled.mach-o.dylib"; name = libiconv.dylib; path = Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS8.1.sdk/usr/lib/libiconv.dylib; sourceTree = DEVELOPER_DIR; }; 886E622818AEBF75000611A0 /* GTFilterSource.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = GTFilterSource.h; sourceTree = ""; }; 886E622918AEBF75000611A0 /* GTFilterSource.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = GTFilterSource.m; sourceTree = ""; }; 886E623618AECD86000611A0 /* GTFilterSpec.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = GTFilterSpec.m; sourceTree = ""; }; 8870390A1975E3F2004118D7 /* GTDiffDeltaSpec.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = GTDiffDeltaSpec.m; sourceTree = ""; }; 88746CC217FA1C950005888A /* GTRepository+Committing.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = "GTRepository+Committing.h"; sourceTree = ""; }; 88746CC317FA1C950005888A /* GTRepository+Committing.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = "GTRepository+Committing.m"; sourceTree = ""; }; + 887B948D1A3A38130070D41D /* ObjectiveGit.modulemap */ = {isa = PBXFileReference; lastKnownFileType = "sourcecode.module-map"; path = ObjectiveGit.modulemap; sourceTree = ""; }; 887DAFF615CB1C8000F30D0D /* Security.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = Security.framework; path = System/Library/Frameworks/Security.framework; sourceTree = SDKROOT; }; 88948AC81779243600809CDA /* GTObjectDatabaseSpec.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = GTObjectDatabaseSpec.m; sourceTree = ""; }; 889923F919FF5DD40092A9A6 /* git2 */ = {isa = PBXFileReference; lastKnownFileType = folder; name = git2; path = External/libgit2/include/git2; sourceTree = ""; }; 88A994B916FCE7D400402C7B /* GTBranchSpec.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = GTBranchSpec.m; sourceTree = ""; }; 88A994C916FCED1D00402C7B /* QuickSpec+GTFixtures.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = "QuickSpec+GTFixtures.h"; sourceTree = ""; }; 88A994CA16FCED1D00402C7B /* QuickSpec+GTFixtures.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = "QuickSpec+GTFixtures.m"; sourceTree = ""; }; + 88B2131A1B20E785005CF2C5 /* GTRepository+References.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = "GTRepository+References.h"; sourceTree = ""; }; + 88B2131B1B20E785005CF2C5 /* GTRepository+References.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = "GTRepository+References.m"; sourceTree = ""; }; 88BC0E4E18EF4F3600C7D0E6 /* GTRepository+Reset.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = "GTRepository+Reset.h"; sourceTree = ""; }; 88BC0E4F18EF4F3600C7D0E6 /* GTRepository+Reset.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = "GTRepository+Reset.m"; sourceTree = ""; }; 88C0BC5817038CF3009E99AA /* GTConfigurationSpec.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = GTConfigurationSpec.m; sourceTree = ""; }; @@ -525,8 +823,6 @@ D09C2E341755F16200065E36 /* GTSubmodule.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = GTSubmodule.h; sourceTree = ""; }; D09C2E351755F16200065E36 /* GTSubmodule.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = GTSubmodule.m; sourceTree = ""; }; D09C2E50175602A500065E36 /* fixtures.zip */ = {isa = PBXFileReference; lastKnownFileType = archive.zip; name = fixtures.zip; path = fixtures/fixtures.zip; sourceTree = ""; }; - D0A0128819F98475007F1914 /* Quick.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; path = Quick.framework; sourceTree = BUILT_PRODUCTS_DIR; }; - D0A0128B19F9853D007F1914 /* Nimble.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; path = Nimble.framework; sourceTree = BUILT_PRODUCTS_DIR; }; D0A0129619F9A660007F1914 /* SwiftSpec.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SwiftSpec.swift; sourceTree = ""; }; D0A463D617E57C45000F5021 /* Common.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = Common.xcconfig; sourceTree = ""; }; D0A463D817E57C45000F5021 /* Debug.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = Debug.xcconfig; sourceTree = ""; }; @@ -541,19 +837,31 @@ D0D81863174421EB00995A2E /* iOS-Application.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = "iOS-Application.xcconfig"; sourceTree = ""; }; D0D81864174421EB00995A2E /* iOS-Base.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = "iOS-Base.xcconfig"; sourceTree = ""; }; D0D81865174421EB00995A2E /* iOS-StaticLibrary.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = "iOS-StaticLibrary.xcconfig"; sourceTree = ""; }; - D0D81867174421EB00995A2E /* Mac-Application.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = "Mac-Application.xcconfig"; sourceTree = ""; }; - D0D81868174421EB00995A2E /* Mac-Base.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = "Mac-Base.xcconfig"; sourceTree = ""; }; - D0D81869174421EB00995A2E /* Mac-DynamicLibrary.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = "Mac-DynamicLibrary.xcconfig"; sourceTree = ""; }; - D0D8186A174421EB00995A2E /* Mac-Framework.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = "Mac-Framework.xcconfig"; sourceTree = ""; }; - D0D8186B174421EB00995A2E /* Mac-StaticLibrary.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = "Mac-StaticLibrary.xcconfig"; sourceTree = ""; }; D0D8186C174421EB00995A2E /* README.md */ = {isa = PBXFileReference; lastKnownFileType = text; path = README.md; sourceTree = ""; }; D0F4E28917C7F24200BBDE30 /* NSErrorGitSpec.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = NSErrorGitSpec.m; sourceTree = ""; }; DD3D9510182A81E1004AF532 /* GTBlame.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = GTBlame.h; sourceTree = ""; }; DD3D9511182A81E1004AF532 /* GTBlame.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = GTBlame.m; sourceTree = ""; }; DD3D951A182AB25C004AF532 /* GTBlameHunk.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = GTBlameHunk.h; sourceTree = ""; }; DD3D951B182AB25C004AF532 /* GTBlameHunk.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = GTBlameHunk.m; sourceTree = ""; }; - E46931A7172740D300F2077D /* update_libgit2 */ = {isa = PBXFileReference; lastKnownFileType = text; name = update_libgit2; path = script/update_libgit2; sourceTree = ""; }; - E46931A8172740D300F2077D /* update_libgit2_ios */ = {isa = PBXFileReference; lastKnownFileType = text; name = update_libgit2_ios; path = script/update_libgit2_ios; sourceTree = ""; }; + F81B6B51207B0A7700AB0836 /* Extension.xcconfig */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.xcconfig; path = Extension.xcconfig; sourceTree = ""; }; + F81B6B53207B0A8B00AB0836 /* iOS-Extension.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = "iOS-Extension.xcconfig"; sourceTree = ""; }; + F879D82F1B4B77F4002D5C07 /* Libgit2FeaturesSpec.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = Libgit2FeaturesSpec.m; sourceTree = ""; }; + F879D8361B4B7F7C002D5C07 /* ObjectiveGit-iOSTests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = "ObjectiveGit-iOSTests.xctest"; sourceTree = BUILT_PRODUCTS_DIR; }; + F8D1BDEC1B31FE7C00CDEC90 /* GTRepository+Pull.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = "GTRepository+Pull.h"; sourceTree = ""; }; + F8D1BDED1B31FE7C00CDEC90 /* GTRepository+Pull.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = "GTRepository+Pull.m"; sourceTree = ""; }; + F8D6384A207A618D00D1FD32 /* script */ = {isa = PBXFileReference; lastKnownFileType = folder; path = script; sourceTree = ""; }; + F8D6385B207AC74A00D1FD32 /* libiconv.tbd */ = {isa = PBXFileReference; lastKnownFileType = "sourcecode.text-based-dylib-definition"; name = libiconv.tbd; path = usr/lib/libiconv.tbd; sourceTree = SDKROOT; }; + F8D6385E207ACAE600D1FD32 /* libz.tbd */ = {isa = PBXFileReference; lastKnownFileType = "sourcecode.text-based-dylib-definition"; name = libz.tbd; path = Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS11.3.sdk/usr/lib/libz.tbd; sourceTree = DEVELOPER_DIR; }; + F8D63860207ACAF600D1FD32 /* libiconv.tbd */ = {isa = PBXFileReference; lastKnownFileType = "sourcecode.text-based-dylib-definition"; name = libiconv.tbd; path = Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS11.3.sdk/usr/lib/libiconv.tbd; sourceTree = DEVELOPER_DIR; }; + F8D63871207AE62A00D1FD32 /* XCTest.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = XCTest.framework; path = Platforms/MacOSX.platform/Developer/Library/Frameworks/XCTest.framework; sourceTree = DEVELOPER_DIR; }; + F8D63872207AE63A00D1FD32 /* XCTest.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = XCTest.framework; path = Platforms/iPhoneOS.platform/Developer/Library/Frameworks/XCTest.framework; sourceTree = DEVELOPER_DIR; }; + F8E4A2901A170CA6006485A8 /* GTRemotePushSpec.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = GTRemotePushSpec.m; sourceTree = ""; }; + F8EFA0361B405020000FF7D0 /* GTRepository+PullSpec.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = "GTRepository+PullSpec.m"; sourceTree = ""; }; + F8EFA0381B4059ED000FF7D0 /* GTUtilityFunctions.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = GTUtilityFunctions.h; sourceTree = ""; }; + F8EFA0391B4059ED000FF7D0 /* GTUtilityFunctions.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = GTUtilityFunctions.m; sourceTree = ""; }; + F964D5EF1CE9D9B200F1D8DD /* GTNote.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = GTNote.h; sourceTree = ""; }; + F964D5F01CE9D9B200F1D8DD /* GTNote.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = GTNote.m; sourceTree = ""; }; + F9D1D4221CEB79D1009E5855 /* GTNoteSpec.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = GTNoteSpec.m; sourceTree = ""; }; /* End PBXFileReference section */ /* Begin PBXFrameworksBuildPhase section */ @@ -561,9 +869,11 @@ isa = PBXFrameworksBuildPhase; buildActionMask = 2147483647; files = ( - D0A0128A19F98475007F1914 /* Quick.framework in Frameworks */, + F81B6B50207B032800AB0836 /* XCTest.framework in Frameworks */, 88F05A9E16011F6E00B7AD1D /* ObjectiveGit.framework in Frameworks */, - D0A0128C19F9853D007F1914 /* Nimble.framework in Frameworks */, + 4DB9711D2645CA3700D14944 /* Quick.framework in Frameworks */, + 4DD769A92645D214007599B8 /* Nimble.framework in Frameworks */, + 4DB9711F2645CA5200D14944 /* ZipArchive.framework in Frameworks */, ); runOnlyForDeploymentPostprocessing = 0; }; @@ -571,9 +881,10 @@ isa = PBXFrameworksBuildPhase; buildActionMask = 2147483647; files = ( - 4D103ADD1819CFAA0029DB24 /* libiconv.dylib in Frameworks */, + F8D6385D207AC75100D1FD32 /* libz.tbd in Frameworks */, + F8D6385C207AC74A00D1FD32 /* libiconv.tbd in Frameworks */, + 4DD7422C25D3F8CB009D9A17 /* libgit2-mac.a in Frameworks */, 8DC2EF570486A6940098B216 /* Cocoa.framework in Frameworks */, - 8803DA871313145700E6E818 /* libz.dylib in Frameworks */, ); runOnlyForDeploymentPostprocessing = 0; }; @@ -581,11 +892,24 @@ isa = PBXFrameworksBuildPhase; buildActionMask = 2147483647; files = ( - 884C8A3919FF4B6D0017E98D /* libiconv.dylib in Frameworks */, - 884C8A3719FF4B4D0017E98D /* libz.dylib in Frameworks */, + F8D63861207ACAF700D1FD32 /* libiconv.tbd in Frameworks */, + F8D6385F207ACAE600D1FD32 /* libz.tbd in Frameworks */, D05FC5E319FAD03C008C9348 /* libssl.a in Frameworks */, D05FC5E219FAD039008C9348 /* libcrypto.a in Frameworks */, - D05FC5E419FAD040008C9348 /* libssh2-ios.a in Frameworks */, + D05FC5E419FAD040008C9348 /* libssh2.a in Frameworks */, + 4D9BCD25206D84B2003CD3CE /* libgit2.a in Frameworks */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + F879D8331B4B7F7C002D5C07 /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + F84277BE207B104A008AB8E8 /* XCTest.framework in Frameworks */, + F879D83C1B4B7F7D002D5C07 /* ObjectiveGit.framework in Frameworks */, + 4DB971202645CA5D00D14944 /* Quick.framework in Frameworks */, + 4DB971212645CA6600D14944 /* Nimble.framework in Frameworks */, + 4DB971222645CA6D00D14944 /* ZipArchive.framework in Frameworks */, ); runOnlyForDeploymentPostprocessing = 0; }; @@ -598,6 +922,7 @@ 8DC2EF5B0486A6940098B216 /* ObjectiveGit.framework */, 88F05A6B16011E5400B7AD1D /* ObjectiveGit-MacTests.xctest */, D01B6ED319F82E2000D411BC /* ObjectiveGit.framework */, + F879D8361B4B7F7C002D5C07 /* ObjectiveGit-iOSTests.xctest */, ); name = Products; sourceTree = ""; @@ -606,6 +931,7 @@ isa = PBXGroup; children = ( BDD8AB01130F01AB00CB5D40 /* README.md */, + 887B948D1A3A38130070D41D /* ObjectiveGit.modulemap */, BDE4C05E130EFE2C00851650 /* ObjectiveGit */, 88F05A7516011E5400B7AD1D /* ObjectiveGitTests */, 32C88DFF0371C24200C91783 /* Other Sources */, @@ -613,7 +939,8 @@ 0867D69AFE84028FC02AAC07 /* External Frameworks and Libraries */, D0D81857174421EB00995A2E /* Configuration */, 034768DFFF38A50411DB9C8B /* Products */, - E46931A6172740D300F2077D /* Scripts */, + F8D6384A207A618D00D1FD32 /* script */, + 4DB9711C2645CA3700D14944 /* Frameworks */, ); name = ObjectiveGitFramework; sourceTree = ""; @@ -622,20 +949,22 @@ 0867D69AFE84028FC02AAC07 /* External Frameworks and Libraries */ = { isa = PBXGroup; children = ( - 4D8DADBE181A7D9F001B1202 /* libgit2 */, + 4DB970902645C8A500D14944 /* Carthage */, 306123A817EA5261006591D4 /* extobjc */, - 4D103ADC1819CFAA0029DB24 /* libiconv.dylib */, - 8803DA861313145700E6E818 /* libz.dylib */, - 884C8A3619FF4B4D0017E98D /* libz.dylib */, - 884C8A3819FF4B6D0017E98D /* libiconv.dylib */, + 889923F919FF5DD40092A9A6 /* git2 */, 6A1F2FD317C6A8F3003DFADE /* libcrypto.a */, + F8D63860207ACAF600D1FD32 /* libiconv.tbd */, + F8D6385B207AC74A00D1FD32 /* libiconv.tbd */, + 23BB67BB1C7DF45300A37A66 /* libz.tbd */, + F8D6385E207ACAE600D1FD32 /* libz.tbd */, 6A1F2FD417C6A8F3003DFADE /* libssl.a */, - 6A502B8617D6892D00BAF4A5 /* libssh2-ios.a */, - 887DAFF615CB1C8000F30D0D /* Security.framework */, + 6A502B8617D6892D00BAF4A5 /* libssh2.a */, + 4D9BCD23206D84AD003CD3CE /* libgit2.a */, + 4DD7422B25D3F8CB009D9A17 /* libgit2-mac.a */, 1058C7B1FEA5585E11CA2CBB /* Cocoa.framework */, - D0A0128819F98475007F1914 /* Quick.framework */, - D0A0128B19F9853D007F1914 /* Nimble.framework */, - 889923F919FF5DD40092A9A6 /* git2 */, + 887DAFF615CB1C8000F30D0D /* Security.framework */, + F8D63871207AE62A00D1FD32 /* XCTest.framework */, + F8D63872207AE63A00D1FD32 /* XCTest.framework */, ); name = "External Frameworks and Libraries"; sourceTree = ""; @@ -644,7 +973,6 @@ isa = PBXGroup; children = ( 8DC2EF5A0486A6940098B216 /* Info.plist */, - 089C1666FE841158C02AAC07 /* InfoPlist.strings */, ); name = Resources; sourceTree = ""; @@ -689,42 +1017,120 @@ name = "Other Sources"; sourceTree = ""; }; + 4DB97073264596AE00D14944 /* macOS */ = { + isa = PBXGroup; + children = ( + 4DB97074264596AE00D14944 /* macOS-Application.xcconfig */, + 4DB97075264596AE00D14944 /* macOS-Framework.xcconfig */, + 4DB97076264596AE00D14944 /* macOS-StaticLibrary.xcconfig */, + 4DB97077264596AE00D14944 /* macOS-Base.xcconfig */, + 4DB97078264596AE00D14944 /* macOS-XCTest.xcconfig */, + 4DB97079264596AE00D14944 /* macOS-DynamicLibrary.xcconfig */, + ); + path = macOS; + sourceTree = ""; + }; + 4DB970902645C8A500D14944 /* Carthage */ = { + isa = PBXGroup; + children = ( + 4DB970912645C8BA00D14944 /* Quick.xcodeproj */, + 4DB970F72645C8F300D14944 /* Nimble.xcodeproj */, + 4DB9710D2645C8F300D14944 /* ZipArchive.xcodeproj */, + ); + name = Carthage; + sourceTree = ""; + }; + 4DB970922645C8BA00D14944 /* Products */ = { + isa = PBXGroup; + children = ( + 4DB970A32645C8BB00D14944 /* Quick.framework */, + 4DB970A52645C8BB00D14944 /* Quick - macOSTests.xctest */, + 4DB970A72645C8BB00D14944 /* QuickIssue853RegressionTests.xctest */, + 4DB970A92645C8BB00D14944 /* QuickFocused - macOSTests.xctest */, + 4DB970AB2645C8BB00D14944 /* QuickAfterSuite - macOSTests.xctest */, + 4DB970AD2645C8BB00D14944 /* Quick.framework */, + 4DB970AF2645C8BB00D14944 /* Quick - iOSTests.xctest */, + 4DB970B12645C8BB00D14944 /* QuickFocused - iOSTests.xctest */, + 4DB970B32645C8BB00D14944 /* QuickAfterSuite - iOSTests.xctest */, + 4DB970B52645C8BB00D14944 /* Quick.framework */, + 4DB970B72645C8BB00D14944 /* Quick - tvOSTests.xctest */, + 4DB970B92645C8BB00D14944 /* QuickFocused - tvOSTests.xctest */, + 4DB970BB2645C8BB00D14944 /* QuickAfterSuite - tvOSTests.xctest */, + ); + name = Products; + sourceTree = ""; + }; + 4DB970F82645C8F300D14944 /* Products */ = { + isa = PBXGroup; + children = ( + 4DB971022645C8F300D14944 /* Nimble.framework */, + 4DB971042645C8F300D14944 /* NimbleTests.xctest */, + 4DB971062645C8F300D14944 /* Nimble.framework */, + 4DB971082645C8F300D14944 /* NimbleTests.xctest */, + 4DB9710A2645C8F300D14944 /* Nimble.framework */, + 4DB9710C2645C8F300D14944 /* NimbleTests.xctest */, + ); + name = Products; + sourceTree = ""; + }; + 4DB9710E2645C8F300D14944 /* Products */ = { + isa = PBXGroup; + children = ( + 4DB971152645C8F300D14944 /* ZipArchive.framework */, + 4DB971172645C8F300D14944 /* ZipArchive.framework */, + 4DB971192645C8F300D14944 /* ZipArchive.framework */, + 4DB9711B2645C8F300D14944 /* ZipArchive.framework */, + ); + name = Products; + sourceTree = ""; + }; + 4DB9711C2645CA3700D14944 /* Frameworks */ = { + isa = PBXGroup; + children = ( + ); + name = Frameworks; + sourceTree = ""; + }; 88F05A7516011E5400B7AD1D /* ObjectiveGitTests */ = { isa = PBXGroup; children = ( - 88F05A7616011E5400B7AD1D /* Supporting Files */, + 200578C418932A82001C06C3 /* GTBlameSpec.m */, 4D1C40D7182C006D00BE2960 /* GTBlobSpec.m */, 88A994B916FCE7D400402C7B /* GTBranchSpec.m */, 88F05AA416011FFD00B7AD1D /* GTCommitSpec.m */, 88C0BC5817038CF3009E99AA /* GTConfigurationSpec.m */, + 8870390A1975E3F2004118D7 /* GTDiffDeltaSpec.m */, 30865A90167F503400B1AB6E /* GTDiffSpec.m */, D06D9E001755D10000558C17 /* GTEnumeratorSpec.m */, + D0751CD818BE520400134314 /* GTFilterListSpec.m */, + 886E623618AECD86000611A0 /* GTFilterSpec.m */, 8832811E173D8816006D7DCF /* GTIndexSpec.m */, + F9D1D4221CEB79D1009E5855 /* GTNoteSpec.m */, + 88948AC81779243600809CDA /* GTObjectDatabaseSpec.m */, 88F05AA816011FFD00B7AD1D /* GTObjectSpec.m */, + D040AF6F177B9779001AD9EB /* GTOIDSpec.m */, D00F6815175D373C004DB9D6 /* GTReferenceSpec.m */, 88215482171499BE00D76B76 /* GTReflogSpec.m */, + F8E4A2901A170CA6006485A8 /* GTRemotePushSpec.m */, 4DBA4A3117DA73CE006CD5F5 /* GTRemoteSpec.m */, - 200578C418932A82001C06C3 /* GTBlameSpec.m */, - D0AC906B172F941F00347DC4 /* GTRepositorySpec.m */, + F8EFA0361B405020000FF7D0 /* GTRepository+PullSpec.m */, + 30A269AC17B4878C000FE64E /* GTRepository+StatusSpec.m */, + 88E353051982EA6B0051001F /* GTRepositoryAttributesSpec.m */, 4D12323F178E009E0048F785 /* GTRepositoryCommittingSpec.m */, + 88234B2518F2FE260039972E /* GTRepositoryResetSpec.m */, + D0AC906B172F941F00347DC4 /* GTRepositorySpec.m */, + D015F7D417F6965400AD5E1F /* GTRepositoryStashingSpec.m */, + D040AF77177B9A9E001AD9EB /* GTSignatureSpec.m */, D03B7C401756AB370034A610 /* GTSubmoduleSpec.m */, 2089E43B17D9A58000F451DA /* GTTagSpec.m */, 30B1E7FF1703871900D0814D /* GTTimeAdditionsSpec.m */, 5BE612921745EEBC00266D8C /* GTTreeBuilderSpec.m */, 88328127173D8A64006D7DCF /* GTTreeSpec.m */, - 88948AC81779243600809CDA /* GTObjectDatabaseSpec.m */, - D040AF6F177B9779001AD9EB /* GTOIDSpec.m */, - D040AF77177B9A9E001AD9EB /* GTSignatureSpec.m */, - 30A269AC17B4878C000FE64E /* GTRepository+StatusSpec.m */, + F879D82F1B4B77F4002D5C07 /* Libgit2FeaturesSpec.m */, 307623AA17C6C8BD00E2CDF1 /* NSArray+StringArraySpec.m */, - D0F4E28917C7F24200BBDE30 /* NSErrorGitSpec.m */, D01EFD9F195DEF2200838D24 /* NSDataGitSpec.m */, - D015F7D417F6965400AD5E1F /* GTRepositoryStashingSpec.m */, - 886E623618AECD86000611A0 /* GTFilterSpec.m */, - D0751CD818BE520400134314 /* GTFilterListSpec.m */, - 88234B2518F2FE260039972E /* GTRepositoryResetSpec.m */, - 8870390A1975E3F2004118D7 /* GTDiffDeltaSpec.m */, - 88E353051982EA6B0051001F /* GTRepositoryAttributesSpec.m */, + D0F4E28917C7F24200BBDE30 /* NSErrorGitSpec.m */, + 88F05A7616011E5400B7AD1D /* Supporting Files */, ); path = ObjectiveGitTests; sourceTree = ""; @@ -732,11 +1138,13 @@ 88F05A7616011E5400B7AD1D /* Supporting Files */ = { isa = PBXGroup; children = ( + D09C2E50175602A500065E36 /* fixtures.zip */, + F8EFA0381B4059ED000FF7D0 /* GTUtilityFunctions.h */, + F8EFA0391B4059ED000FF7D0 /* GTUtilityFunctions.m */, D01B6F0F19F82F3C00D411BC /* Info.plist */, 88A994C916FCED1D00402C7B /* QuickSpec+GTFixtures.h */, 88A994CA16FCED1D00402C7B /* QuickSpec+GTFixtures.m */, D0A0129619F9A660007F1914 /* SwiftSpec.swift */, - D09C2E50175602A500065E36 /* fixtures.zip */, ); name = "Supporting Files"; sourceTree = ""; @@ -760,8 +1168,14 @@ D015F7C917F695E800AD5E1F /* GTRepository+Stashing.m */, 88746CC217FA1C950005888A /* GTRepository+Committing.h */, 88746CC317FA1C950005888A /* GTRepository+Committing.m */, + F8D1BDEC1B31FE7C00CDEC90 /* GTRepository+Pull.h */, + F8D1BDED1B31FE7C00CDEC90 /* GTRepository+Pull.m */, 4DFFB159183AA8D600D1565E /* GTRepository+RemoteOperations.h */, 4DFFB15A183AA8D600D1565E /* GTRepository+RemoteOperations.m */, + 88B2131A1B20E785005CF2C5 /* GTRepository+References.h */, + 88B2131B1B20E785005CF2C5 /* GTRepository+References.m */, + 23F39FAB1C86DB1C00849F3C /* GTRepository+Merging.h */, + 23F39FAC1C86DB1C00849F3C /* GTRepository+Merging.m */, BDD8AE6D13131B8800CB5D40 /* GTEnumerator.h */, BDD8AE6E13131B8800CB5D40 /* GTEnumerator.m */, BD6C22A71314625800992935 /* GTObject.h */, @@ -778,6 +1192,8 @@ BD6B0416131496CC001909D0 /* GTTreeEntry.m */, 5BE612861745EE3300266D8C /* GTTreeBuilder.h */, 5BE612871745EE3300266D8C /* GTTreeBuilder.m */, + F964D5EF1CE9D9B200F1D8DD /* GTNote.h */, + F964D5F01CE9D9B200F1D8DD /* GTNote.m */, BDD62922131C03D600DE34D1 /* GTTag.h */, BDD62923131C03D600DE34D1 /* GTTag.m */, BDFAF9C1131C1845000508BC /* GTIndex.h */, @@ -827,6 +1243,8 @@ 88E352FF1982E9160051001F /* GTRepository+Attributes.m */, 6EEB519F199D62B9001D72C0 /* GTFetchHeadEntry.h */, 6EEB51A0199D62B9001D72C0 /* GTFetchHeadEntry.m */, + 4DC55AE31AD859AD0032563C /* GTCheckoutOptions.h */, + 4DC55AE41AD859AD0032563C /* GTCheckoutOptions.m */, ); path = ObjectiveGit; sourceTree = ""; @@ -873,6 +1291,7 @@ isa = PBXGroup; children = ( D0A463DD17E57C45000F5021 /* Application.xcconfig */, + F81B6B51207B0A7700AB0836 /* Extension.xcconfig */, D019778B19F830CC00F523DA /* Framework.xcconfig */, D0A463DE17E57C45000F5021 /* StaticLibrary.xcconfig */, ); @@ -882,13 +1301,13 @@ D0D81857174421EB00995A2E /* Configuration */ = { isa = PBXGroup; children = ( + 4DB97073264596AE00D14944 /* macOS */, D0A463D517E57C45000F5021 /* Base */, D0D81862174421EB00995A2E /* iOS */, - D0D81866174421EB00995A2E /* Mac OS X */, D0D8186C174421EB00995A2E /* README.md */, ); name = Configuration; - path = External/Configuration; + path = Carthage/Checkouts/xcconfigs; sourceTree = ""; }; D0D81862174421EB00995A2E /* iOS */ = { @@ -896,34 +1315,13 @@ children = ( D0D81863174421EB00995A2E /* iOS-Application.xcconfig */, D0D81864174421EB00995A2E /* iOS-Base.xcconfig */, + F81B6B53207B0A8B00AB0836 /* iOS-Extension.xcconfig */, D019778C19F830D100F523DA /* iOS-Framework.xcconfig */, D0D81865174421EB00995A2E /* iOS-StaticLibrary.xcconfig */, ); path = iOS; sourceTree = ""; }; - D0D81866174421EB00995A2E /* Mac OS X */ = { - isa = PBXGroup; - children = ( - D0D81867174421EB00995A2E /* Mac-Application.xcconfig */, - D0D81868174421EB00995A2E /* Mac-Base.xcconfig */, - D0D81869174421EB00995A2E /* Mac-DynamicLibrary.xcconfig */, - D0D8186A174421EB00995A2E /* Mac-Framework.xcconfig */, - D0D8186B174421EB00995A2E /* Mac-StaticLibrary.xcconfig */, - ); - path = "Mac OS X"; - sourceTree = ""; - }; - E46931A6172740D300F2077D /* Scripts */ = { - isa = PBXGroup; - children = ( - 6A3C60A017D5987600382DFF /* update_libssh2_ios */, - E46931A7172740D300F2077D /* update_libgit2 */, - E46931A8172740D300F2077D /* update_libgit2_ios */, - ); - path = Scripts; - sourceTree = ""; - }; /* End PBXGroup section */ /* Begin PBXHeadersBuildPhase section */ @@ -945,8 +1343,10 @@ BDFAF9C3131C1845000508BC /* GTIndex.h in Headers */, BDFAF9C9131C1868000508BC /* GTIndexEntry.h in Headers */, 6EEB51A1199D62B9001D72C0 /* GTFetchHeadEntry.h in Headers */, + 4DC55AE51AD859AD0032563C /* GTCheckoutOptions.h in Headers */, BD441E08131ED0C300187010 /* GTReference.h in Headers */, 88F6D9D91320451F00CC0BA8 /* ObjectiveGit.h in Headers */, + 88B2131C1B20E785005CF2C5 /* GTRepository+References.h in Headers */, 88F6D9FA1320467100CC0BA8 /* GTCommit.h in Headers */, 88F6D9FB1320467500CC0BA8 /* GTObject.h in Headers */, AA046112134F4D2000DF526B /* GTOdbObject.h in Headers */, @@ -958,6 +1358,7 @@ 79262F8B13C69B1600A4B1EA /* git2.h in Headers */, 88EB7E4D14AEBA600046FEA4 /* GTConfiguration.h in Headers */, BDE4C064130EFE2C00851650 /* NSError+Git.h in Headers */, + 23F39FAD1C86DB1C00849F3C /* GTRepository+Merging.h in Headers */, 55C8057D13875C11004DCB0F /* NSData+Git.h in Headers */, D03B57A118BFFF07007124F4 /* GTDiffPatch.h in Headers */, 883CD6AB1600EBC600F57354 /* GTRemote.h in Headers */, @@ -980,6 +1381,8 @@ 30DCBA5C17B45213009B0EBD /* GTStatusDelta.h in Headers */, 88746CC417FA1C950005888A /* GTRepository+Committing.h in Headers */, D09C2E361755F16200065E36 /* GTSubmodule.h in Headers */, + F8D1BDEE1B31FE7C00CDEC90 /* GTRepository+Pull.h in Headers */, + F964D5F11CE9D9B200F1D8DD /* GTNote.h in Headers */, 4D79C0EE17DF9F4D00997DE4 /* GTCredential.h in Headers */, ); runOnlyForDeploymentPostprocessing = 0; @@ -993,11 +1396,13 @@ D01B6F2319F82F8700D411BC /* GTRepository+Reset.h in Headers */, D01B6F2D19F82F8700D411BC /* GTEnumerator.h in Headers */, D01B6F5519F82FA600D411BC /* GTReflog.h in Headers */, + 23F39FAF1C86DD0A00849F3C /* GTRepository+Merging.h in Headers */, D01B6F3519F82F8700D411BC /* GTBlob.h in Headers */, D01B6F4D19F82F8700D411BC /* GTRemote.h in Headers */, D01B6F1519F82F7B00D411BC /* NSData+Git.h in Headers */, D01B6F6119F82FA600D411BC /* GTFilterSource.h in Headers */, D0E0171519F9AD820019930C /* ObjectiveGit.h in Headers */, + 88B2131D1B20E785005CF2C5 /* GTRepository+References.h in Headers */, D01B6F4919F82F8700D411BC /* GTOdbObject.h in Headers */, D01B6F3919F82F8700D411BC /* GTTreeEntry.h in Headers */, D01B6F5B19F82FA600D411BC /* GTSubmodule.h in Headers */, @@ -1022,6 +1427,7 @@ D01B6F5919F82FA600D411BC /* GTOID.h in Headers */, D01B6F6D19F82FB300D411BC /* GTDiffFile.h in Headers */, D01B6F2F19F82F8700D411BC /* GTObject.h in Headers */, + 4DC55AE61AD859AD0032563C /* GTCheckoutOptions.h in Headers */, D01B6F4B19F82F8700D411BC /* GTConfiguration.h in Headers */, D01B6F6719F82FA600D411BC /* GTFetchHeadEntry.h in Headers */, D01B6F5F19F82FA600D411BC /* GTFilter.h in Headers */, @@ -1036,8 +1442,10 @@ D01B6F7119F82FB300D411BC /* GTDiffDelta.h in Headers */, D01B6F3B19F82F8700D411BC /* GTTreeBuilder.h in Headers */, D01B6F1B19F82F7B00D411BC /* NSDate+GTTimeAdditions.h in Headers */, + F964D5F21CE9D9B200F1D8DD /* GTNote.h in Headers */, D01B6F6319F82FA600D411BC /* GTFilterList.h in Headers */, 889923FB19FF5DD40092A9A6 /* git2 in Headers */, + F8D1BDEF1B31FE7C00CDEC90 /* GTRepository+Pull.h in Headers */, D01B6F1419F82F6000D411BC /* git2.h in Headers */, ); runOnlyForDeploymentPostprocessing = 0; @@ -1056,6 +1464,9 @@ buildRules = ( ); dependencies = ( + 4DD769852645D15D007599B8 /* PBXTargetDependency */, + 4DD769872645D15D007599B8 /* PBXTargetDependency */, + 4DD769892645D15D007599B8 /* PBXTargetDependency */, 88F05AA016011F9000B7AD1D /* PBXTargetDependency */, ); name = "ObjectiveGit-MacTests"; @@ -1071,12 +1482,14 @@ 8DC2EF520486A6940098B216 /* Resources */, 8DC2EF560486A6940098B216 /* Frameworks */, 79262F0F13C697BE00A4B1EA /* Copy git2 Headers */, + BEF7E4DF1A3A47450035BB8E /* Copy git2 Headers again */, 8DC2EF500486A6940098B216 /* Headers */, + 4D751E9D215D765D003CD3CE /* Package external libraries */, ); buildRules = ( ); dependencies = ( - D0A330F816027F4900A616FA /* PBXTargetDependency */, + 3D6123BE1A6432F6008F831A /* PBXTargetDependency */, ); name = "ObjectiveGit-Mac"; productInstallPath = "$(HOME)/Library/Frameworks"; @@ -1102,40 +1515,88 @@ productReference = D01B6ED319F82E2000D411BC /* ObjectiveGit.framework */; productType = "com.apple.product-type.framework"; }; + F879D8351B4B7F7C002D5C07 /* ObjectiveGit-iOSTests */ = { + isa = PBXNativeTarget; + buildConfigurationList = F879D83F1B4B7F7D002D5C07 /* Build configuration list for PBXNativeTarget "ObjectiveGit-iOSTests" */; + buildPhases = ( + F879D8321B4B7F7C002D5C07 /* Sources */, + F879D8331B4B7F7C002D5C07 /* Frameworks */, + F879D8341B4B7F7C002D5C07 /* Resources */, + ); + buildRules = ( + ); + dependencies = ( + 4DD769A42645D16B007599B8 /* PBXTargetDependency */, + 4DD769A62645D16B007599B8 /* PBXTargetDependency */, + 4DD769A82645D16B007599B8 /* PBXTargetDependency */, + F879D83E1B4B7F7D002D5C07 /* PBXTargetDependency */, + ); + name = "ObjectiveGit-iOSTests"; + productName = "ObjectiveGit-iOSTests"; + productReference = F879D8361B4B7F7C002D5C07 /* ObjectiveGit-iOSTests.xctest */; + productType = "com.apple.product-type.bundle.unit-test"; + }; /* End PBXNativeTarget section */ /* Begin PBXProject section */ 0867D690FE84028FC02AAC07 /* Project object */ = { isa = PBXProject; attributes = { + LastSwiftUpdateCheck = 0700; LastTestingUpgradeCheck = 0510; - LastUpgradeCheck = 0510; + LastUpgradeCheck = 0930; ORGANIZATIONNAME = "GitHub, Inc"; TargetAttributes = { + 88F05A6A16011E5400B7AD1D = { + LastSwiftMigration = 0830; + }; + 8DC2EF4F0486A6940098B216 = { + LastSwiftMigration = 0800; + }; D01B6ED219F82E2000D411BC = { CreatedOnToolsVersion = 6.1; + LastSwiftMigration = 0800; + }; + F879D8351B4B7F7C002D5C07 = { + CreatedOnToolsVersion = 6.4; + LastSwiftMigration = 0930; }; }; }; buildConfigurationList = 1DEB91B108733DA50010E9CD /* Build configuration list for PBXProject "ObjectiveGitFramework" */; compatibilityVersion = "Xcode 3.2"; - developmentRegion = English; + developmentRegion = en; hasScannedForEncodings = 1; knownRegions = ( - English, - Japanese, - French, - German, en, + ja, + fr, + de, + Base, ); mainGroup = 0867D691FE84028FC02AAC07 /* ObjectiveGitFramework */; productRefGroup = 034768DFFF38A50411DB9C8B /* Products */; projectDirPath = ""; + projectReferences = ( + { + ProductGroup = 4DB970F82645C8F300D14944 /* Products */; + ProjectRef = 4DB970F72645C8F300D14944 /* Nimble.xcodeproj */; + }, + { + ProductGroup = 4DB970922645C8BA00D14944 /* Products */; + ProjectRef = 4DB970912645C8BA00D14944 /* Quick.xcodeproj */; + }, + { + ProductGroup = 4DB9710E2645C8F300D14944 /* Products */; + ProjectRef = 4DB9710D2645C8F300D14944 /* ZipArchive.xcodeproj */; + }, + ); projectRoot = ""; targets = ( 8DC2EF4F0486A6940098B216 /* ObjectiveGit-Mac */, 88F05A6A16011E5400B7AD1D /* ObjectiveGit-MacTests */, D01B6ED219F82E2000D411BC /* ObjectiveGit-iOS */, + F879D8351B4B7F7C002D5C07 /* ObjectiveGit-iOSTests */, D0A330ED16027F1E00A616FA /* libgit2 */, D0A330F216027F3600A616FA /* libgit2-iOS */, 6A28265217C69CB400C6A948 /* OpenSSL-iOS */, @@ -1144,6 +1605,170 @@ }; /* End PBXProject section */ +/* Begin PBXReferenceProxy section */ + 4DB970A32645C8BB00D14944 /* Quick.framework */ = { + isa = PBXReferenceProxy; + fileType = wrapper.framework; + path = Quick.framework; + remoteRef = 4DB970A22645C8BB00D14944 /* PBXContainerItemProxy */; + sourceTree = BUILT_PRODUCTS_DIR; + }; + 4DB970A52645C8BB00D14944 /* Quick - macOSTests.xctest */ = { + isa = PBXReferenceProxy; + fileType = wrapper.cfbundle; + path = "Quick - macOSTests.xctest"; + remoteRef = 4DB970A42645C8BB00D14944 /* PBXContainerItemProxy */; + sourceTree = BUILT_PRODUCTS_DIR; + }; + 4DB970A72645C8BB00D14944 /* QuickIssue853RegressionTests.xctest */ = { + isa = PBXReferenceProxy; + fileType = wrapper.cfbundle; + path = QuickIssue853RegressionTests.xctest; + remoteRef = 4DB970A62645C8BB00D14944 /* PBXContainerItemProxy */; + sourceTree = BUILT_PRODUCTS_DIR; + }; + 4DB970A92645C8BB00D14944 /* QuickFocused - macOSTests.xctest */ = { + isa = PBXReferenceProxy; + fileType = wrapper.cfbundle; + path = "QuickFocused - macOSTests.xctest"; + remoteRef = 4DB970A82645C8BB00D14944 /* PBXContainerItemProxy */; + sourceTree = BUILT_PRODUCTS_DIR; + }; + 4DB970AB2645C8BB00D14944 /* QuickAfterSuite - macOSTests.xctest */ = { + isa = PBXReferenceProxy; + fileType = wrapper.cfbundle; + path = "QuickAfterSuite - macOSTests.xctest"; + remoteRef = 4DB970AA2645C8BB00D14944 /* PBXContainerItemProxy */; + sourceTree = BUILT_PRODUCTS_DIR; + }; + 4DB970AD2645C8BB00D14944 /* Quick.framework */ = { + isa = PBXReferenceProxy; + fileType = wrapper.framework; + path = Quick.framework; + remoteRef = 4DB970AC2645C8BB00D14944 /* PBXContainerItemProxy */; + sourceTree = BUILT_PRODUCTS_DIR; + }; + 4DB970AF2645C8BB00D14944 /* Quick - iOSTests.xctest */ = { + isa = PBXReferenceProxy; + fileType = wrapper.cfbundle; + path = "Quick - iOSTests.xctest"; + remoteRef = 4DB970AE2645C8BB00D14944 /* PBXContainerItemProxy */; + sourceTree = BUILT_PRODUCTS_DIR; + }; + 4DB970B12645C8BB00D14944 /* QuickFocused - iOSTests.xctest */ = { + isa = PBXReferenceProxy; + fileType = wrapper.cfbundle; + path = "QuickFocused - iOSTests.xctest"; + remoteRef = 4DB970B02645C8BB00D14944 /* PBXContainerItemProxy */; + sourceTree = BUILT_PRODUCTS_DIR; + }; + 4DB970B32645C8BB00D14944 /* QuickAfterSuite - iOSTests.xctest */ = { + isa = PBXReferenceProxy; + fileType = wrapper.cfbundle; + path = "QuickAfterSuite - iOSTests.xctest"; + remoteRef = 4DB970B22645C8BB00D14944 /* PBXContainerItemProxy */; + sourceTree = BUILT_PRODUCTS_DIR; + }; + 4DB970B52645C8BB00D14944 /* Quick.framework */ = { + isa = PBXReferenceProxy; + fileType = wrapper.framework; + path = Quick.framework; + remoteRef = 4DB970B42645C8BB00D14944 /* PBXContainerItemProxy */; + sourceTree = BUILT_PRODUCTS_DIR; + }; + 4DB970B72645C8BB00D14944 /* Quick - tvOSTests.xctest */ = { + isa = PBXReferenceProxy; + fileType = wrapper.cfbundle; + path = "Quick - tvOSTests.xctest"; + remoteRef = 4DB970B62645C8BB00D14944 /* PBXContainerItemProxy */; + sourceTree = BUILT_PRODUCTS_DIR; + }; + 4DB970B92645C8BB00D14944 /* QuickFocused - tvOSTests.xctest */ = { + isa = PBXReferenceProxy; + fileType = wrapper.cfbundle; + path = "QuickFocused - tvOSTests.xctest"; + remoteRef = 4DB970B82645C8BB00D14944 /* PBXContainerItemProxy */; + sourceTree = BUILT_PRODUCTS_DIR; + }; + 4DB970BB2645C8BB00D14944 /* QuickAfterSuite - tvOSTests.xctest */ = { + isa = PBXReferenceProxy; + fileType = wrapper.cfbundle; + path = "QuickAfterSuite - tvOSTests.xctest"; + remoteRef = 4DB970BA2645C8BB00D14944 /* PBXContainerItemProxy */; + sourceTree = BUILT_PRODUCTS_DIR; + }; + 4DB971022645C8F300D14944 /* Nimble.framework */ = { + isa = PBXReferenceProxy; + fileType = wrapper.framework; + path = Nimble.framework; + remoteRef = 4DB971012645C8F300D14944 /* PBXContainerItemProxy */; + sourceTree = BUILT_PRODUCTS_DIR; + }; + 4DB971042645C8F300D14944 /* NimbleTests.xctest */ = { + isa = PBXReferenceProxy; + fileType = wrapper.cfbundle; + path = NimbleTests.xctest; + remoteRef = 4DB971032645C8F300D14944 /* PBXContainerItemProxy */; + sourceTree = BUILT_PRODUCTS_DIR; + }; + 4DB971062645C8F300D14944 /* Nimble.framework */ = { + isa = PBXReferenceProxy; + fileType = wrapper.framework; + path = Nimble.framework; + remoteRef = 4DB971052645C8F300D14944 /* PBXContainerItemProxy */; + sourceTree = BUILT_PRODUCTS_DIR; + }; + 4DB971082645C8F300D14944 /* NimbleTests.xctest */ = { + isa = PBXReferenceProxy; + fileType = wrapper.cfbundle; + path = NimbleTests.xctest; + remoteRef = 4DB971072645C8F300D14944 /* PBXContainerItemProxy */; + sourceTree = BUILT_PRODUCTS_DIR; + }; + 4DB9710A2645C8F300D14944 /* Nimble.framework */ = { + isa = PBXReferenceProxy; + fileType = wrapper.framework; + path = Nimble.framework; + remoteRef = 4DB971092645C8F300D14944 /* PBXContainerItemProxy */; + sourceTree = BUILT_PRODUCTS_DIR; + }; + 4DB9710C2645C8F300D14944 /* NimbleTests.xctest */ = { + isa = PBXReferenceProxy; + fileType = wrapper.cfbundle; + path = NimbleTests.xctest; + remoteRef = 4DB9710B2645C8F300D14944 /* PBXContainerItemProxy */; + sourceTree = BUILT_PRODUCTS_DIR; + }; + 4DB971152645C8F300D14944 /* ZipArchive.framework */ = { + isa = PBXReferenceProxy; + fileType = wrapper.framework; + path = ZipArchive.framework; + remoteRef = 4DB971142645C8F300D14944 /* PBXContainerItemProxy */; + sourceTree = BUILT_PRODUCTS_DIR; + }; + 4DB971172645C8F300D14944 /* ZipArchive.framework */ = { + isa = PBXReferenceProxy; + fileType = wrapper.framework; + path = ZipArchive.framework; + remoteRef = 4DB971162645C8F300D14944 /* PBXContainerItemProxy */; + sourceTree = BUILT_PRODUCTS_DIR; + }; + 4DB971192645C8F300D14944 /* ZipArchive.framework */ = { + isa = PBXReferenceProxy; + fileType = wrapper.framework; + path = ZipArchive.framework; + remoteRef = 4DB971182645C8F300D14944 /* PBXContainerItemProxy */; + sourceTree = BUILT_PRODUCTS_DIR; + }; + 4DB9711B2645C8F300D14944 /* ZipArchive.framework */ = { + isa = PBXReferenceProxy; + fileType = wrapper.framework; + path = ZipArchive.framework; + remoteRef = 4DB9711A2645C8F300D14944 /* PBXContainerItemProxy */; + sourceTree = BUILT_PRODUCTS_DIR; + }; +/* End PBXReferenceProxy section */ + /* Begin PBXResourcesBuildPhase section */ 88F05A6816011E5400B7AD1D /* Resources */ = { isa = PBXResourcesBuildPhase; @@ -1157,59 +1782,84 @@ isa = PBXResourcesBuildPhase; buildActionMask = 2147483647; files = ( - 8DC2EF530486A6940098B216 /* InfoPlist.strings in Resources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + F879D8341B4B7F7C002D5C07 /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + F8D007A81B4FA045009A8DAF /* fixtures.zip in Resources */, ); runOnlyForDeploymentPostprocessing = 0; }; /* End PBXResourcesBuildPhase section */ /* Begin PBXShellScriptBuildPhase section */ - 6A28265317C69CB400C6A948 /* ShellScript */ = { + 4D751E9D215D765D003CD3CE /* Package external libraries */ = { + isa = PBXShellScriptBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + inputPaths = ( + ); + name = "Package external libraries"; + outputPaths = ( + ); + runOnlyForDeploymentPostprocessing = 0; + shellPath = /bin/sh; + shellScript = "./script/repackage-dylibs.rb"; + }; + 6A28265317C69CB400C6A948 /* OpenSSL-iOS */ = { isa = PBXShellScriptBuildPhase; buildActionMask = 2147483647; files = ( ); inputPaths = ( ); + name = "OpenSSL-iOS"; outputPaths = ( ); runOnlyForDeploymentPostprocessing = 0; shellPath = /bin/sh; shellScript = script/update_libssl_ios; }; - 6A3C609117D5963700382DFF /* ShellScript */ = { + 6A3C609117D5963700382DFF /* libssh2-iOS */ = { isa = PBXShellScriptBuildPhase; buildActionMask = 2147483647; files = ( ); inputPaths = ( ); + name = "libssh2-iOS"; outputPaths = ( ); runOnlyForDeploymentPostprocessing = 0; shellPath = /bin/sh; shellScript = script/update_libssh2_ios; }; - D0A330F116027F2300A616FA /* ShellScript */ = { + D0A330F116027F2300A616FA /* libgit2 */ = { isa = PBXShellScriptBuildPhase; buildActionMask = 2147483647; files = ( ); inputPaths = ( ); + name = libgit2; outputPaths = ( ); runOnlyForDeploymentPostprocessing = 0; shellPath = /bin/sh; shellScript = script/update_libgit2; }; - D0A330F616027F3B00A616FA /* ShellScript */ = { + D0A330F616027F3B00A616FA /* libgit2-iOS */ = { isa = PBXShellScriptBuildPhase; buildActionMask = 2147483647; files = ( ); inputPaths = ( ); + name = "libgit2-iOS"; outputPaths = ( ); runOnlyForDeploymentPostprocessing = 0; @@ -1223,6 +1873,8 @@ isa = PBXSourcesBuildPhase; buildActionMask = 2147483647; files = ( + F9D1D4251CEB7BA6009E5855 /* GTNoteSpec.m in Sources */, + 23BB67C11C7DF60300A37A66 /* GTRepository+PullSpec.m in Sources */, D0751CD918BE520400134314 /* GTFilterListSpec.m in Sources */, 200578C518932A82001C06C3 /* GTBlameSpec.m in Sources */, 4D1C40D8182C006D00BE2960 /* GTBlobSpec.m in Sources */, @@ -1234,6 +1886,7 @@ 2089E43C17D9A58000F451DA /* GTTagSpec.m in Sources */, D015F7D517F6965400AD5E1F /* GTRepositoryStashingSpec.m in Sources */, 88A994CB16FCED1D00402C7B /* QuickSpec+GTFixtures.m in Sources */, + F8EFA03A1B4059ED000FF7D0 /* GTUtilityFunctions.m in Sources */, 30B1E8001703871900D0814D /* GTTimeAdditionsSpec.m in Sources */, 8870390B1975E3F2004118D7 /* GTDiffDeltaSpec.m in Sources */, 88C0BC5917038CF3009E99AA /* GTConfigurationSpec.m in Sources */, @@ -1246,10 +1899,12 @@ 307623AB17C6C8BD00E2CDF1 /* NSArray+StringArraySpec.m in Sources */, 8832811F173D8816006D7DCF /* GTIndexSpec.m in Sources */, D0F4E28A17C7F24200BBDE30 /* NSErrorGitSpec.m in Sources */, + F879D8311B4B788F002D5C07 /* Libgit2FeaturesSpec.m in Sources */, 88328128173D8A64006D7DCF /* GTTreeSpec.m in Sources */, 88E353061982EA6B0051001F /* GTRepositoryAttributesSpec.m in Sources */, 88234B2618F2FE260039972E /* GTRepositoryResetSpec.m in Sources */, 5BE612931745EEBC00266D8C /* GTTreeBuilderSpec.m in Sources */, + F8E4A2911A170CA6006485A8 /* GTRemotePushSpec.m in Sources */, D06D9E011755D10000558C17 /* GTEnumeratorSpec.m in Sources */, D03B7C411756AB370034A610 /* GTSubmoduleSpec.m in Sources */, D00F6816175D373C004DB9D6 /* GTReferenceSpec.m in Sources */, @@ -1270,13 +1925,16 @@ BDD8AE7013131B8800CB5D40 /* GTEnumerator.m in Sources */, BD6C235313146E6600992935 /* GTCommit.m in Sources */, 30DCBA5E17B45213009B0EBD /* GTStatusDelta.m in Sources */, + 23F39FAE1C86DB1C00849F3C /* GTRepository+Merging.m in Sources */, 30DCBA6517B45A78009B0EBD /* GTRepository+Status.m in Sources */, BD6C235413146E6A00992935 /* GTObject.m in Sources */, + 4DC55AE71AD859AD0032563C /* GTCheckoutOptions.m in Sources */, BD6C254613148DD300992935 /* GTSignature.m in Sources */, BD6B0412131496B8001909D0 /* GTTree.m in Sources */, BD6B0418131496CC001909D0 /* GTTreeEntry.m in Sources */, DD3D951D182AB25C004AF532 /* GTBlameHunk.m in Sources */, 306123AE17EA5261006591D4 /* EXTScope.m in Sources */, + F8D1BDF01B31FE7C00CDEC90 /* GTRepository+Pull.m in Sources */, BDD6279A1318391200DE34D1 /* GTBlob.m in Sources */, BDD62925131C03D600DE34D1 /* GTTag.m in Sources */, BDFAF9C4131C1845000508BC /* GTIndex.m in Sources */, @@ -1299,12 +1957,14 @@ 3011D8731668E78500CE3409 /* GTDiffHunk.m in Sources */, 3011D8791668F29600CE3409 /* GTDiffDelta.m in Sources */, 6EEB51A2199D62B9001D72C0 /* GTFetchHeadEntry.m in Sources */, + 88B2131E1B20E785005CF2C5 /* GTRepository+References.m in Sources */, 30FDC08116835A8100654BF0 /* GTDiffLine.m in Sources */, 886E622C18AEBF75000611A0 /* GTFilterSource.m in Sources */, DD3D9513182A81E1004AF532 /* GTBlame.m in Sources */, 88746CC617FA1C950005888A /* GTRepository+Committing.m in Sources */, D015F7CC17F695E800AD5E1F /* GTRepository+Stashing.m in Sources */, 30B1E7F01703522100D0814D /* NSDate+GTTimeAdditions.m in Sources */, + F964D5F31CE9D9B200F1D8DD /* GTNote.m in Sources */, 8821546B1714740500D76B76 /* GTReflog.m in Sources */, 8821547817147A5200D76B76 /* GTReflogEntry.m in Sources */, 8821547F17147B3600D76B76 /* GTOID.m in Sources */, @@ -1327,13 +1987,16 @@ D01B6F2E19F82F8700D411BC /* GTEnumerator.m in Sources */, D01B6F4C19F82F8700D411BC /* GTConfiguration.m in Sources */, D01B6F6619F82FA600D411BC /* GTRepository+Attributes.m in Sources */, + 23F39FB01C86E01800849F3C /* GTRepository+Merging.m in Sources */, D019778A19F8307600F523DA /* ObjectiveGit.m in Sources */, D01B6F3219F82F8700D411BC /* GTCommit.m in Sources */, + 4DC55AE81AD859AD0032563C /* GTCheckoutOptions.m in Sources */, D01B6F3819F82F8700D411BC /* GTTree.m in Sources */, D01B6F6C19F82FB300D411BC /* GTDiff.m in Sources */, 884C8A3A19FF4B890017E98D /* EXTScope.m in Sources */, D01B6F4E19F82F8700D411BC /* GTRemote.m in Sources */, D01B6F3019F82F8700D411BC /* GTObject.m in Sources */, + F8D1BDF11B31FE7C00CDEC90 /* GTRepository+Pull.m in Sources */, D01B6F4619F82F8700D411BC /* GTBranch.m in Sources */, D01B6F3A19F82F8700D411BC /* GTTreeEntry.m in Sources */, D01B6F2419F82F8700D411BC /* GTRepository+Reset.m in Sources */, @@ -1356,12 +2019,14 @@ D01B6F1A19F82F7B00D411BC /* NSString+Git.m in Sources */, D01B6F2619F82F8700D411BC /* GTStatusDelta.m in Sources */, D01B6F2019F82F8700D411BC /* GTRepository.m in Sources */, + 88B2131F1B20E785005CF2C5 /* GTRepository+References.m in Sources */, D01B6F7019F82FB300D411BC /* GTDiffHunk.m in Sources */, D01B6F4819F82F8700D411BC /* GTObjectDatabase.m in Sources */, D01B6F2C19F82F8700D411BC /* GTRepository+RemoteOperations.m in Sources */, D01B6F5419F82FA600D411BC /* GTBlameHunk.m in Sources */, D01B6F6819F82FA600D411BC /* GTFetchHeadEntry.m in Sources */, D01B6F3619F82F8700D411BC /* GTBlob.m in Sources */, + F964D5F51CE9D9B200F1D8DD /* GTNote.m in Sources */, D01B6F6E19F82FB300D411BC /* GTDiffFile.m in Sources */, D01B6F5619F82FA600D411BC /* GTReflog.m in Sources */, D01B6F5E19F82FA600D411BC /* GTCredential.m in Sources */, @@ -1374,13 +2039,88 @@ ); runOnlyForDeploymentPostprocessing = 0; }; + F879D8321B4B7F7C002D5C07 /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + F8D007931B4FA03B009A8DAF /* GTObjectSpec.m in Sources */, + F8D0078D1B4FA03B009A8DAF /* GTBranchSpec.m in Sources */, + F8D007761B4F7D10009A8DAF /* GTTimeAdditionsSpec.m in Sources */, + F8D007921B4FA03B009A8DAF /* GTIndexSpec.m in Sources */, + F8D007711B4F7CB0009A8DAF /* NSDataGitSpec.m in Sources */, + 23BB67C21C7DF60400A37A66 /* GTRepository+PullSpec.m in Sources */, + F8D007A11B4FA03B009A8DAF /* GTRepositoryStashingSpec.m in Sources */, + F8D007A31B4FA03B009A8DAF /* GTFilterListSpec.m in Sources */, + F8D0079D1B4FA03B009A8DAF /* GTTreeBuilderSpec.m in Sources */, + F8D007721B4F7CB6009A8DAF /* NSArray+StringArraySpec.m in Sources */, + F8D007731B4F7CC3009A8DAF /* GTSignatureSpec.m in Sources */, + F8D007A21B4FA03B009A8DAF /* GTFilterSpec.m in Sources */, + F81B6B59207B0D3B00AB0836 /* SwiftSpec.swift in Sources */, + F8D007971B4FA03B009A8DAF /* GTRemoteSpec.m in Sources */, + F8D007A61B4FA03B009A8DAF /* GTRepositoryAttributesSpec.m in Sources */, + F8D007941B4FA03B009A8DAF /* GTReferenceSpec.m in Sources */, + F8D007981B4FA03B009A8DAF /* GTBlameSpec.m in Sources */, + F8D007911B4FA03B009A8DAF /* GTEnumeratorSpec.m in Sources */, + F8D007701B4F7CA8009A8DAF /* NSErrorGitSpec.m in Sources */, + F8D007A41B4FA03B009A8DAF /* GTRepositoryResetSpec.m in Sources */, + F8D007951B4FA03B009A8DAF /* GTReflogSpec.m in Sources */, + F8D0079C1B4FA03B009A8DAF /* GTTagSpec.m in Sources */, + F8D007741B4F7CCC009A8DAF /* GTOIDSpec.m in Sources */, + F8D007901B4FA03B009A8DAF /* GTDiffSpec.m in Sources */, + F8D007A71B4FA040009A8DAF /* QuickSpec+GTFixtures.m in Sources */, + F8D0079A1B4FA03B009A8DAF /* GTRepositoryCommittingSpec.m in Sources */, + F8D0078E1B4FA03B009A8DAF /* GTCommitSpec.m in Sources */, + F86949AA1BF1B79E00A989D3 /* GTUtilityFunctions.m in Sources */, + F8D0078F1B4FA03B009A8DAF /* GTConfigurationSpec.m in Sources */, + F8D0079B1B4FA03B009A8DAF /* GTSubmoduleSpec.m in Sources */, + F879D8441B4B80C7002D5C07 /* Libgit2FeaturesSpec.m in Sources */, + F8D0078C1B4FA03B009A8DAF /* GTBlobSpec.m in Sources */, + F8D007991B4FA03B009A8DAF /* GTRepositorySpec.m in Sources */, + F8D0079F1B4FA03B009A8DAF /* GTObjectDatabaseSpec.m in Sources */, + F8D0079E1B4FA03B009A8DAF /* GTTreeSpec.m in Sources */, + F8D007A01B4FA03B009A8DAF /* GTRepository+StatusSpec.m in Sources */, + F8D007961B4FA03B009A8DAF /* GTRemotePushSpec.m in Sources */, + F8D007A51B4FA03B009A8DAF /* GTDiffDeltaSpec.m in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; /* End PBXSourcesBuildPhase section */ /* Begin PBXTargetDependency section */ - 6A28265B17C69D6300C6A948 /* PBXTargetDependency */ = { + 3D6123BE1A6432F6008F831A /* PBXTargetDependency */ = { isa = PBXTargetDependency; - target = 6A28265217C69CB400C6A948 /* OpenSSL-iOS */; - targetProxy = 6A28265A17C69D6300C6A948 /* PBXContainerItemProxy */; + target = D0A330ED16027F1E00A616FA /* libgit2 */; + targetProxy = 3D6123BD1A6432F6008F831A /* PBXContainerItemProxy */; + }; + 4DD769852645D15D007599B8 /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + name = "Quick-macOS"; + targetProxy = 4DD769842645D15D007599B8 /* PBXContainerItemProxy */; + }; + 4DD769872645D15D007599B8 /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + name = "Nimble-macOS"; + targetProxy = 4DD769862645D15D007599B8 /* PBXContainerItemProxy */; + }; + 4DD769892645D15D007599B8 /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + name = "ZipArchive-Mac"; + targetProxy = 4DD769882645D15D007599B8 /* PBXContainerItemProxy */; + }; + 4DD769A42645D16B007599B8 /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + name = "Quick-iOS"; + targetProxy = 4DD769A32645D16B007599B8 /* PBXContainerItemProxy */; + }; + 4DD769A62645D16B007599B8 /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + name = "Nimble-iOS"; + targetProxy = 4DD769A52645D16B007599B8 /* PBXContainerItemProxy */; + }; + 4DD769A82645D16B007599B8 /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + name = "ZipArchive-iOS"; + targetProxy = 4DD769A72645D16B007599B8 /* PBXContainerItemProxy */; }; 6A3C609D17D5964E00382DFF /* PBXTargetDependency */ = { isa = PBXTargetDependency; @@ -1399,44 +2139,42 @@ }; D019779719F8335100F523DA /* PBXTargetDependency */ = { isa = PBXTargetDependency; + platformFilter = ios; target = D0A330F216027F3600A616FA /* libgit2-iOS */; targetProxy = D019779619F8335100F523DA /* PBXContainerItemProxy */; }; - D0A330F816027F4900A616FA /* PBXTargetDependency */ = { + F879D83E1B4B7F7D002D5C07 /* PBXTargetDependency */ = { isa = PBXTargetDependency; - target = D0A330ED16027F1E00A616FA /* libgit2 */; - targetProxy = D0A330F716027F4900A616FA /* PBXContainerItemProxy */; + target = D01B6ED219F82E2000D411BC /* ObjectiveGit-iOS */; + targetProxy = F879D83D1B4B7F7D002D5C07 /* PBXContainerItemProxy */; }; /* End PBXTargetDependency section */ -/* Begin PBXVariantGroup section */ - 089C1666FE841158C02AAC07 /* InfoPlist.strings */ = { - isa = PBXVariantGroup; - children = ( - 089C1667FE841158C02AAC07 /* English */, - ); - name = InfoPlist.strings; - sourceTree = ""; - }; -/* End PBXVariantGroup section */ - /* Begin XCBuildConfiguration section */ 1DEB91AE08733DA50010E9CD /* Debug */ = { isa = XCBuildConfiguration; - baseConfigurationReference = D0D8186A174421EB00995A2E /* Mac-Framework.xcconfig */; + baseConfigurationReference = 4DB97075264596AE00D14944 /* macOS-Framework.xcconfig */; buildSettings = { DYLIB_COMPATIBILITY_VERSION = 1; DYLIB_CURRENT_VERSION = 1; FRAMEWORK_VERSION = A; INFOPLIST_FILE = Info.plist; + LIBRARY_SEARCH_PATHS = ( + "$(inherited)", + /usr/local/opt/openssl/lib, + "$(PROJECT_DIR)/External/build/lib", + "$(PROJECT_DIR)/External", + ); + MODULEMAP_FILE = ObjectiveGit.modulemap; OTHER_LDFLAGS = ( - "-lgit2", "-force_load", - External/libgit2.a, + "External/libgit2-mac.a", /usr/local/lib/libssh2.a, "-lcrypto", "-lssl", + "-lcurl", ); + PRODUCT_BUNDLE_IDENTIFIER = "org.libgit2.$(PRODUCT_NAME:rfc1034identifier)"; PRODUCT_NAME = ObjectiveGit; WRAPPER_EXTENSION = framework; }; @@ -1444,20 +2182,28 @@ }; 1DEB91AF08733DA50010E9CD /* Release */ = { isa = XCBuildConfiguration; - baseConfigurationReference = D0D8186A174421EB00995A2E /* Mac-Framework.xcconfig */; + baseConfigurationReference = 4DB97075264596AE00D14944 /* macOS-Framework.xcconfig */; buildSettings = { DYLIB_COMPATIBILITY_VERSION = 1; DYLIB_CURRENT_VERSION = 1; FRAMEWORK_VERSION = A; INFOPLIST_FILE = Info.plist; + LIBRARY_SEARCH_PATHS = ( + "$(inherited)", + /usr/local/opt/openssl/lib, + "$(PROJECT_DIR)/External/build/lib", + "$(PROJECT_DIR)/External", + ); + MODULEMAP_FILE = ObjectiveGit.modulemap; OTHER_LDFLAGS = ( - "-lgit2", "-force_load", - External/libgit2.a, + "External/libgit2-mac.a", /usr/local/lib/libssh2.a, "-lcrypto", "-lssl", + "-lcurl", ); + PRODUCT_BUNDLE_IDENTIFIER = "org.libgit2.$(PRODUCT_NAME:rfc1034identifier)"; PRODUCT_NAME = ObjectiveGit; WRAPPER_EXTENSION = framework; }; @@ -1468,21 +2214,33 @@ baseConfigurationReference = D0A463D817E57C45000F5021 /* Debug.xcconfig */; buildSettings = { CLANG_ALLOW_NON_MODULAR_INCLUDES_IN_FRAMEWORK_MODULES = YES; + CLANG_ANALYZER_LOCALIZABILITY_NONLOCALIZED = YES; + CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; + CLANG_WARN_COMMA = YES; + CLANG_WARN_INFINITE_RECURSION = YES; + CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; + CLANG_WARN_STRICT_PROTOTYPES = YES; + CLANG_WARN_SUSPICIOUS_MOVE = YES; + ENABLE_TESTABILITY = YES; + GCC_NO_COMMON_BLOCKS = YES; + GCC_TREAT_WARNINGS_AS_ERRORS = NO; GCC_WARN_ABOUT_MISSING_FIELD_INITIALIZERS = NO; HEADER_SEARCH_PATHS = ( External/libgit2/include, /usr/local/include, ); - IPHONEOS_DEPLOYMENT_TARGET = 8.0; + IPHONEOS_DEPLOYMENT_TARGET = 9.3; LIBRARY_SEARCH_PATHS = ( ., External, ); - MACOSX_DEPLOYMENT_TARGET = 10.8; + MACOSX_DEPLOYMENT_TARGET = 10.10; + ONLY_ACTIVE_ARCH = YES; OTHER_CFLAGS = ( "$(inherited)", "-DGIT_SSH", ); + SWIFT_VERSION = 5.0; TARGETED_DEVICE_FAMILY = "1,2"; WARNING_CFLAGS = ( "$(inherited)", @@ -1496,21 +2254,31 @@ baseConfigurationReference = D0A463DA17E57C45000F5021 /* Release.xcconfig */; buildSettings = { CLANG_ALLOW_NON_MODULAR_INCLUDES_IN_FRAMEWORK_MODULES = YES; + CLANG_ANALYZER_LOCALIZABILITY_NONLOCALIZED = YES; + CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; + CLANG_WARN_COMMA = YES; + CLANG_WARN_INFINITE_RECURSION = YES; + CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; + CLANG_WARN_STRICT_PROTOTYPES = YES; + CLANG_WARN_SUSPICIOUS_MOVE = YES; + GCC_NO_COMMON_BLOCKS = YES; + GCC_TREAT_WARNINGS_AS_ERRORS = NO; GCC_WARN_ABOUT_MISSING_FIELD_INITIALIZERS = NO; HEADER_SEARCH_PATHS = ( External/libgit2/include, /usr/local/include, ); - IPHONEOS_DEPLOYMENT_TARGET = 8.0; + IPHONEOS_DEPLOYMENT_TARGET = 9.3; LIBRARY_SEARCH_PATHS = ( ., External, ); - MACOSX_DEPLOYMENT_TARGET = 10.8; + MACOSX_DEPLOYMENT_TARGET = 10.10; OTHER_CFLAGS = ( "$(inherited)", "-DGIT_SSH", ); + SWIFT_VERSION = 5.0; TARGETED_DEVICE_FAMILY = "1,2"; WARNING_CFLAGS = ( "$(inherited)", @@ -1569,28 +2337,45 @@ }; 88F05A8016011E5400B7AD1D /* Debug */ = { isa = XCBuildConfiguration; - baseConfigurationReference = D0D81867174421EB00995A2E /* Mac-Application.xcconfig */; + baseConfigurationReference = 4DB97078264596AE00D14944 /* macOS-XCTest.xcconfig */; buildSettings = { + CLANG_WARN_NULLABLE_TO_NONNULL_CONVERSION = NO; FRAMEWORK_SEARCH_PATHS = ( "$(inherited)", "$(DEVELOPER_FRAMEWORKS_DIR)", + "$(PROJECT_DIR)/Carthage/Build/Mac", + ); + GCC_PREPROCESSOR_DEFINITIONS = ( + "DEBUG=1", + "NOUNCRYPT=1", + "NOCRYPT=1", + ); + HEADER_SEARCH_PATHS = ( + External/libgit2/include, + /usr/local/include, ); INFOPLIST_FILE = "ObjectiveGitTests/ObjectiveGitTests-Info.plist"; - MACOSX_DEPLOYMENT_TARGET = 10.9; + PRODUCT_BUNDLE_IDENTIFIER = "org.libgit2.$(PRODUCT_NAME:rfc1034identifier)"; PRODUCT_NAME = "$(TARGET_NAME)"; }; name = Debug; }; 88F05A8116011E5400B7AD1D /* Release */ = { isa = XCBuildConfiguration; - baseConfigurationReference = D0D81867174421EB00995A2E /* Mac-Application.xcconfig */; + baseConfigurationReference = 4DB97078264596AE00D14944 /* macOS-XCTest.xcconfig */; buildSettings = { + CLANG_WARN_NULLABLE_TO_NONNULL_CONVERSION = NO; FRAMEWORK_SEARCH_PATHS = ( "$(inherited)", "$(DEVELOPER_FRAMEWORKS_DIR)", + "$(PROJECT_DIR)/Carthage/Build/Mac", + ); + HEADER_SEARCH_PATHS = ( + External/libgit2/include, + /usr/local/include, ); INFOPLIST_FILE = "ObjectiveGitTests/ObjectiveGitTests-Info.plist"; - MACOSX_DEPLOYMENT_TARGET = 10.9; + PRODUCT_BUNDLE_IDENTIFIER = "org.libgit2.$(PRODUCT_NAME:rfc1034identifier)"; PRODUCT_NAME = "$(TARGET_NAME)"; }; name = Release; @@ -1600,21 +2385,31 @@ baseConfigurationReference = D0A463DB17E57C45000F5021 /* Test.xcconfig */; buildSettings = { CLANG_ALLOW_NON_MODULAR_INCLUDES_IN_FRAMEWORK_MODULES = YES; + CLANG_ANALYZER_LOCALIZABILITY_NONLOCALIZED = YES; + CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; + CLANG_WARN_COMMA = YES; + CLANG_WARN_INFINITE_RECURSION = YES; + CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; + CLANG_WARN_STRICT_PROTOTYPES = YES; + CLANG_WARN_SUSPICIOUS_MOVE = YES; + GCC_NO_COMMON_BLOCKS = YES; + GCC_TREAT_WARNINGS_AS_ERRORS = NO; GCC_WARN_ABOUT_MISSING_FIELD_INITIALIZERS = NO; HEADER_SEARCH_PATHS = ( External/libgit2/include, /usr/local/include, ); - IPHONEOS_DEPLOYMENT_TARGET = 8.0; + IPHONEOS_DEPLOYMENT_TARGET = 9.3; LIBRARY_SEARCH_PATHS = ( ., External, ); - MACOSX_DEPLOYMENT_TARGET = 10.8; + MACOSX_DEPLOYMENT_TARGET = 10.10; OTHER_CFLAGS = ( "$(inherited)", "-DGIT_SSH", ); + SWIFT_VERSION = 5.0; TARGETED_DEVICE_FAMILY = "1,2"; WARNING_CFLAGS = ( "$(inherited)", @@ -1625,20 +2420,28 @@ }; D019778E19F830F500F523DA /* Test */ = { isa = XCBuildConfiguration; - baseConfigurationReference = D0D8186A174421EB00995A2E /* Mac-Framework.xcconfig */; + baseConfigurationReference = 4DB97075264596AE00D14944 /* macOS-Framework.xcconfig */; buildSettings = { DYLIB_COMPATIBILITY_VERSION = 1; DYLIB_CURRENT_VERSION = 1; FRAMEWORK_VERSION = A; INFOPLIST_FILE = Info.plist; + LIBRARY_SEARCH_PATHS = ( + "$(inherited)", + /usr/local/opt/openssl/lib, + "$(PROJECT_DIR)/External/build/lib", + "$(PROJECT_DIR)/External", + ); + MODULEMAP_FILE = ObjectiveGit.modulemap; OTHER_LDFLAGS = ( - "-lgit2", "-force_load", - External/libgit2.a, + "External/libgit2-mac.a", /usr/local/lib/libssh2.a, "-lcrypto", "-lssl", + "-lcurl", ); + PRODUCT_BUNDLE_IDENTIFIER = "org.libgit2.$(PRODUCT_NAME:rfc1034identifier)"; PRODUCT_NAME = ObjectiveGit; WRAPPER_EXTENSION = framework; }; @@ -1646,14 +2449,20 @@ }; D019778F19F830F500F523DA /* Test */ = { isa = XCBuildConfiguration; - baseConfigurationReference = D0D81867174421EB00995A2E /* Mac-Application.xcconfig */; + baseConfigurationReference = 4DB97078264596AE00D14944 /* macOS-XCTest.xcconfig */; buildSettings = { + CLANG_WARN_NULLABLE_TO_NONNULL_CONVERSION = NO; FRAMEWORK_SEARCH_PATHS = ( "$(inherited)", "$(DEVELOPER_FRAMEWORKS_DIR)", + "$(PROJECT_DIR)/Carthage/Build/Mac", + ); + HEADER_SEARCH_PATHS = ( + External/libgit2/include, + /usr/local/include, ); INFOPLIST_FILE = "ObjectiveGitTests/ObjectiveGitTests-Info.plist"; - MACOSX_DEPLOYMENT_TARGET = 10.9; + PRODUCT_BUNDLE_IDENTIFIER = "org.libgit2.$(PRODUCT_NAME:rfc1034identifier)"; PRODUCT_NAME = "$(TARGET_NAME)"; }; name = Test; @@ -1663,26 +2472,21 @@ baseConfigurationReference = D019778C19F830D100F523DA /* iOS-Framework.xcconfig */; buildSettings = { CODE_SIGN_IDENTITY = "iPhone Developer"; - "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = ""; CURRENT_PROJECT_VERSION = 1; DYLIB_COMPATIBILITY_VERSION = 1; DYLIB_CURRENT_VERSION = 1; HEADER_SEARCH_PATHS = ( "$(inherited)", - "External/libssh2-ios/include/libssh2", - External/libgit2/include, + External/build/include, ); INFOPLIST_FILE = Info.plist; - LIBRARY_SEARCH_PATHS = ( - "External/ios-openssl/lib", - "External/libssh2-ios/lib", - "External/libgit2-ios", - ); - OTHER_LDFLAGS = ( - "-lgit2-ios", - "-all_load", - ); + LIBRARY_SEARCH_PATHS = "$(PROJECT_DIR)/External/build/lib"; + MODULEMAP_FILE = ObjectiveGit.modulemap; + OTHER_LDFLAGS = "-all_load"; + PRODUCT_BUNDLE_IDENTIFIER = "org.libgit2.$(PRODUCT_NAME:rfc1034identifier)"; PRODUCT_NAME = ObjectiveGit; + USER_HEADER_SEARCH_PATHS = "$(SRCROOT)/External/libgit2/include"; VERSIONING_SYSTEM = "apple-generic"; VERSION_INFO_PREFIX = ""; }; @@ -1690,7 +2494,7 @@ }; D019779219F830F500F523DA /* Test */ = { isa = XCBuildConfiguration; - baseConfigurationReference = D0D8186B174421EB00995A2E /* Mac-StaticLibrary.xcconfig */; + baseConfigurationReference = 4DB97076264596AE00D14944 /* macOS-StaticLibrary.xcconfig */; buildSettings = { PRODUCT_NAME = "$(TARGET_NAME)"; }; @@ -1725,26 +2529,21 @@ baseConfigurationReference = D019778C19F830D100F523DA /* iOS-Framework.xcconfig */; buildSettings = { CODE_SIGN_IDENTITY = "iPhone Developer"; - "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = ""; CURRENT_PROJECT_VERSION = 1; DYLIB_COMPATIBILITY_VERSION = 1; DYLIB_CURRENT_VERSION = 1; HEADER_SEARCH_PATHS = ( "$(inherited)", - "External/libssh2-ios/include/libssh2", - External/libgit2/include, + External/build/include, ); INFOPLIST_FILE = Info.plist; - LIBRARY_SEARCH_PATHS = ( - "External/ios-openssl/lib", - "External/libssh2-ios/lib", - "External/libgit2-ios", - ); - OTHER_LDFLAGS = ( - "-lgit2-ios", - "-all_load", - ); + LIBRARY_SEARCH_PATHS = "$(PROJECT_DIR)/External/build/lib"; + MODULEMAP_FILE = ObjectiveGit.modulemap; + OTHER_LDFLAGS = "-all_load"; + PRODUCT_BUNDLE_IDENTIFIER = "org.libgit2.$(PRODUCT_NAME:rfc1034identifier)"; PRODUCT_NAME = ObjectiveGit; + USER_HEADER_SEARCH_PATHS = "$(SRCROOT)/External/libgit2/include"; VERSIONING_SYSTEM = "apple-generic"; VERSION_INFO_PREFIX = ""; }; @@ -1755,26 +2554,21 @@ baseConfigurationReference = D019778C19F830D100F523DA /* iOS-Framework.xcconfig */; buildSettings = { CODE_SIGN_IDENTITY = "iPhone Developer"; - "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = ""; CURRENT_PROJECT_VERSION = 1; DYLIB_COMPATIBILITY_VERSION = 1; DYLIB_CURRENT_VERSION = 1; HEADER_SEARCH_PATHS = ( "$(inherited)", - "External/libssh2-ios/include/libssh2", - External/libgit2/include, + External/build/include, ); INFOPLIST_FILE = Info.plist; - LIBRARY_SEARCH_PATHS = ( - "External/ios-openssl/lib", - "External/libssh2-ios/lib", - "External/libgit2-ios", - ); - OTHER_LDFLAGS = ( - "-lgit2-ios", - "-all_load", - ); + LIBRARY_SEARCH_PATHS = "$(PROJECT_DIR)/External/build/lib"; + MODULEMAP_FILE = ObjectiveGit.modulemap; + OTHER_LDFLAGS = "-all_load"; + PRODUCT_BUNDLE_IDENTIFIER = "org.libgit2.$(PRODUCT_NAME:rfc1034identifier)"; PRODUCT_NAME = ObjectiveGit; + USER_HEADER_SEARCH_PATHS = "$(SRCROOT)/External/libgit2/include"; VERSIONING_SYSTEM = "apple-generic"; VERSION_INFO_PREFIX = ""; }; @@ -1785,26 +2579,21 @@ baseConfigurationReference = D019778C19F830D100F523DA /* iOS-Framework.xcconfig */; buildSettings = { CODE_SIGN_IDENTITY = "iPhone Developer"; - "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = ""; CURRENT_PROJECT_VERSION = 1; DYLIB_COMPATIBILITY_VERSION = 1; DYLIB_CURRENT_VERSION = 1; HEADER_SEARCH_PATHS = ( "$(inherited)", - "External/libssh2-ios/include/libssh2", - External/libgit2/include, + External/build/include, ); INFOPLIST_FILE = Info.plist; - LIBRARY_SEARCH_PATHS = ( - "External/ios-openssl/lib", - "External/libssh2-ios/lib", - "External/libgit2-ios", - ); - OTHER_LDFLAGS = ( - "-lgit2-ios", - "-all_load", - ); + LIBRARY_SEARCH_PATHS = "$(PROJECT_DIR)/External/build/lib"; + MODULEMAP_FILE = ObjectiveGit.modulemap; + OTHER_LDFLAGS = "-all_load"; + PRODUCT_BUNDLE_IDENTIFIER = "org.libgit2.$(PRODUCT_NAME:rfc1034identifier)"; PRODUCT_NAME = ObjectiveGit; + USER_HEADER_SEARCH_PATHS = "$(SRCROOT)/External/libgit2/include"; VERSIONING_SYSTEM = "apple-generic"; VERSION_INFO_PREFIX = ""; }; @@ -1815,21 +2604,31 @@ baseConfigurationReference = D0A463D917E57C45000F5021 /* Profile.xcconfig */; buildSettings = { CLANG_ALLOW_NON_MODULAR_INCLUDES_IN_FRAMEWORK_MODULES = YES; + CLANG_ANALYZER_LOCALIZABILITY_NONLOCALIZED = YES; + CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; + CLANG_WARN_COMMA = YES; + CLANG_WARN_INFINITE_RECURSION = YES; + CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; + CLANG_WARN_STRICT_PROTOTYPES = YES; + CLANG_WARN_SUSPICIOUS_MOVE = YES; + GCC_NO_COMMON_BLOCKS = YES; + GCC_TREAT_WARNINGS_AS_ERRORS = NO; GCC_WARN_ABOUT_MISSING_FIELD_INITIALIZERS = NO; HEADER_SEARCH_PATHS = ( External/libgit2/include, /usr/local/include, ); - IPHONEOS_DEPLOYMENT_TARGET = 8.0; + IPHONEOS_DEPLOYMENT_TARGET = 9.3; LIBRARY_SEARCH_PATHS = ( ., External, ); - MACOSX_DEPLOYMENT_TARGET = 10.8; + MACOSX_DEPLOYMENT_TARGET = 10.10; OTHER_CFLAGS = ( "$(inherited)", "-DGIT_SSH", ); + SWIFT_VERSION = 5.0; TARGETED_DEVICE_FAMILY = "1,2"; WARNING_CFLAGS = ( "$(inherited)", @@ -1840,20 +2639,28 @@ }; D03FC3D81602E97F00BCFA73 /* Profile */ = { isa = XCBuildConfiguration; - baseConfigurationReference = D0D8186A174421EB00995A2E /* Mac-Framework.xcconfig */; + baseConfigurationReference = 4DB97075264596AE00D14944 /* macOS-Framework.xcconfig */; buildSettings = { DYLIB_COMPATIBILITY_VERSION = 1; DYLIB_CURRENT_VERSION = 1; FRAMEWORK_VERSION = A; INFOPLIST_FILE = Info.plist; + LIBRARY_SEARCH_PATHS = ( + "$(inherited)", + /usr/local/opt/openssl/lib, + "$(PROJECT_DIR)/External/build/lib", + "$(PROJECT_DIR)/External", + ); + MODULEMAP_FILE = ObjectiveGit.modulemap; OTHER_LDFLAGS = ( - "-lgit2", "-force_load", - External/libgit2.a, + "External/libgit2-mac.a", /usr/local/lib/libssh2.a, "-lcrypto", "-lssl", + "-lcurl", ); + PRODUCT_BUNDLE_IDENTIFIER = "org.libgit2.$(PRODUCT_NAME:rfc1034identifier)"; PRODUCT_NAME = ObjectiveGit; WRAPPER_EXTENSION = framework; }; @@ -1861,21 +2668,27 @@ }; D03FC3DA1602E97F00BCFA73 /* Profile */ = { isa = XCBuildConfiguration; - baseConfigurationReference = D0D81867174421EB00995A2E /* Mac-Application.xcconfig */; + baseConfigurationReference = 4DB97078264596AE00D14944 /* macOS-XCTest.xcconfig */; buildSettings = { + CLANG_WARN_NULLABLE_TO_NONNULL_CONVERSION = NO; FRAMEWORK_SEARCH_PATHS = ( "$(inherited)", "$(DEVELOPER_FRAMEWORKS_DIR)", + "$(PROJECT_DIR)/Carthage/Build/Mac", + ); + HEADER_SEARCH_PATHS = ( + External/libgit2/include, + /usr/local/include, ); INFOPLIST_FILE = "ObjectiveGitTests/ObjectiveGitTests-Info.plist"; - MACOSX_DEPLOYMENT_TARGET = 10.9; + PRODUCT_BUNDLE_IDENTIFIER = "org.libgit2.$(PRODUCT_NAME:rfc1034identifier)"; PRODUCT_NAME = "$(TARGET_NAME)"; }; name = Profile; }; D03FC3DB1602E97F00BCFA73 /* Profile */ = { isa = XCBuildConfiguration; - baseConfigurationReference = D0D8186B174421EB00995A2E /* Mac-StaticLibrary.xcconfig */; + baseConfigurationReference = 4DB97076264596AE00D14944 /* macOS-StaticLibrary.xcconfig */; buildSettings = { PRODUCT_NAME = "$(TARGET_NAME)"; }; @@ -1891,7 +2704,7 @@ }; D0A330EF16027F1E00A616FA /* Debug */ = { isa = XCBuildConfiguration; - baseConfigurationReference = D0D8186B174421EB00995A2E /* Mac-StaticLibrary.xcconfig */; + baseConfigurationReference = 4DB97076264596AE00D14944 /* macOS-StaticLibrary.xcconfig */; buildSettings = { PRODUCT_NAME = "$(TARGET_NAME)"; }; @@ -1899,7 +2712,7 @@ }; D0A330F016027F1E00A616FA /* Release */ = { isa = XCBuildConfiguration; - baseConfigurationReference = D0D8186B174421EB00995A2E /* Mac-StaticLibrary.xcconfig */; + baseConfigurationReference = 4DB97076264596AE00D14944 /* macOS-StaticLibrary.xcconfig */; buildSettings = { PRODUCT_NAME = "$(TARGET_NAME)"; }; @@ -1921,6 +2734,227 @@ }; name = Release; }; + F879D8401B4B7F7D002D5C07 /* Debug */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = D0A463DB17E57C45000F5021 /* Test.xcconfig */; + buildSettings = { + CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x"; + CLANG_CXX_LIBRARY = "libc++"; + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_NULLABLE_TO_NONNULL_CONVERSION = NO; + CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_UNREACHABLE_CODE = YES; + CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; + COPY_PHASE_STRIP = NO; + DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; + ENABLE_STRICT_OBJC_MSGSEND = YES; + FRAMEWORK_SEARCH_PATHS = ( + "$(inherited)", + "$(PROJECT_DIR)/Carthage/Build/iOS", + ); + GCC_C_LANGUAGE_STANDARD = gnu99; + GCC_DYNAMIC_NO_PIC = NO; + GCC_OPTIMIZATION_LEVEL = 0; + GCC_PREPROCESSOR_DEFINITIONS = ( + "$(inherited)", + "NOCRYPT=1", + "NOUNCRYPT=1", + "NS_ENFORCE_NSOBJECT_DESIGNATED_INITIALIZER=0", + ); + GCC_SYMBOLS_PRIVATE_EXTERN = NO; + GCC_TREAT_WARNINGS_AS_ERRORS = NO; + GCC_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_ABOUT_DEPRECATED_FUNCTIONS = NO; + GCC_WARN_ABOUT_MISSING_FIELD_INITIALIZERS = NO; + GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; + GCC_WARN_UNDECLARED_SELECTOR = YES; + GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; + GCC_WARN_UNUSED_FUNCTION = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + HEADER_SEARCH_PATHS = "$(inherited)"; + INFOPLIST_FILE = "ObjectiveGitTests/ObjectiveGitTests-Info.plist"; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + "@loader_path/Frameworks", + ); + LIBRARY_SEARCH_PATHS = ( + ., + External, + ); + MTL_ENABLE_DEBUG_INFO = YES; + PRODUCT_BUNDLE_IDENTIFIER = "org.libgit2.$(PRODUCT_NAME:rfc1034identifier)"; + PRODUCT_NAME = "$(TARGET_NAME)"; + SDKROOT = iphoneos; + }; + name = Debug; + }; + F879D8411B4B7F7D002D5C07 /* Test */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = D0A463DB17E57C45000F5021 /* Test.xcconfig */; + buildSettings = { + CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x"; + CLANG_CXX_LIBRARY = "libc++"; + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_NULLABLE_TO_NONNULL_CONVERSION = NO; + CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_UNREACHABLE_CODE = YES; + CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; + COPY_PHASE_STRIP = NO; + DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; + ENABLE_NS_ASSERTIONS = NO; + ENABLE_STRICT_OBJC_MSGSEND = YES; + FRAMEWORK_SEARCH_PATHS = ( + "$(inherited)", + "$(PROJECT_DIR)/Carthage/Build/iOS", + ); + GCC_C_LANGUAGE_STANDARD = gnu99; + GCC_TREAT_WARNINGS_AS_ERRORS = NO; + GCC_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_ABOUT_DEPRECATED_FUNCTIONS = NO; + GCC_WARN_ABOUT_MISSING_FIELD_INITIALIZERS = NO; + GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; + GCC_WARN_UNDECLARED_SELECTOR = YES; + GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; + GCC_WARN_UNUSED_FUNCTION = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + HEADER_SEARCH_PATHS = "$(inherited)"; + INFOPLIST_FILE = "ObjectiveGitTests/ObjectiveGitTests-Info.plist"; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + "@loader_path/Frameworks", + ); + LIBRARY_SEARCH_PATHS = ( + ., + External, + ); + MTL_ENABLE_DEBUG_INFO = NO; + PRODUCT_BUNDLE_IDENTIFIER = "org.libgit2.$(PRODUCT_NAME:rfc1034identifier)"; + PRODUCT_NAME = "$(TARGET_NAME)"; + SDKROOT = iphoneos; + VALIDATE_PRODUCT = YES; + }; + name = Test; + }; + F879D8421B4B7F7D002D5C07 /* Release */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = D0A463DB17E57C45000F5021 /* Test.xcconfig */; + buildSettings = { + CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x"; + CLANG_CXX_LIBRARY = "libc++"; + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_NULLABLE_TO_NONNULL_CONVERSION = NO; + CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_UNREACHABLE_CODE = YES; + CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; + COPY_PHASE_STRIP = NO; + DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; + ENABLE_NS_ASSERTIONS = NO; + ENABLE_STRICT_OBJC_MSGSEND = YES; + FRAMEWORK_SEARCH_PATHS = ( + "$(inherited)", + "$(PROJECT_DIR)/Carthage/Build/iOS", + ); + GCC_C_LANGUAGE_STANDARD = gnu99; + GCC_TREAT_WARNINGS_AS_ERRORS = NO; + GCC_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_ABOUT_DEPRECATED_FUNCTIONS = NO; + GCC_WARN_ABOUT_MISSING_FIELD_INITIALIZERS = NO; + GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; + GCC_WARN_UNDECLARED_SELECTOR = YES; + GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; + GCC_WARN_UNUSED_FUNCTION = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + HEADER_SEARCH_PATHS = "$(inherited)"; + INFOPLIST_FILE = "ObjectiveGitTests/ObjectiveGitTests-Info.plist"; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + "@loader_path/Frameworks", + ); + LIBRARY_SEARCH_PATHS = ( + ., + External, + ); + MTL_ENABLE_DEBUG_INFO = NO; + PRODUCT_BUNDLE_IDENTIFIER = "org.libgit2.$(PRODUCT_NAME:rfc1034identifier)"; + PRODUCT_NAME = "$(TARGET_NAME)"; + SDKROOT = iphoneos; + SWIFT_COMPILATION_MODE = wholemodule; + SWIFT_OPTIMIZATION_LEVEL = "-O"; + VALIDATE_PRODUCT = YES; + }; + name = Release; + }; + F879D8431B4B7F7D002D5C07 /* Profile */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = D0A463DB17E57C45000F5021 /* Test.xcconfig */; + buildSettings = { + CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x"; + CLANG_CXX_LIBRARY = "libc++"; + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_NULLABLE_TO_NONNULL_CONVERSION = NO; + CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_UNREACHABLE_CODE = YES; + CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; + COPY_PHASE_STRIP = NO; + DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; + ENABLE_NS_ASSERTIONS = NO; + ENABLE_STRICT_OBJC_MSGSEND = YES; + FRAMEWORK_SEARCH_PATHS = ( + "$(inherited)", + "$(PROJECT_DIR)/Carthage/Build/iOS", + ); + GCC_C_LANGUAGE_STANDARD = gnu99; + GCC_TREAT_WARNINGS_AS_ERRORS = NO; + GCC_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_ABOUT_DEPRECATED_FUNCTIONS = NO; + GCC_WARN_ABOUT_MISSING_FIELD_INITIALIZERS = NO; + GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; + GCC_WARN_UNDECLARED_SELECTOR = YES; + GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; + GCC_WARN_UNUSED_FUNCTION = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + HEADER_SEARCH_PATHS = "$(inherited)"; + INFOPLIST_FILE = "ObjectiveGitTests/ObjectiveGitTests-Info.plist"; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + "@loader_path/Frameworks", + ); + LIBRARY_SEARCH_PATHS = ( + ., + External, + ); + MTL_ENABLE_DEBUG_INFO = NO; + PRODUCT_BUNDLE_IDENTIFIER = "org.libgit2.$(PRODUCT_NAME:rfc1034identifier)"; + PRODUCT_NAME = "$(TARGET_NAME)"; + SDKROOT = iphoneos; + VALIDATE_PRODUCT = YES; + }; + name = Profile; + }; /* End XCBuildConfiguration section */ /* Begin XCConfigurationList section */ @@ -2012,6 +3046,17 @@ defaultConfigurationIsVisible = 0; defaultConfigurationName = Release; }; + F879D83F1B4B7F7D002D5C07 /* Build configuration list for PBXNativeTarget "ObjectiveGit-iOSTests" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + F879D8401B4B7F7D002D5C07 /* Debug */, + F879D8411B4B7F7D002D5C07 /* Test */, + F879D8421B4B7F7D002D5C07 /* Release */, + F879D8431B4B7F7D002D5C07 /* Profile */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; /* End XCConfigurationList section */ }; rootObject = 0867D690FE84028FC02AAC07 /* Project object */; diff --git a/ObjectiveGitFramework.xcodeproj/project.xcworkspace/contents.xcworkspacedata b/ObjectiveGitFramework.xcodeproj/project.xcworkspace/contents.xcworkspacedata new file mode 100644 index 000000000..f3c74e883 --- /dev/null +++ b/ObjectiveGitFramework.xcodeproj/project.xcworkspace/contents.xcworkspacedata @@ -0,0 +1,7 @@ + + + + + diff --git a/ObjectiveGitFramework.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist b/ObjectiveGitFramework.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist new file mode 100644 index 000000000..18d981003 --- /dev/null +++ b/ObjectiveGitFramework.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist @@ -0,0 +1,8 @@ + + + + + IDEDidComputeMac32BitWarning + + + diff --git a/ObjectiveGitFramework.xcodeproj/xcshareddata/xcschemes/ObjectiveGit Mac.xcscheme b/ObjectiveGitFramework.xcodeproj/xcshareddata/xcschemes/ObjectiveGit Mac.xcscheme index fe89b52dd..02ffc2cf1 100644 --- a/ObjectiveGitFramework.xcodeproj/xcshareddata/xcschemes/ObjectiveGit Mac.xcscheme +++ b/ObjectiveGitFramework.xcodeproj/xcshareddata/xcschemes/ObjectiveGit Mac.xcscheme @@ -1,6 +1,6 @@ + + + + + + + + + + + + + shouldUseLaunchSchemeArgsEnv = "YES"> + + + + @@ -53,25 +104,17 @@ - - - - - - + + + + + + + + + + + + + shouldUseLaunchSchemeArgsEnv = "YES"> + + + + - - - - - - - - + location = "group:../libgit2"> diff --git a/ObjectiveGitFramework.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist b/ObjectiveGitFramework.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist new file mode 100644 index 000000000..18d981003 --- /dev/null +++ b/ObjectiveGitFramework.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist @@ -0,0 +1,8 @@ + + + + + IDEDidComputeMac32BitWarning + + + diff --git a/ObjectiveGitFramework.xcworkspace/xcshareddata/WorkspaceSettings.xcsettings b/ObjectiveGitFramework.xcworkspace/xcshareddata/WorkspaceSettings.xcsettings new file mode 100644 index 000000000..0c67376eb --- /dev/null +++ b/ObjectiveGitFramework.xcworkspace/xcshareddata/WorkspaceSettings.xcsettings @@ -0,0 +1,5 @@ + + + + + diff --git a/ObjectiveGitTests/GTBlameSpec.m b/ObjectiveGitTests/GTBlameSpec.m index 8cd8a8225..2cbeec1a4 100644 --- a/ObjectiveGitTests/GTBlameSpec.m +++ b/ObjectiveGitTests/GTBlameSpec.m @@ -6,9 +6,9 @@ // Copyright (c) 2014 GitHub, Inc. All rights reserved. // -#import -#import -#import +@import ObjectiveGit; +@import Nimble; +@import Quick; #import "QuickSpec+GTFixtures.h" diff --git a/ObjectiveGitTests/GTBlobSpec.m b/ObjectiveGitTests/GTBlobSpec.m index fed7020ca..97e735337 100644 --- a/ObjectiveGitTests/GTBlobSpec.m +++ b/ObjectiveGitTests/GTBlobSpec.m @@ -6,9 +6,9 @@ // Copyright (c) 2013 GitHub, Inc. All rights reserved. // -#import -#import -#import +@import ObjectiveGit; +@import Nimble; +@import Quick; #import "QuickSpec+GTFixtures.h" diff --git a/ObjectiveGitTests/GTBranchSpec.m b/ObjectiveGitTests/GTBranchSpec.m index 631207b05..2b997e222 100644 --- a/ObjectiveGitTests/GTBranchSpec.m +++ b/ObjectiveGitTests/GTBranchSpec.m @@ -6,9 +6,9 @@ // Copyright (c) 2013 GitHub, Inc. All rights reserved. // -#import -#import -#import +@import ObjectiveGit; +@import Nimble; +@import Quick; #import "QuickSpec+GTFixtures.h" @@ -34,6 +34,16 @@ expect(error).to(beNil()); }); +describe(@"name", ^{ + it(@"should use just the branch name for a local branch", ^{ + expect(masterBranch.name).to(equal(@"master")); + }); + + it(@"should include the remote name for a tracking branch", ^{ + expect(trackingBranch.name).to(equal(@"origin/master")); + }); +}); + describe(@"shortName", ^{ it(@"should use just the branch name for a local branch", ^{ expect(masterBranch.shortName).to(equal(@"master")); @@ -121,13 +131,13 @@ it(@"should reload the branch from disk", ^{ static NSString * const originalSHA = @"a4bca6b67a5483169963572ee3da563da33712f7"; static NSString * const updatedSHA = @"6b0c1c8b8816416089c534e474f4c692a76ac14f"; - expect([masterBranch targetCommitAndReturnError:NULL].SHA).to(equal(originalSHA)); - [masterBranch.reference referenceByUpdatingTarget:updatedSHA committer:nil message:nil error:NULL]; + expect([masterBranch targetCommitWithError:NULL].SHA).to(equal(originalSHA)); + [masterBranch.reference referenceByUpdatingTarget:updatedSHA message:nil error:NULL]; GTBranch *reloadedBranch = [masterBranch reloadedBranchWithError:NULL]; expect(reloadedBranch).notTo(beNil()); - expect([reloadedBranch targetCommitAndReturnError:NULL].SHA).to(equal(updatedSHA)); - expect([masterBranch targetCommitAndReturnError:NULL].SHA).to(equal(originalSHA)); + expect([reloadedBranch targetCommitWithError:NULL].SHA).to(equal(updatedSHA)); + expect([masterBranch targetCommitWithError:NULL].SHA).to(equal(originalSHA)); }); }); @@ -158,11 +168,11 @@ GTOID *OID = [[GTOID alloc] initWithSHA:@"6b0c1c8b8816416089c534e474f4c692a76ac14f"]; NSError *error = nil; - GTReference *otherRef = [repository createReferenceNamed:@"refs/heads/yet-another-branch" fromOID:OID committer:nil message:nil error:&error]; + GTReference *otherRef = [repository createReferenceNamed:@"refs/heads/yet-another-branch" fromOID:OID message:nil error:&error]; expect(otherRef).notTo(beNil()); expect(error).to(beNil()); - GTBranch *otherBranch = [GTBranch branchWithReference:otherRef repository:repository]; + GTBranch *otherBranch = [GTBranch branchWithReference:otherRef]; expect(otherBranch).notTo(beNil()); BOOL success = NO; @@ -174,11 +184,11 @@ it(@"should return itself for a remote branch", ^{ NSError *error = nil; - GTReference *remoteRef = [GTReference referenceByLookingUpReferencedNamed:@"refs/remotes/origin/master" inRepository:repository error:&error]; + GTReference *remoteRef = [repository lookUpReferenceWithName:@"refs/remotes/origin/master" error:&error]; expect(remoteRef).notTo(beNil()); expect(error).to(beNil()); - GTBranch *remoteBranch = [GTBranch branchWithReference:remoteRef repository:repository]; + GTBranch *remoteBranch = [GTBranch branchWithReference:remoteRef]; expect(remoteBranch).notTo(beNil()); BOOL success = NO; @@ -189,28 +199,112 @@ }); }); -// TODO: Test branch renaming, branch upstream -//- (void)testCanRenameBranch { -// -// NSError *error = nil; -// GTRepository *repo = [GTRepository repoByOpeningRepositoryInDirectory:[NSURL URLWithString:TEST_REPO_PATH()] error:&error]; -// STAssertNil(error, [error localizedDescription]); -// -// NSArray *branches = [GTBranch listAllLocalBranchesInRepository:repo error:&error]; -// STAssertNotNil(branches, [error localizedDescription], nil); -// STAssertEquals(2, (int)branches.count, nil); -// -// NSString *newBranchName = [NSString stringWithFormat:@"%@%@", [GTBranch localNamePrefix], @"this_is_the_renamed_branch"]; -// GTBranch *firstBranch = [branches objectAtIndex:0]; -// NSString *originalBranchName = firstBranch.name; -// BOOL success = [firstBranch.reference setName:newBranchName error:&error]; -// STAssertTrue(success, [error localizedDescription]); -// STAssertEqualObjects(firstBranch.name, newBranchName, nil); -// -// success = [firstBranch.reference setName:originalBranchName error:&error]; -// STAssertTrue(success, [error localizedDescription]); -// STAssertEqualObjects(firstBranch.name, originalBranchName, nil); -//} +describe(@"-updateTrackingBranch:error:", ^{ + __block GTBranch *masterBranch; + beforeEach(^{ + masterBranch = [repository lookUpBranchWithName:@"master" type:GTBranchTypeLocal success:NULL error:NULL]; + expect(masterBranch).notTo(beNil()); + }); + + it(@"should set a tracking branch", ^{ + GTBranch *branch = [repository lookUpBranchWithName:@"feature" type:GTBranchTypeLocal success:NULL error:NULL]; + expect(branch).notTo(beNil()); + + BOOL success = NO; + GTBranch *trackingBranch = [branch trackingBranchWithError:NULL success:&success]; + expect(trackingBranch).to(beNil()); + expect(@(success)).to(beTruthy()); + + NSError *error; + success = [branch updateTrackingBranch:masterBranch error:&error]; + expect(@(success)).to(beTruthy()); + expect(error).to(beNil()); + + trackingBranch = [branch trackingBranchWithError:NULL success:&success]; + expect(trackingBranch).notTo(beNil()); + expect(@(success)).to(beTruthy()); + }); + + it(@"should unset a tracking branch", ^{ + BOOL success = NO; + GTBranch *trackingBranch = [masterBranch trackingBranchWithError:NULL success:&success]; + expect(trackingBranch).notTo(beNil()); + expect(@(success)).to(beTruthy()); + + success = [masterBranch updateTrackingBranch:nil error:NULL]; + expect(@(success)).to(beTruthy()); + + trackingBranch = [masterBranch trackingBranchWithError:NULL success:&success]; + expect(trackingBranch).to(beNil()); + expect(@(success)).to(beTruthy()); + }); + + it(@"should set a remote tracking branch without branches amount change", ^{ + GTRepository *repository = self.testAppForkFixtureRepository; + expect(repository).notTo(beNil()); + + NSError *error = nil; + BOOL success = NO; + GTBranch *remoteBranch = [repository lookUpBranchWithName:@"github/BranchC" type:GTBranchTypeRemote success:&success error:&error]; + expect(remoteBranch).notTo(beNil()); + expect(error).to(beNil()); + + NSArray *beforeBranches = [repository branches:&error]; + expect(error).to(beNil()); + + GTBranch *localBranch = [repository createBranchNamed:remoteBranch.shortName fromOID:remoteBranch.OID message:nil error:&error]; + expect(localBranch).notTo(beNil()); + expect(error).to(beNil()); + + NSArray *inBranches = [repository branches:&error]; + expect(error).to(beNil()); + + [localBranch updateTrackingBranch:remoteBranch error:&error]; + expect(error).to(beNil()); + + NSArray *afterBranches = [repository branches:&error]; + expect(error).to(beNil()); + + expect(@(beforeBranches.count + 1)).to(equal(@(inBranches.count))); + expect(@(beforeBranches.count)).to(equal(@(afterBranches.count))); + + }); +}); + +describe(@"-rename:force:error", ^{ + __block GTBranch *masterBranch; + beforeEach(^{ + masterBranch = [repository lookUpBranchWithName:@"master" type:GTBranchTypeLocal success:NULL error:NULL]; + expect(masterBranch).notTo(beNil()); + }); + + it(@"should rename the branch", ^{ + NSError *error = nil; + BOOL success = [masterBranch rename:@"plop" force:NO error:&error]; + expect(@(success)).to(beTruthy()); + expect(error).to(beNil()); + + expect(masterBranch.shortName).to(equal(@"plop")); + }); + + it(@"should fail on duplicates", ^{ + NSError *error = nil; + BOOL success = [masterBranch rename:@"feature" force:NO error:&error]; + expect(@(success)).to(beFalsy()); + expect(error).notTo(beNil()); + + expect(masterBranch.shortName).to(equal(@"master")); + }); + + it(@"should rename when forced", ^{ + NSError *error = nil; + BOOL success = [masterBranch rename:@"feature" force:YES error:&error]; + expect(@(success)).to(beTruthy()); + expect(error).to(beNil()); + + expect(masterBranch.shortName).to(equal(@"feature")); + }); +}); afterEach(^{ [self tearDown]; diff --git a/ObjectiveGitTests/GTCommitSpec.m b/ObjectiveGitTests/GTCommitSpec.m index 31e80e998..38ebe87ff 100644 --- a/ObjectiveGitTests/GTCommitSpec.m +++ b/ObjectiveGitTests/GTCommitSpec.m @@ -6,9 +6,9 @@ // Copyright (c) 2013 GitHub, Inc. All rights reserved. // -#import -#import -#import +@import ObjectiveGit; +@import Nimble; +@import Quick; #import "QuickSpec+GTFixtures.h" @@ -31,6 +31,7 @@ expect(commit).to(beAnInstanceOf(GTCommit.class)); expect(commit.type).to(equal(@"commit")); expect(commit.SHA).to(equal(commitSHA)); + expect(commit.OID).to(equal([GTOID oidWithSHA:commitSHA])); expect(commit.message).to(equal(@"testing\n")); expect(commit.messageSummary).to(equal(@"testing")); @@ -60,7 +61,14 @@ expect(commit).notTo(beNil()); expect(error).to(beNil()); - expect(@(commit.parents.count)).to(equal(@2)); + NSArray *commitOIDs = @[@"c47800c7266a2be04c571c04d5a6614691ea99bd", @"9fd738e8f7967c078dceed8190330fc8648ee56a"]; + NSArray *commitParents = commit.parentOIDs; + expect(@(commitParents.count)).to(equal(@(commitOIDs.count))); + expect([commitParents valueForKey:@"SHA"]).to(equal(commitOIDs)); + + commitParents = commit.parents; + expect(@(commitParents.count)).to(equal(@(commitOIDs.count))); + expect([commitParents valueForKeyPath:@"OID.SHA"]).to(equal(commitOIDs)); }); it(@"can identify merges", ^{ diff --git a/ObjectiveGitTests/GTConfigurationSpec.m b/ObjectiveGitTests/GTConfigurationSpec.m index c225a04ec..25f3c1248 100644 --- a/ObjectiveGitTests/GTConfigurationSpec.m +++ b/ObjectiveGitTests/GTConfigurationSpec.m @@ -6,9 +6,9 @@ // Copyright (c) 2013 GitHub, Inc. All rights reserved. // -#import -#import -#import +@import ObjectiveGit; +@import Nimble; +@import Quick; #import "QuickSpec+GTFixtures.h" diff --git a/ObjectiveGitTests/GTDiffDeltaSpec.m b/ObjectiveGitTests/GTDiffDeltaSpec.m index e326861f5..81c1ae0e0 100644 --- a/ObjectiveGitTests/GTDiffDeltaSpec.m +++ b/ObjectiveGitTests/GTDiffDeltaSpec.m @@ -6,9 +6,9 @@ // Copyright (c) 2014 GitHub, Inc. All rights reserved. // -#import -#import -#import +@import ObjectiveGit; +@import Nimble; +@import Quick; #import "QuickSpec+GTFixtures.h" diff --git a/ObjectiveGitTests/GTDiffSpec.m b/ObjectiveGitTests/GTDiffSpec.m index 676dda6bb..0ad3eea82 100644 --- a/ObjectiveGitTests/GTDiffSpec.m +++ b/ObjectiveGitTests/GTDiffSpec.m @@ -6,9 +6,9 @@ // Copyright (c) 2012 GitHub, Inc. All rights reserved. // -#import -#import -#import +@import ObjectiveGit; +@import Nimble; +@import Quick; #import "QuickSpec+GTFixtures.h" @@ -90,7 +90,7 @@ setupDiffFromCommitSHAsAndOptions(@"be0f001ff517a00b5b8e3c29ee6561e70f994e17", @"fe89ea0a8e70961b8a6344d9660c326d3f2eb0fe", nil); expect(@(diff.deltaCount)).to(equal(@1)); - expect(@([diff numberOfDeltasWithType:GTDiffFileDeltaModified])).to(equal(@1)); + expect(@([diff numberOfDeltasWithType:GTDeltaTypeModified])).to(equal(@1)); [diff enumerateDeltasUsingBlock:^(GTDiffDelta *delta, BOOL *stop) { NSError *error = nil; @@ -101,7 +101,7 @@ expect(delta.oldFile.path).to(equal(@"TestAppWindowController.h")); expect(delta.oldFile.path).to(equal(delta.newFile.path)); expect(@(delta.flags & GTDiffFileFlagBinaryMask)).to(equal(@(GTDiffFileFlagNotBinary))); - expect(@(delta.type)).to(equal(@(GTDiffFileDeltaModified))); + expect(@(delta.type)).to(equal(@(GTDeltaTypeModified))); expect(patch.delta).to(beIdenticalTo(delta)); expect(@(patch.hunkCount)).to(equal(@1)); @@ -112,6 +112,10 @@ [patch enumerateHunksUsingBlock:^(GTDiffHunk *hunk, BOOL *stop) { expect(hunk.header).to(equal(@"@@ -4,7 +4,7 @@")); expect(@(hunk.lineCount)).to(equal(@8)); + expect(@(hunk.oldStart)).to(equal(@4)); + expect(@(hunk.oldLines)).to(equal(@7)); + expect(@(hunk.newStart)).to(equal(@4)); + expect(@(hunk.newLines)).to(equal(@7)); NSArray *expectedLines = @[ @"//", @"// Created by Joe Ricioppo on 9/29/10.", @@ -151,7 +155,7 @@ expect(@(diff.deltaCount)).to(equal(@1)); [diff enumerateDeltasUsingBlock:^(GTDiffDelta *delta, BOOL *stop) { expect(delta.newFile.path).to(equal(@"REAME")); //loltypo - expect(@(delta.type)).to(equal(@(GTDiffFileDeltaAdded))); + expect(@(delta.type)).to(equal(@(GTDeltaTypeAdded))); *stop = YES; }]; @@ -162,7 +166,7 @@ expect(@(diff.deltaCount)).to(equal(@1)); [diff enumerateDeltasUsingBlock:^(GTDiffDelta *delta, BOOL *stop) { - expect(@(delta.type)).to(equal(@(GTDiffFileDeltaDeleted))); + expect(@(delta.type)).to(equal(@(GTDeltaTypeDeleted))); *stop = YES; }]; @@ -189,7 +193,7 @@ expect(@(diff.deltaCount)).to(equal(@1)); [diff enumerateDeltasUsingBlock:^(GTDiffDelta *delta, BOOL *stop) { - expect(@(delta.type)).to(equal(@(GTDiffFileDeltaRenamed))); + expect(@(delta.type)).to(equal(@(GTDeltaTypeRenamed))); expect(delta.oldFile.path).to(equal(@"README")); expect(delta.newFile.path).to(equal(@"README_renamed")); diff --git a/ObjectiveGitTests/GTEnumeratorSpec.m b/ObjectiveGitTests/GTEnumeratorSpec.m index c88abcc8e..70f4e4784 100644 --- a/ObjectiveGitTests/GTEnumeratorSpec.m +++ b/ObjectiveGitTests/GTEnumeratorSpec.m @@ -6,9 +6,9 @@ // Copyright (c) 2013 GitHub, Inc. All rights reserved. // -#import -#import -#import +@import ObjectiveGit; +@import Nimble; +@import Quick; #import "QuickSpec+GTFixtures.h" @@ -31,10 +31,12 @@ GTReference *HEADRef = [repo headReferenceWithError:NULL]; expect(HEADRef).notTo(beNil()); - [enumerator pushSHA:HEADRef.targetSHA error:NULL]; + BOOL success = [enumerator pushSHA:HEADRef.targetOID.SHA error:&error]; + expect(@(success)).to(beTruthy()); + expect(error).to(beNil()); + NSUInteger count = [enumerator allObjects].count; expect(@(count)).to(equal(@3)); - expect(error).to(beNil()); }); describe(@"with a rev list", ^{ diff --git a/ObjectiveGitTests/GTFilterListSpec.m b/ObjectiveGitTests/GTFilterListSpec.m index f093dfe0c..97313a562 100644 --- a/ObjectiveGitTests/GTFilterListSpec.m +++ b/ObjectiveGitTests/GTFilterListSpec.m @@ -6,9 +6,9 @@ // Copyright (c) 2014 GitHub, Inc. All rights reserved. // -#import -#import -#import +@import ObjectiveGit; +@import Nimble; +@import Quick; #import "QuickSpec+GTFixtures.h" diff --git a/ObjectiveGitTests/GTFilterSpec.m b/ObjectiveGitTests/GTFilterSpec.m index 2f969e731..7ab7a5597 100644 --- a/ObjectiveGitTests/GTFilterSpec.m +++ b/ObjectiveGitTests/GTFilterSpec.m @@ -6,9 +6,9 @@ // Copyright (c) 2014 GitHub, Inc. All rights reserved. // -#import -#import -#import +@import ObjectiveGit; +@import Nimble; +@import Quick; #import "QuickSpec+GTFixtures.h" @@ -159,7 +159,7 @@ BOOL success = [NSFileManager.defaultManager removeItemAtURL:testFileURL error:NULL]; expect(@(success)).to(beTruthy()); - success = [repository checkoutCommit:newCommit strategy:GTCheckoutStrategyForce error:NULL progressBlock:NULL]; + success = [repository checkoutCommit:newCommit options:[GTCheckoutOptions checkoutOptionsWithStrategy:GTCheckoutStrategyForce] error:NULL]; expect(@(success)).to(beTruthy()); expect([NSData dataWithContentsOfURL:testFileURL]).to(equal(replacementData)); diff --git a/ObjectiveGitTests/GTIndexSpec.m b/ObjectiveGitTests/GTIndexSpec.m index 222e82501..4e894153a 100644 --- a/ObjectiveGitTests/GTIndexSpec.m +++ b/ObjectiveGitTests/GTIndexSpec.m @@ -6,9 +6,9 @@ // Copyright (c) 2013 GitHub, Inc. All rights reserved. // -#import -#import -#import +@import ObjectiveGit; +@import Nimble; +@import Quick; #import "QuickSpec+GTFixtures.h" @@ -52,9 +52,9 @@ it(@"should write to a specific repository and return a tree", ^{ GTRepository *repository = self.bareFixtureRepository; - NSArray *branches = [repository allBranchesWithError:NULL]; - GTCommit *masterCommit = [branches[0] targetCommitAndReturnError:NULL]; - GTCommit *packedCommit = [branches[1] targetCommitAndReturnError:NULL]; + NSArray *branches = [repository branches:NULL]; + GTCommit *masterCommit = [branches[0] targetCommitWithError:NULL]; + GTCommit *packedCommit = [branches[1] targetCommitWithError:NULL]; expect(masterCommit).notTo(beNil()); expect(packedCommit).notTo(beNil()); @@ -92,7 +92,7 @@ if (treeEntry.type == GTObjectTypeBlob) { NSString *path = [root stringByAppendingString:treeEntry.name]; - GTIndexEntry *indexEntry = [memoryIndex entryWithName:path]; + GTIndexEntry *indexEntry = [memoryIndex entryWithPath:path]; expect(indexEntry).notTo(beNil()); } @@ -202,7 +202,7 @@ NSDictionary *renamedOptions = @{ GTRepositoryStatusOptionsFlagsKey: @(GTRepositoryStatusFlagsIncludeIgnored | GTRepositoryStatusFlagsIncludeUntracked | GTRepositoryStatusFlagsRecurseUntrackedDirectories | GTRepositoryStatusFlagsRenamesHeadToIndex | GTRepositoryStatusFlagsIncludeUnmodified) }; - BOOL (^fileStatusEqualsExpected)(NSString *filename, GTStatusDeltaStatus headToIndexStatus, GTStatusDeltaStatus indexToWorkingDirectoryStatus) = ^(NSString *filename, GTStatusDeltaStatus headToIndexStatus, GTStatusDeltaStatus indexToWorkingDirectoryStatus) { + BOOL (^fileStatusEqualsExpected)(NSString *filename, GTDeltaType headToIndexStatus, GTDeltaType indexToWorkingDirectoryStatus) = ^(NSString *filename, GTDeltaType headToIndexStatus, GTDeltaType indexToWorkingDirectoryStatus) { return [index.repository enumerateFileStatusWithOptions:renamedOptions error:NULL usingBlock:^(GTStatusDelta *headToIndex, GTStatusDelta *indexToWorkingDirectory, BOOL *stop) { if (![headToIndex.newFile.path isEqualToString:filename]) return; expect(@(headToIndex.status)).to(equal(@(headToIndexStatus))); @@ -227,52 +227,104 @@ renamedFileURL = [NSURL fileURLWithPath:newPath isDirectory:NO]; }); + it(@"should add all files from the current file system to the index", ^{ + NSData *currentFileContent = [[NSFileManager defaultManager] contentsAtPath:fileURL.path]; + expect(currentFileContent).notTo(beNil()); + NSString *currentFileString = [[NSString alloc] initWithData:currentFileContent encoding:NSUTF8StringEncoding]; + currentFileString = [currentFileString stringByAppendingString:@"I would like to append this to the file"]; + currentFileContent = [currentFileString dataUsingEncoding:NSUTF8StringEncoding]; + expect(@([[NSFileManager defaultManager] createFileAtPath:fileURL.path contents:currentFileContent attributes:nil])).to(beTruthy()); + + NSString *newFileContent = @"This is a new file \n1 2 3"; + NSData *newFileData = [newFileContent dataUsingEncoding:NSUTF8StringEncoding]; + expect(newFileData).notTo(beNil()); + expect(@([[NSFileManager defaultManager] createFileAtPath:renamedFileURL.path contents:newFileData attributes:nil])).to(beTruthy()); + + GTIndexEntry *entry = [index entryWithPath:[filename decomposedStringWithCanonicalMapping]]; + expect(@(fileStatusEqualsExpected(entry.path, GTDeltaTypeUnmodified, GTDeltaTypeModified))).to(beTruthy()); + entry = [index entryWithPath:[renamedFilename decomposedStringWithCanonicalMapping]]; + expect(@(fileStatusEqualsExpected(entry.path, GTDeltaTypeUnmodified, GTDeltaTypeUntracked))).to(beTruthy()); + + expect(@([index addAll:NULL])).to(beTruthy()); + expect(@([index write:NULL])).to(beTruthy()); + + entry = [index entryWithPath:[filename decomposedStringWithCanonicalMapping]]; + expect(@(fileStatusEqualsExpected(entry.path, GTDeltaTypeModified, GTDeltaTypeUnmodified))).to(beTruthy()); + entry = [index entryWithPath:[renamedFilename decomposedStringWithCanonicalMapping]]; + expect(@(fileStatusEqualsExpected(entry.path, GTDeltaTypeAdded, GTDeltaTypeUnmodified))).to(beTruthy()); + }); + it(@"it preserves decomposed Unicode in index paths with precomposeunicode disabled", ^{ NSString *decomposedFilename = [filename decomposedStringWithCanonicalMapping]; - GTIndexEntry *entry = [index entryWithName:decomposedFilename error:NULL]; - expect(@(fileStatusEqualsExpected(entry.path, GTStatusDeltaStatusUnmodified, GTStatusDeltaStatusUnmodified))).to(beTruthy()); + GTIndexEntry *entry = [index entryWithPath:decomposedFilename error:NULL]; + expect(@(fileStatusEqualsExpected(entry.path, GTDeltaTypeUnmodified, GTDeltaTypeUnmodified))).to(beTruthy()); expect(@([[NSFileManager defaultManager] moveItemAtURL:fileURL toURL:renamedFileURL error:NULL])).to(beTruthy()); - entry = [index entryWithName:decomposedFilename error:NULL]; - expect(@(fileStatusEqualsExpected(entry.path, GTStatusDeltaStatusUnmodified, GTStatusDeltaStatusDeleted))).to(beTruthy()); + entry = [index entryWithPath:decomposedFilename error:NULL]; + expect(@(fileStatusEqualsExpected(entry.path, GTDeltaTypeUnmodified, GTDeltaTypeDeleted))).to(beTruthy()); [index removeFile:filename error:NULL]; [index addFile:renamedFilename error:NULL]; [index write:NULL]; - entry = [index entryWithName:[renamedFilename decomposedStringWithCanonicalMapping] error:NULL]; - expect(@(fileStatusEqualsExpected(entry.path, GTStatusDeltaStatusRenamed, GTStatusDeltaStatusUnmodified))).to(beTruthy()); + entry = [index entryWithPath:[renamedFilename decomposedStringWithCanonicalMapping] error:NULL]; + expect(@(fileStatusEqualsExpected(entry.path, GTDeltaTypeRenamed, GTDeltaTypeUnmodified))).to(beTruthy()); }); it(@"it preserves precomposed Unicode in index paths with precomposeunicode enabled", ^{ - GTIndexEntry *fileEntry = [index entryWithName:[filename decomposedStringWithCanonicalMapping] error:NULL]; + GTIndexEntry *fileEntry = [index entryWithPath:[filename decomposedStringWithCanonicalMapping] error:NULL]; expect(fileEntry).notTo(beNil()); - expect(@(fileStatusEqualsExpected(fileEntry.path, GTStatusDeltaStatusUnmodified, GTStatusDeltaStatusUnmodified))).to(beTruthy()); + expect(@(fileStatusEqualsExpected(fileEntry.path, GTDeltaTypeUnmodified, GTDeltaTypeUnmodified))).to(beTruthy()); [configuration setBool:true forKey:@"core.precomposeunicode"]; expect(@([configuration boolForKey:@"core.precomposeunicode"])).to(beTruthy()); - GTIndexEntry *decomposedFileEntry = [index entryWithName:[filename decomposedStringWithCanonicalMapping] error:NULL]; + GTIndexEntry *decomposedFileEntry = [index entryWithPath:[filename decomposedStringWithCanonicalMapping] error:NULL]; expect(decomposedFileEntry).notTo(beNil()); - expect(@(fileStatusEqualsExpected(decomposedFileEntry.path, GTStatusDeltaStatusUnmodified, GTStatusDeltaStatusDeleted))).to(beTruthy()); + expect(@(fileStatusEqualsExpected(decomposedFileEntry.path, GTDeltaTypeUnmodified, GTDeltaTypeDeleted))).to(beTruthy()); expect(@([[NSFileManager defaultManager] moveItemAtURL:fileURL toURL:renamedFileURL error:NULL])).to(beTruthy()); - GTIndexEntry *precomposedFileEntry = [index entryWithName:filename error:NULL]; + GTIndexEntry *precomposedFileEntry = [index entryWithPath:filename error:NULL]; expect(precomposedFileEntry).to(beNil()); - decomposedFileEntry = [index entryWithName:[filename decomposedStringWithCanonicalMapping] error:NULL]; + decomposedFileEntry = [index entryWithPath:[filename decomposedStringWithCanonicalMapping] error:NULL]; expect(decomposedFileEntry).notTo(beNil()); - expect(@(fileStatusEqualsExpected(decomposedFileEntry.path, GTStatusDeltaStatusUnmodified, GTStatusDeltaStatusDeleted))).to(beTruthy()); + expect(@(fileStatusEqualsExpected(decomposedFileEntry.path, GTDeltaTypeUnmodified, GTDeltaTypeDeleted))).to(beTruthy()); [index removeFile:filename error:NULL]; [index addFile:renamedFilename error:NULL]; [index write:NULL]; - GTIndexEntry *precomposedRenamedFileEntry = [index entryWithName:renamedFilename error:NULL]; + GTIndexEntry *precomposedRenamedFileEntry = [index entryWithPath:renamedFilename error:NULL]; expect(precomposedRenamedFileEntry).notTo(beNil()); - expect(@(fileStatusEqualsExpected(precomposedFileEntry.path, GTStatusDeltaStatusRenamed, GTStatusDeltaStatusUntracked))).to(beTruthy()); + expect(@(fileStatusEqualsExpected(precomposedFileEntry.path, GTDeltaTypeRenamed, GTDeltaTypeUntracked))).to(beTruthy()); + }); +}); + +describe(@"adding data", ^{ + __block GTRepository *repo; + __block GTIndex *index; + __block NSError *error; + + beforeEach(^{ + error = nil; + repo = self.testUnicodeFixtureRepository; + // Not sure why but it doesn't work with an in memory index + // index = [GTIndex inMemoryIndexWithRepository:repo error:&error]; + index = [repo indexWithError:&error]; + expect(error).to(beNil()); + }); + + it(@"should store data at given path", ^{ + NSData *data = [NSData dataWithBytes:"foo" length:4]; + [index addData:data withPath:@"bar/foo" error:&error]; + expect(error).to(beNil()); + + GTIndexEntry *entry = [index entryWithPath:@"bar/foo" error:&error]; + expect(entry).notTo(beNil()); + expect(error).to(beNil()); }); }); diff --git a/ObjectiveGitTests/GTNoteSpec.m b/ObjectiveGitTests/GTNoteSpec.m new file mode 100644 index 000000000..3f977df5c --- /dev/null +++ b/ObjectiveGitTests/GTNoteSpec.m @@ -0,0 +1,87 @@ +// +// GTNoteSpec.m +// ObjectiveGitFramework +// +// Created by Slava Karpenko on 2016/05/17. +// Copyright (c) 2016 Wildbit LLC. All rights reserved. +// + +@import ObjectiveGit; +@import Nimble; +@import Quick; + +#import "QuickSpec+GTFixtures.h" + +QuickSpecBegin(GTNoteSpec) + +__block GTRepository *repository; +__block GTCommit *initialCommit; + +beforeEach(^{ + NSURL *fileURL = [self.tempDirectoryFileURL URLByAppendingPathComponent:[[NSUUID alloc] init].UUIDString isDirectory:NO]; + repository = [GTRepository initializeEmptyRepositoryAtFileURL:fileURL options:nil error:NULL]; + expect(repository).notTo(beNil()); + + GTTreeBuilder *builder = [[GTTreeBuilder alloc] initWithTree:nil repository:repository error:NULL]; + expect(builder).notTo(beNil()); + + GTTreeEntry *entry = [builder addEntryWithData:[@"Xyzzy" dataUsingEncoding:NSUTF8StringEncoding] fileName:@"test.txt" fileMode:GTFileModeBlob error:NULL]; + expect(entry).notTo(beNil()); + + GTTree *tree = [builder writeTree:NULL]; + expect(tree).notTo(beNil()); + + initialCommit = [repository createCommitWithTree:tree message:@"Initial commit" parents:nil updatingReferenceNamed:@"refs/heads/master" error:NULL]; + expect(initialCommit).notTo(beNil()); +}); + +it(@"can create notes", ^{ + // Annotate the commit + GTSignature *sig = [repository userSignatureForNow]; + expect(sig).notTo(beNil()); + + NSError *err = nil; + + GTNote *note = [repository createNote:@"Note text" target:initialCommit referenceName:nil author:sig committer:sig overwriteIfExists:YES error:&err]; + expect(note).notTo(beNil()); + expect(err).to(beNil()); + + [repository enumerateNotesWithReferenceName:nil error:&err usingBlock:^(GTNote *note, GTObject *object, NSError *error, BOOL *stop) { + expect(error).to(beNil()); + expect(note).notTo(beNil()); + expect(object).notTo(beNil()); + + expect(note.note).to(equal(@"Note text")); + }]; + expect(err).to(beNil()); +}); + +it(@"can delete notes", ^{ + // Annotate the commit + GTSignature *sig = [repository userSignatureForNow]; + expect(sig).notTo(beNil()); + + NSError *err = nil; + + GTNote *note = [repository createNote:@"Note text" target:initialCommit referenceName:nil author:sig committer:sig overwriteIfExists:YES error:&err]; + expect(note).notTo(beNil()); + expect(err).to(beNil()); + + BOOL res = [repository removeNoteFromObject:initialCommit referenceName:nil author:sig committer:sig error:&err]; + expect(@(res)).to(beTrue()); + expect(err).to(beNil()); + + NSMutableArray *notes = [NSMutableArray arrayWithCapacity:0]; + + [repository enumerateNotesWithReferenceName:nil error:&err usingBlock:^(GTNote *note, GTObject *object, NSError *error, BOOL *stop) { + [notes addObject:note]; + }]; + + expect(@(notes.count)).to(equal(@(0))); +}); + +afterEach(^{ + [self tearDown]; +}); + +QuickSpecEnd diff --git a/ObjectiveGitTests/GTOIDSpec.m b/ObjectiveGitTests/GTOIDSpec.m index 3f301caa9..ae9421a1f 100644 --- a/ObjectiveGitTests/GTOIDSpec.m +++ b/ObjectiveGitTests/GTOIDSpec.m @@ -6,9 +6,9 @@ // Copyright (c) 2013 GitHub, Inc. All rights reserved. // -#import -#import -#import +@import ObjectiveGit; +@import Nimble; +@import Quick; #import "QuickSpec+GTFixtures.h" @@ -48,7 +48,7 @@ const git_oid *git_oid = NULL; { - GTOID *testOID __attribute__((objc_precise_lifetime)) = [[GTOID alloc] initWithSHA:testSHA]; + GTOID *testOID = [[GTOID alloc] initWithSHA:testSHA]; git_oid = testOID.git_oid; } diff --git a/ObjectiveGitTests/GTObjectDatabaseSpec.m b/ObjectiveGitTests/GTObjectDatabaseSpec.m index f68ed056f..654a06fc8 100644 --- a/ObjectiveGitTests/GTObjectDatabaseSpec.m +++ b/ObjectiveGitTests/GTObjectDatabaseSpec.m @@ -6,9 +6,9 @@ // Copyright (c) 2013 GitHub, Inc. All rights reserved. // -#import -#import -#import +@import ObjectiveGit; +@import Nimble; +@import Quick; #import "QuickSpec+GTFixtures.h" diff --git a/ObjectiveGitTests/GTObjectSpec.m b/ObjectiveGitTests/GTObjectSpec.m index c8e89ea0a..677b9c5d2 100644 --- a/ObjectiveGitTests/GTObjectSpec.m +++ b/ObjectiveGitTests/GTObjectSpec.m @@ -27,8 +27,9 @@ // THE SOFTWARE. // -#import -#import +@import ObjectiveGit; +@import Nimble; +@import Quick; #import "QuickSpec+GTFixtures.h" diff --git a/ObjectiveGitTests/GTReferenceSpec.m b/ObjectiveGitTests/GTReferenceSpec.m index 54bb2e687..a3b9b4022 100644 --- a/ObjectiveGitTests/GTReferenceSpec.m +++ b/ObjectiveGitTests/GTReferenceSpec.m @@ -6,9 +6,9 @@ // Copyright (c) 2013 GitHub, Inc. All rights reserved. // -#import -#import -#import +@import ObjectiveGit; +@import Nimble; +@import Quick; #import "QuickSpec+GTFixtures.h" @@ -22,17 +22,17 @@ }); it(@"should compare equal to the same reference", ^{ - expect([[GTReference alloc] initByLookingUpReferenceNamed:@"refs/heads/master" inRepository:repository error:NULL]).to(equal([[GTReference alloc] initByLookingUpReferenceNamed:@"refs/heads/master" inRepository:repository error:NULL])); + expect([repository lookUpReferenceWithName:@"refs/heads/master" error:NULL]).to(equal([repository lookUpReferenceWithName:@"refs/heads/master" error:NULL])); }); it(@"should compare unequal to a different reference", ^{ - expect([[GTReference alloc] initByLookingUpReferenceNamed:@"refs/heads/master" inRepository:repository error:NULL]).notTo(equal([[GTReference alloc] initByLookingUpReferenceNamed:@"refs/remotes/origin/master" inRepository:repository error:NULL])); + expect([repository lookUpReferenceWithName:@"refs/heads/master" error:NULL]).notTo(equal([repository lookUpReferenceWithName:@"refs/remotes/origin/master" error:NULL])); }); describe(@"remote property", ^{ it(@"should be YES for a remote-tracking branch", ^{ NSError *error = nil; - GTReference *ref = [[GTReference alloc] initByLookingUpReferenceNamed:@"refs/remotes/origin/master" inRepository:repository error:&error]; + GTReference *ref = [repository lookUpReferenceWithName:@"refs/remotes/origin/master" error:&error]; expect(ref).notTo(beNil()); expect(error).to(beNil()); @@ -42,7 +42,7 @@ it(@"should be NO for a local branch", ^{ NSError *error = nil; - GTReference *ref = [[GTReference alloc] initByLookingUpReferenceNamed:@"refs/heads/master" inRepository:repository error:&error]; + GTReference *ref = [repository lookUpReferenceWithName:@"refs/heads/master" error:&error]; expect(ref).notTo(beNil()); expect(error).to(beNil()); @@ -62,10 +62,10 @@ expect(repository).notTo(beNil()); NSError *error; - reference = [repository createReferenceNamed:testRefName fromOID:testRefOID committer:nil message:nil error:&error]; + reference = [repository createReferenceNamed:testRefName fromOID:testRefOID message:nil error:&error]; expect(reference).notTo(beNil()); expect(reference.name).to(equal(testRefName)); - expect(reference.targetSHA).to(equal(testRefOID.SHA)); + expect(reference.targetOID).to(equal(testRefOID)); }); it(@"should be able to be renamed", ^{ @@ -74,16 +74,16 @@ GTReference *renamedRef = [reference referenceByRenaming:newRefName error:NULL]; expect(renamedRef).notTo(beNil()); expect(renamedRef.name).to(equal(newRefName)); - expect(renamedRef.targetSHA).to(equal(testRefOID.SHA)); + expect(renamedRef.targetOID).to(equal(testRefOID)); }); it(@"should be able to change the target", ^{ NSString *newRefTarget = @"5b5b025afb0b4c913b4c338a42934a3863bf3644"; - GTReference *updatedRef = [reference referenceByUpdatingTarget:newRefTarget committer:nil message:nil error:NULL]; + GTReference *updatedRef = [reference referenceByUpdatingTarget:newRefTarget message:nil error:NULL]; expect(updatedRef).notTo(beNil()); expect(updatedRef.name).to(equal(testRefName)); - expect(updatedRef.targetSHA).to(equal(newRefTarget)); + expect(updatedRef.targetOID.SHA).to(equal(newRefTarget)); }); }); @@ -119,7 +119,7 @@ void (^expectValidReference)(GTReference *ref, NSString *SHA, GTReferenceType type, NSString *name) = ^(GTReference *ref, NSString *SHA, GTReferenceType type, NSString *name) { expect(ref).notTo(beNil()); - expect(ref.targetSHA).to(equal(SHA)); + expect(ref.targetOID.SHA).to(equal(SHA)); expect(@(ref.referenceType)).to(equal(@(type))); expect(ref.name).to(equal(name)); }; @@ -131,30 +131,30 @@ describe(@"+referenceByLookingUpReferenceNamed:inRepository:error:", ^{ it(@"should return a valid reference to a branch", ^{ NSError *error = nil; - GTReference *ref = [GTReference referenceByLookingUpReferencedNamed:@"refs/heads/master" inRepository:bareRepository error:&error]; + GTReference *ref = [bareRepository lookUpReferenceWithName:@"refs/heads/master" error:&error]; expect(ref).notTo(beNil()); expect(error).to(beNil()); - expectValidReference(ref, @"36060c58702ed4c2a40832c51758d5344201d89a", GTReferenceTypeOid, @"refs/heads/master"); + expectValidReference(ref, @"36060c58702ed4c2a40832c51758d5344201d89a", GTReferenceTypeDirect, @"refs/heads/master"); }); it(@"should return a valid reference to a tag", ^{ NSError *error = nil; - GTReference *ref = [GTReference referenceByLookingUpReferencedNamed:@"refs/tags/v0.9" inRepository:bareRepository error:&error]; + GTReference *ref = [bareRepository lookUpReferenceWithName:@"refs/tags/v0.9" error:&error]; expect(ref).notTo(beNil()); expect(error).to(beNil()); - expectValidReference(ref, @"5b5b025afb0b4c913b4c338a42934a3863bf3644", GTReferenceTypeOid, @"refs/tags/v0.9"); + expectValidReference(ref, @"5b5b025afb0b4c913b4c338a42934a3863bf3644", GTReferenceTypeDirect, @"refs/tags/v0.9"); }); }); describe(@"creating", ^{ it(@"can create a reference from a symbolic reference", ^{ - GTReference *target = [[GTReference alloc] initByLookingUpReferenceNamed:@"refs/heads/master" inRepository:bareRepository error:NULL]; + GTReference *target = [bareRepository lookUpReferenceWithName:@"refs/heads/master" error:NULL]; expect(target).notTo(beNil()); NSError *error = nil; - GTReference *ref = [bareRepository createReferenceNamed:@"refs/heads/unit_test" fromReference:target committer:nil message:nil error:&error]; + GTReference *ref = [bareRepository createReferenceNamed:@"refs/heads/unit_test" fromReference:target message:nil error:&error]; expect(error).to(beNil()); expect(ref).notTo(beNil()); @@ -166,11 +166,11 @@ GTOID *target = [[GTOID alloc] initWithSHA:@"36060c58702ed4c2a40832c51758d5344201d89a"]; NSError *error = nil; - GTReference *ref = [bareRepository createReferenceNamed:@"refs/heads/unit_test" fromOID:target committer:nil message:nil error:&error]; + GTReference *ref = [bareRepository createReferenceNamed:@"refs/heads/unit_test" fromOID:target message:nil error:&error]; expect(error).to(beNil()); expect(ref).notTo(beNil()); - expectValidReference(ref, @"36060c58702ed4c2a40832c51758d5344201d89a", GTReferenceTypeOid, @"refs/heads/unit_test"); + expectValidReference(ref, @"36060c58702ed4c2a40832c51758d5344201d89a", GTReferenceTypeDirect, @"refs/heads/unit_test"); }); }); @@ -179,7 +179,7 @@ GTOID *target = [[GTOID alloc] initWithSHA:@"36060c58702ed4c2a40832c51758d5344201d89a"]; NSError *error = nil; - GTReference *ref = [bareRepository createReferenceNamed:@"refs/heads/unit_test" fromOID:target committer:nil message:nil error:&error]; + GTReference *ref = [bareRepository createReferenceNamed:@"refs/heads/unit_test" fromOID:target message:nil error:&error]; expect(error).to(beNil()); expect(ref).notTo(beNil()); diff --git a/ObjectiveGitTests/GTReflogSpec.m b/ObjectiveGitTests/GTReflogSpec.m index dbd484f1f..cc4bd022b 100644 --- a/ObjectiveGitTests/GTReflogSpec.m +++ b/ObjectiveGitTests/GTReflogSpec.m @@ -6,9 +6,9 @@ // Copyright (c) 2013 GitHub, Inc. All rights reserved. // -#import -#import -#import +@import ObjectiveGit; +@import Nimble; +@import Quick; #import "QuickSpec+GTFixtures.h" diff --git a/ObjectiveGitTests/GTRemotePushSpec.m b/ObjectiveGitTests/GTRemotePushSpec.m new file mode 100644 index 000000000..a4c4af331 --- /dev/null +++ b/ObjectiveGitTests/GTRemotePushSpec.m @@ -0,0 +1,171 @@ +// +// GTRemotePushSpec.m +// ObjectiveGitFramework +// +// Created by Ben Chatelain on 11/14/2014. +// Copyright (c) 2014 GitHub, Inc. All rights reserved. +// + +@import ObjectiveGit; +@import Nimble; +@import Quick; + +#import "QuickSpec+GTFixtures.h" +#import "GTUtilityFunctions.h" + +#pragma mark - GTRemotePushSpec + +QuickSpecBegin(GTRemotePushSpec) + +describe(@"pushing", ^{ + __block GTRepository *notBareRepo; + + beforeEach(^{ + notBareRepo = self.bareFixtureRepository; + expect(notBareRepo).notTo(beNil()); + // This repo is not really "bare" according to libgit2 + expect(@(notBareRepo.isBare)).to(beFalsy()); + }); + + describe(@"to remote", ^{ // via local transport + __block NSURL *remoteRepoURL; + __block NSURL *localRepoURL; + __block GTRepository *remoteRepo; + __block GTRepository *localRepo; + __block GTRemote *remote; + __block NSError *error; + + beforeEach(^{ + // Make a bare clone to serve as the remote + remoteRepoURL = [notBareRepo.gitDirectoryURL.URLByDeletingLastPathComponent URLByAppendingPathComponent:@"bare_remote_repo.git"]; + NSDictionary *options = @{ GTRepositoryCloneOptionsBare: @1 }; + remoteRepo = [GTRepository cloneFromURL:notBareRepo.gitDirectoryURL toWorkingDirectory:remoteRepoURL options:options error:&error transferProgressBlock:NULL]; + expect(error).to(beNil()); + expect(remoteRepo).notTo(beNil()); + expect(@(remoteRepo.isBare)).to(beTruthy()); // that's better + + localRepoURL = [remoteRepoURL.URLByDeletingLastPathComponent URLByAppendingPathComponent:@"local_push_repo"]; + expect(localRepoURL).notTo(beNil()); + + // Local clone for testing pushes + localRepo = [GTRepository cloneFromURL:remoteRepoURL toWorkingDirectory:localRepoURL options:nil error:&error transferProgressBlock:NULL]; + + expect(error).to(beNil()); + expect(localRepo).notTo(beNil()); + + GTConfiguration *configuration = [localRepo configurationWithError:&error]; + expect(error).to(beNil()); + expect(configuration).notTo(beNil()); + + expect(@(configuration.remotes.count)).to(equal(@1)); + + remote = configuration.remotes[0]; + expect(remote.name).to(equal(@"origin")); + }); + + afterEach(^{ + [NSFileManager.defaultManager removeItemAtURL:remoteRepoURL error:&error]; + expect(error).to(beNil()); + [NSFileManager.defaultManager removeItemAtURL:localRepoURL error:&error]; + expect(error).to(beNil()); + error = NULL; + }); + + context(@"when the local and remote branches are in sync", ^{ + it(@"should push no commits", ^{ + GTBranch *masterBranch = localBranchWithName(@"master", localRepo); + expect(@([masterBranch numberOfCommitsWithError:NULL])).to(equal(@3)); + + GTBranch *remoteMasterBranch = localBranchWithName(@"master", remoteRepo); + expect(@([remoteMasterBranch numberOfCommitsWithError:NULL])).to(equal(@3)); + + // Push + __block BOOL transferProgressed = NO; + BOOL result = [localRepo pushBranch:masterBranch toRemote:remote withOptions:nil error:&error progress:^(unsigned int current, unsigned int total, size_t bytes, BOOL *stop) { + transferProgressed = YES; + }]; + expect(error).to(beNil()); + expect(@(result)).to(beTruthy()); + expect(@(transferProgressed)).to(beTruthy()); + + // Same number of commits after push, refresh branch first + remoteMasterBranch = localBranchWithName(@"master", remoteRepo); + expect(@([remoteMasterBranch numberOfCommitsWithError:NULL])).to(equal(@3)); + }); + }); + + it(@"can push one commit", ^{ + // Create a new commit in the local repo + NSString *testData = @"Test"; + NSString *fileName = @"test.txt"; + GTCommit *testCommit = createCommitInRepository(@"Test commit", [testData dataUsingEncoding:NSUTF8StringEncoding], fileName, localRepo); + expect(testCommit).notTo(beNil()); + + // Refetch master branch to ensure the commit count is accurate + GTBranch *masterBranch = localBranchWithName(@"master", localRepo); + expect(@([masterBranch numberOfCommitsWithError:NULL])).to(equal(@4)); + + // Number of commits on tracking branch before push + BOOL success = NO; + GTBranch *localTrackingBranch = [masterBranch trackingBranchWithError:&error success:&success]; + expect(error).to(beNil()); + expect(@(success)).to(beTruthy()); + expect(@([localTrackingBranch numberOfCommitsWithError:NULL])).to(equal(@3)); + + // Number of commits on remote before push + GTBranch *remoteMasterBranch = localBranchWithName(@"master", remoteRepo); + expect(@([remoteMasterBranch numberOfCommitsWithError:NULL])).to(equal(@3)); + + // Push + __block BOOL transferProgressed = NO; + BOOL result = [localRepo pushBranch:masterBranch toRemote:remote withOptions:nil error:&error progress:^(unsigned int current, unsigned int total, size_t bytes, BOOL *stop) { + transferProgressed = YES; + }]; + expect(error).to(beNil()); + expect(@(result)).to(beTruthy()); + expect(@(transferProgressed)).to(beTruthy()); + + // Number of commits on tracking branch after push + localTrackingBranch = [masterBranch trackingBranchWithError:&error success:&success]; + expect(error).to(beNil()); + expect(@(success)).to(beTruthy()); + expect(@([localTrackingBranch numberOfCommitsWithError:NULL])).to(equal(@4)); + + // Refresh remote master branch to ensure the commit count is accurate + remoteMasterBranch = localBranchWithName(@"master", remoteRepo); + + // Number of commits in remote repo after push + expect(@([remoteMasterBranch numberOfCommitsWithError:NULL])).to(equal(@4)); + + // Verify commit is in remote + GTCommit *pushedCommit = [remoteRepo lookUpObjectByOID:testCommit.OID objectType:GTObjectTypeCommit error:&error]; + expect(error).to(beNil()); + expect(pushedCommit).notTo(beNil()); + expect(pushedCommit.OID).to(equal(testCommit.OID)); + + GTTreeEntry *entry = [[pushedCommit tree] entryWithName:fileName]; + expect(entry).notTo(beNil()); + + GTBlob *fileData = (GTBlob *)[entry GTObject:&error]; + expect(error).to(beNil()); + expect(fileData).notTo(beNil()); + expect(fileData.content).to(equal(testData)); + }); + + it(@"can push two branches", ^{ + // refs/heads/master on local + GTBranch *branch1 = localBranchWithName(@"master", localRepo); + + // Create refs/heads/new_master on local + [localRepo createReferenceNamed:@"refs/heads/new_master" fromReference:branch1.reference message:@"Create new_master branch" error:&error]; + GTBranch *branch2 = localBranchWithName(@"new_master", localRepo); + + BOOL result = [localRepo pushBranches:@[ branch1, branch2 ] toRemote:remote withOptions:nil error:&error progress:NULL]; + expect(error).to(beNil()); + expect(@(result)).to(beTruthy()); + }); + }); + +}); + +QuickSpecEnd diff --git a/ObjectiveGitTests/GTRemoteSpec.m b/ObjectiveGitTests/GTRemoteSpec.m index 02c1ce432..e7ac77891 100644 --- a/ObjectiveGitTests/GTRemoteSpec.m +++ b/ObjectiveGitTests/GTRemoteSpec.m @@ -6,16 +6,18 @@ // Copyright (c) 2013 GitHub, Inc. All rights reserved. // -#import -#import -#import +@import ObjectiveGit; +@import Nimble; +@import Quick; #import "QuickSpec+GTFixtures.h" +#import "GTUtilityFunctions.h" QuickSpecBegin(GTRemoteSpec) __block GTRemote *remote = nil; __block GTRepository *repository = nil; +__block GTConfiguration *configuration = nil; NSString *fetchRefspec = @"+refs/heads/*:refs/remotes/origin/*"; beforeEach(^{ @@ -23,7 +25,7 @@ expect(repository).notTo(beNil()); NSError *error = nil; - GTConfiguration *configuration = [repository configurationWithError:&error]; + configuration = [repository configurationWithError:&error]; expect(configuration).notTo(beNil()); expect(error).to(beNil()); @@ -53,9 +55,27 @@ expect(@([remote updateURLString:newURLString error:&error])).to(beTruthy()); expect(error).to(beNil()); + // Reload remote from disk to pick up the change + remote = configuration.remotes[0]; + expect(remote.URLString).to(equal(newURLString)); }); + it(@"push URL string", ^{ + expect(remote.pushURLString).to(beNil()); + + NSString *newURLString = @"https://github.com/github/Test_App.git"; + + __block NSError *error = nil; + expect(@([remote updatePushURLString:newURLString error:&error])).to(beTruthy()); + expect(error).to(beNil()); + + // Reload remote from disk to pick up the change + remote = configuration.remotes[0]; + + expect(remote.pushURLString).to(equal(newURLString)); + }); + it(@"fetch refspecs", ^{ expect(remote.fetchRefspecs).to(equal(@[ fetchRefspec ])); @@ -65,6 +85,9 @@ expect(@([remote addFetchRefspec:newFetchRefspec error:&error])).to(beTruthy()); expect(error).to(beNil()); + // Reload remote from disk to pick up the change + remote = configuration.remotes[0]; + expect(remote.fetchRefspecs).to(equal((@[ fetchRefspec, newFetchRefspec ]))); }); }); @@ -84,7 +107,7 @@ fetchingRepoURL = [fixturesURL URLByAppendingPathComponent:@"fetchrepo"]; NSError *error = nil; - fetchingRepo = [GTRepository cloneFromURL:repositoryURL toWorkingDirectory:fetchingRepoURL options:nil error:&error transferProgressBlock:nil checkoutProgressBlock:nil]; + fetchingRepo = [GTRepository cloneFromURL:repositoryURL toWorkingDirectory:fetchingRepoURL options:nil error:&error transferProgressBlock:nil]; expect(fetchingRepo).notTo(beNil()); expect(error).to(beNil()); @@ -133,26 +156,6 @@ }); }); - // Helper to quickly create commits - GTCommit *(^createCommitInRepository)(NSString *, NSData *, NSString *, GTRepository *) = ^(NSString *message, NSData *fileData, NSString *fileName, GTRepository *repo) { - GTTreeBuilder *treeBuilder = [[GTTreeBuilder alloc] initWithTree:nil error:nil]; - [treeBuilder addEntryWithData:fileData fileName:fileName fileMode:GTFileModeBlob error:nil]; - - GTTree *testTree = [treeBuilder writeTreeToRepository:repo error:nil]; - - // We need the parent commit to make the new one - GTReference *headReference = [repo headReferenceWithError:nil]; - - GTEnumerator *commitEnum = [[GTEnumerator alloc] initWithRepository:repo error:nil]; - [commitEnum pushSHA:[headReference targetSHA] error:nil]; - GTCommit *parent = [commitEnum nextObject]; - - GTCommit *testCommit = [repo createCommitWithTree:testTree message:message parents:@[parent] updatingReferenceNamed:headReference.name error:nil]; - expect(testCommit).notTo(beNil()); - - return testCommit; - }; - describe(@"-[GTRepository fetchRemote:withOptions:error:progress:]", ^{ it(@"allows remotes to be fetched", ^{ NSError *error = nil; @@ -184,7 +187,7 @@ expect(error).to(beNil()); expect(@(success)).to(beTruthy()); expect(@(transferProgressed)).to(beTruthy()); - expect(@(receivedObjects)).to(equal(@10)); + expect(@(receivedObjects)).to(beGreaterThan(@0)); GTCommit *fetchedCommit = [fetchingRepo lookUpObjectByOID:testCommit.OID objectType:GTObjectTypeCommit error:&error]; expect(error).to(beNil()); diff --git a/ObjectiveGitTests/GTRepository+PullSpec.m b/ObjectiveGitTests/GTRepository+PullSpec.m new file mode 100644 index 000000000..3c36ebde6 --- /dev/null +++ b/ObjectiveGitTests/GTRepository+PullSpec.m @@ -0,0 +1,272 @@ +// +// GTRepository+PullSpec.m +// ObjectiveGitFramework +// +// Created by Ben Chatelain on 6/28/15. +// Copyright (c) 2015 GitHub, Inc. All rights reserved. +// + +@import ObjectiveGit; +@import Nimble; +@import Quick; + +#import "QuickSpec+GTFixtures.h" +#import "GTUtilityFunctions.h" + +#pragma mark - GTRepository+PullSpec + +QuickSpecBegin(GTRepositoryPullSpec) + +describe(@"pull", ^{ + __block GTRepository *notBareRepo; + + beforeEach(^{ + notBareRepo = self.bareFixtureRepository; + expect(notBareRepo).notTo(beNil()); + // This repo is not really "bare" according to libgit2 + expect(@(notBareRepo.isBare)).to(beFalsy()); + }); + + describe(@"from remote", ^{ // via local transport + __block NSURL *remoteRepoURL; + __block NSURL *localRepoURL; + __block GTRepository *remoteRepo; + __block GTRepository *localRepo; + __block GTRemote *remote; + __block NSError *error; + + beforeEach(^{ + // Make a bare clone to serve as the remote + remoteRepoURL = [notBareRepo.gitDirectoryURL.URLByDeletingLastPathComponent URLByAppendingPathComponent:@"bare_remote_repo.git"]; + NSDictionary *options = @{ GTRepositoryCloneOptionsBare: @1 }; + remoteRepo = [GTRepository cloneFromURL:notBareRepo.gitDirectoryURL toWorkingDirectory:remoteRepoURL options:options error:&error transferProgressBlock:NULL]; + expect(error).to(beNil()); + expect(remoteRepo).notTo(beNil()); + expect(@(remoteRepo.isBare)).to(beTruthy()); // that's better + + localRepoURL = [remoteRepoURL.URLByDeletingLastPathComponent URLByAppendingPathComponent:@"local_pull_repo"]; + expect(localRepoURL).notTo(beNil()); + + // Local clone for testing pushes + localRepo = [GTRepository cloneFromURL:remoteRepoURL toWorkingDirectory:localRepoURL options:nil error:&error transferProgressBlock:NULL]; + + expect(error).to(beNil()); + expect(localRepo).notTo(beNil()); + + GTConfiguration *configuration = [localRepo configurationWithError:&error]; + expect(error).to(beNil()); + expect(configuration).notTo(beNil()); + + expect(@(configuration.remotes.count)).to(equal(@1)); + + remote = configuration.remotes[0]; + expect(remote.name).to(equal(@"origin")); + }); + + afterEach(^{ + [NSFileManager.defaultManager removeItemAtURL:remoteRepoURL error:NULL]; + [NSFileManager.defaultManager removeItemAtURL:localRepoURL error:NULL]; + error = NULL; + }); + + context(@"when the local and remote branches are in sync", ^{ + it(@"should pull no commits", ^{ + GTBranch *masterBranch = localBranchWithName(@"master", localRepo); + expect(@([masterBranch numberOfCommitsWithError:NULL])).to(equal(@3)); + + GTBranch *remoteMasterBranch = localBranchWithName(@"master", remoteRepo); + expect(@([remoteMasterBranch numberOfCommitsWithError:NULL])).to(equal(@3)); + + // Pull + __block BOOL transferProgressed = NO; + BOOL result = [localRepo pullBranch:masterBranch fromRemote:remote withOptions:nil error:&error progress:^(const git_transfer_progress *progress, BOOL *stop) { + transferProgressed = YES; + }]; + expect(error).to(beNil()); + expect(@(result)).to(beTruthy()); + expect(@(transferProgressed)).to(beFalsy()); // Local transport doesn't currently call progress callbacks + + // Same number of commits after pull, refresh branch from disk first + remoteMasterBranch = localBranchWithName(@"master", remoteRepo); + expect(@([remoteMasterBranch numberOfCommitsWithError:NULL])).to(equal(@3)); + }); + }); + +/* pending tests break build on travis + /// Unborn + /// Can't get a GTBranch reference wrapping HEAD when its symref is unborn + pending(@"into an empty repo", ^{ + // Create an empty local repo + localRepoURL = [remoteRepoURL.URLByDeletingLastPathComponent URLByAppendingPathComponent:@"empty_pull_repo"]; + NSLog(@"localRepoURL: %@", localRepoURL); + NSDictionary *options = @{ GTRepositoryInitOptionsOriginURLString: [remoteRepoURL absoluteString] }; + localRepo = [GTRepository initializeEmptyRepositoryAtFileURL:localRepoURL options:options error:&error]; + expect(localRepo).toNot(beNil()); + expect(error).to(beNil()); + + // Verify unborn + expect(@(localRepo.isHEADUnborn)).to(beTruthy()); + + // Configure tracking + GTConfiguration *configuration = [localRepo configurationWithError:&error]; + expect(configuration).toNot(beNil()); + expect(error).to(beNil()); + [configuration setString:@"origin" forKey:@"branch.master.remote"]; + [configuration setString:@"refs/heads/master" forKey:@"branch.master.merge"]; + + GTReference *head = [localRepo headReferenceWithError:&error]; + expect(head).toNot(beNil()); + expect(error).to(beNil()); + +// GTBranch *masterBranch = localBranchWithName(@"master", localRepo); + GTBranch *masterBranch = [localRepo currentBranchWithError:&error]; + expect(masterBranch).toNot(beNil()); + + // Pull + __block BOOL transferProgressed = NO; + BOOL result = [localRepo pullBranch:masterBranch fromRemote:remote withOptions:nil error:&error progress:^(const git_transfer_progress *progress, BOOL *stop) { + transferProgressed = YES; + }]; + expect(@(result)).to(beTruthy()); + expect(error).to(beNil()); + expect(@(transferProgressed)).to(beFalsy()); // Local transport doesn't currently call progress callbacks + +// GTReference *head = [localRepo headReferenceWithError:&error]; +// expect(head).toNot(beNil()); + + }); +*/ + + /// Fast-Forward Merge + /// + /// Stages a pull by modifying a clone, resetting it back in history + /// then using pull to bring the repos back in sync. + it(@"fast-forwards one commit", ^{ + GTBranch *masterBranch = localBranchWithName(@"master", localRepo); + expect(@([masterBranch numberOfCommitsWithError:NULL])).to(equal(@3)); + + // Reset local master back one commit + GTCommit *commit = [localRepo lookUpObjectByRevParse:@"HEAD^" error:&error]; + BOOL success = [localRepo resetToCommit:commit resetType:GTRepositoryResetTypeHard error:&error]; + expect(@(success)).to(beTruthy()); + expect(error).to(beNil()); + + // Verify rollback, must refresh branch from disk + masterBranch = localBranchWithName(@"master", localRepo); + expect(@([masterBranch numberOfCommitsWithError:NULL])).to(equal(@2)); + + // HEADs point to different objects + expect([[localRepo headReferenceWithError:NULL] OID]) + .toNot(equal([[remoteRepo headReferenceWithError:NULL] OID])); + + // Remote has 3 commits + GTBranch *remoteMasterBranch = localBranchWithName(@"master", remoteRepo); + expect(@([remoteMasterBranch numberOfCommitsWithError:NULL])).to(equal(@3)); + + // Pull + __block BOOL transferProgressed = NO; + BOOL result = [localRepo pullBranch:masterBranch fromRemote:remote withOptions:nil error:&error progress:^(const git_transfer_progress *progress, BOOL *stop) { + transferProgressed = YES; + }]; + expect(error).to(beNil()); + expect(@(result)).to(beTruthy()); + expect(@(transferProgressed)).to(beFalsy()); // Local transport doesn't currently call progress callbacks + + // Verify same number of commits after pull, refresh branch from disk first + masterBranch = localBranchWithName(@"master", localRepo); + expect(@([masterBranch numberOfCommitsWithError:NULL])).to(equal(@3)); + + // Verify HEADs are in sync + expect([[localRepo headReferenceWithError:NULL] OID]) + .to(equal([[remoteRepo headReferenceWithError:NULL] OID])); + }); + + /// Normal Merge + it(@"merges the upstream changes", ^{ + // 3 commits + GTBranch *masterBranch = localBranchWithName(@"master", localRepo); + expect(@([masterBranch numberOfCommitsWithError:NULL])).to(equal(@3)); + + // Create a new commit in the local repo + GTCommit *localCommit = createCommitInRepository(@"Local commit", [@"Test" dataUsingEncoding:NSUTF8StringEncoding], @"test.txt", localRepo); + expect(localCommit).notTo(beNil()); + + // 4 commits + masterBranch = localBranchWithName(@"master", localRepo); + expect(@([masterBranch numberOfCommitsWithError:NULL])).to(equal(@4)); + + localCommit = [localRepo lookUpObjectByOID:localCommit.OID objectType:GTObjectTypeCommit error:&error]; + expect(localCommit).notTo(beNil()); + expect(error).to(beNil()); + + // Create a new commit in the remote repo + GTCommit *upstreamCommit = createCommitInRepository(@"Upstream commit", [@"# So Fancy" dataUsingEncoding:NSUTF8StringEncoding], @"fancy.md", remoteRepo); + expect(upstreamCommit).notTo(beNil()); + + masterBranch = localBranchWithName(@"master", localRepo); + + // Validate there is one unique local commit before merge + BOOL success = NO; + GTBranch *remoteTrackingBranch = [masterBranch trackingBranchWithError:&error success:&success]; + expect(@(success)).to(beTrue()); + expect(error).to(beNil()); + expect(remoteTrackingBranch).toNot(beNil()); + + NSArray *uniqueLocalCommits = [localRepo localCommitsRelativeToRemoteBranch:remoteTrackingBranch error:&error]; + expect(uniqueLocalCommits).toNot(beNil()); + expect(error).to(beNil()); + expect(@(uniqueLocalCommits.count)).to(equal(@1)); + + // Pull + __block BOOL transferProgressed = NO; + BOOL result = [localRepo pullBranch:masterBranch fromRemote:remote withOptions:nil error:&error progress:^(const git_transfer_progress *progress, BOOL *stop) { + transferProgressed = YES; + }]; + expect(@(result)).to(beTruthy()); + expect(error).to(beNil()); + expect(@(transferProgressed)).to(beTruthy()); + + // Validate + + // 5 commits + masterBranch = localBranchWithName(@"master", localRepo); + expect(@([masterBranch numberOfCommitsWithError:NULL])).to(equal(@6)); + + // We should have have an additional merge commit after the pull + uniqueLocalCommits = [localRepo localCommitsRelativeToRemoteBranch:remoteTrackingBranch error:&error]; + expect(uniqueLocalCommits).toNot(beNil()); + expect(error).to(beNil()); + expect(@(uniqueLocalCommits.count)).to(equal(@3)); + }); + + /// Conflict During Merge + it(@"fails to merge when there is a conflict", ^{ + // Stage a conflict by adding the same file with different contents to both repos + GTCommit *localCommit = createCommitInRepository(@"Local commit", [@"TestLocal" dataUsingEncoding:NSUTF8StringEncoding], @"test.txt", localRepo); + expect(localCommit).notTo(beNil()); + GTCommit *remoteCommit = createCommitInRepository(@"Upstream commit", [@"TestUpstream" dataUsingEncoding:NSUTF8StringEncoding], @"test.txt", remoteRepo); + expect(remoteCommit).notTo(beNil()); + + GTBranch *masterBranch = localBranchWithName(@"master", localRepo); + + // Pull + __block BOOL transferProgressed = NO; + BOOL result = [localRepo pullBranch:masterBranch fromRemote:remote withOptions:nil error:&error progress:^(const git_transfer_progress *progress, BOOL *stop) { + transferProgressed = YES; + }]; + NSString *fileContents = [NSString stringWithContentsOfURL:[localRepo.fileURL URLByAppendingPathComponent:@"test.txt"] encoding:NSUTF8StringEncoding error:nil]; + expect(@(result)).to(beFalsy()); + expect(error.domain).to(equal(@"GTGitErrorDomain")); + expect(error.userInfo[GTPullMergeConflictedFiles]).to(equal(@[@"test.txt"])); + expect(fileContents).notTo(equal(@"TestLocal")); + expect([localRepo mergeHeadEntriesWithError:nil]).to(equal(@[remoteCommit.OID])); + expect([localRepo preparedMessageWithError:nil]).to(beginWith(@"Merge commit")); + expect(error.localizedDescription).to(equal(@"Merge conflict")); + expect(@(transferProgressed)).to(beTruthy()); + }); + + }); + +}); + +QuickSpecEnd diff --git a/ObjectiveGitTests/GTRepository+StatusSpec.m b/ObjectiveGitTests/GTRepository+StatusSpec.m index de7a95312..c2ceaa9cb 100644 --- a/ObjectiveGitTests/GTRepository+StatusSpec.m +++ b/ObjectiveGitTests/GTRepository+StatusSpec.m @@ -6,9 +6,9 @@ // Copyright (c) 2013 GitHub, Inc. All rights reserved. // -#import -#import -#import +@import ObjectiveGit; +@import Nimble; +@import Quick; #import "QuickSpec+GTFixtures.h" @@ -27,7 +27,7 @@ expect(repository).notTo(beNil()); }); - void (^updateIndexForSubpathAndExpectStatus)(NSString *, GTStatusDeltaStatus) = ^(NSString *subpath, GTStatusDeltaStatus expectedIndexStatus) { + void (^updateIndexForSubpathAndExpectStatus)(NSString *, GTDeltaType) = ^(NSString *subpath, GTDeltaType expectedIndexStatus) { __block NSError *err = nil; GTIndex *index = [repository indexWithError:&err]; expect(err).to(beNil()); @@ -42,7 +42,7 @@ expect(err).to(beNil()); }; - void (^expectSubpathToHaveWorkDirStatus)(NSString *, GTStatusDeltaStatus) = ^(NSString *subpath, GTStatusDeltaStatus expectedWorkDirStatus) { + void (^expectSubpathToHaveWorkDirStatus)(NSString *, GTDeltaType) = ^(NSString *subpath, GTDeltaType expectedWorkDirStatus) { __block NSError *err = nil; NSDictionary *renamedOptions = @{ GTRepositoryStatusOptionsFlagsKey: @(GTRepositoryStatusFlagsIncludeIgnored | GTRepositoryStatusFlagsIncludeUntracked | GTRepositoryStatusFlagsRecurseUntrackedDirectories | GTRepositoryStatusFlagsRenamesIndexToWorkingDirectory) }; expect(@([repository enumerateFileStatusWithOptions:renamedOptions error:&err usingBlock:^(GTStatusDelta *headToIndex, GTStatusDelta *indexToWorkingDirectory, BOOL *stop) { @@ -52,59 +52,77 @@ expect(err).to(beNil()); }; - void (^expectSubpathToHaveMatchingStatus)(NSString *, GTStatusDeltaStatus) = ^(NSString *subpath, GTStatusDeltaStatus status) { + void (^expectSubpathToHaveMatchingStatus)(NSString *, GTDeltaType) = ^(NSString *subpath, GTDeltaType status) { expectSubpathToHaveWorkDirStatus(subpath, status); updateIndexForSubpathAndExpectStatus(subpath, status); }; it(@"should recognize untracked files", ^{ - expectSubpathToHaveWorkDirStatus(@"UntrackedImage.png", GTStatusDeltaStatusUntracked); + expectSubpathToHaveWorkDirStatus(@"UntrackedImage.png", GTDeltaTypeUntracked); }); it(@"should recognize added files", ^{ - updateIndexForSubpathAndExpectStatus(@"UntrackedImage.png", GTStatusDeltaStatusAdded); + updateIndexForSubpathAndExpectStatus(@"UntrackedImage.png", GTDeltaTypeAdded); }); it(@"should recognize modified files", ^{ expect(@([NSFileManager.defaultManager removeItemAtURL:targetFileURL error:&err])).to(beTruthy()); expect(err).to(beNil()); expect(@([testData writeToURL:targetFileURL atomically:YES])).to(beTruthy()); - expectSubpathToHaveMatchingStatus(targetFileURL.lastPathComponent, GTStatusDeltaStatusModified); + expectSubpathToHaveMatchingStatus(targetFileURL.lastPathComponent, GTDeltaTypeModified); }); it(@"should recognize copied files", ^{ NSURL *copyLocation = [repository.fileURL URLByAppendingPathComponent:@"main2.m"]; expect(@([NSFileManager.defaultManager copyItemAtURL:targetFileURL toURL:copyLocation error:&err])).to(beTruthy()); expect(err).to(beNil()); - updateIndexForSubpathAndExpectStatus(copyLocation.lastPathComponent, GTStatusDeltaStatusCopied); + updateIndexForSubpathAndExpectStatus(copyLocation.lastPathComponent, GTDeltaTypeCopied); }); it(@"should recognize deleted files", ^{ expect(@([NSFileManager.defaultManager removeItemAtURL:targetFileURL error:&err])).to(beTruthy()); expect(err).to(beNil()); - expectSubpathToHaveMatchingStatus(targetFileURL.lastPathComponent, GTStatusDeltaStatusDeleted); + expectSubpathToHaveMatchingStatus(targetFileURL.lastPathComponent, GTDeltaTypeDeleted); }); it(@"should recognize renamed files", ^{ NSURL *moveLocation = [repository.fileURL URLByAppendingPathComponent:@"main-moved.m"]; expect(@([NSFileManager.defaultManager moveItemAtURL:targetFileURL toURL:moveLocation error:&err])).to(beTruthy()); expect(err).to(beNil()); - expectSubpathToHaveWorkDirStatus(moveLocation.lastPathComponent, GTStatusDeltaStatusRenamed); + expectSubpathToHaveWorkDirStatus(moveLocation.lastPathComponent, GTDeltaTypeRenamed); }); it(@"should recognise ignored files", ^{ //at least in the default options - expectSubpathToHaveWorkDirStatus(@".DS_Store", GTStatusDeltaStatusIgnored); + expectSubpathToHaveWorkDirStatus(@".DS_Store", GTDeltaTypeIgnored); }); it(@"should skip ignored files if asked", ^{ __block NSError *err = nil; NSDictionary *options = @{ GTRepositoryStatusOptionsFlagsKey: @(0) }; BOOL enumerationSuccessful = [repository enumerateFileStatusWithOptions:options error:&err usingBlock:^(GTStatusDelta *headToIndex, GTStatusDelta *indexToWorkingDirectory, BOOL *stop) { - expect(@(indexToWorkingDirectory.status)).notTo(equal(@(GTStatusDeltaStatusIgnored))); + expect(@(indexToWorkingDirectory.status)).notTo(equal(@(GTDeltaTypeIgnored))); }]; expect(@(enumerationSuccessful)).to(beTruthy()); expect(err).to(beNil()); }); + + it(@"should report file should be ignored", ^{ + __block NSError *err = nil; + NSURL *fileURL = [repository.fileURL URLByAppendingPathComponent:@".DS_Store"]; + BOOL success = NO; + BOOL shouldIgnore = [repository shouldFileBeIgnored:fileURL success:&success error:&err]; + expect(@(success)).to(beTrue()); + expect(@(shouldIgnore)).to(beTrue()); + expect(err).to(beNil()); + }); + + it(@"should report file should be ignored (convenience wrapper)", ^{ + __block NSError *err = nil; + NSURL *fileURL = [repository.fileURL URLByAppendingPathComponent:@".DS_Store"]; + GTFileIgnoreState ignore = [repository shouldIgnoreFileURL:fileURL error:&err]; + expect(@(ignore)).to(equal(@(GTFileIgnoreStateShouldIgnore))); + expect(err).to(beNil()); + }); }); afterEach(^{ diff --git a/ObjectiveGitTests/GTRepositoryAttributesSpec.m b/ObjectiveGitTests/GTRepositoryAttributesSpec.m index 5e4ed7465..e60737eb0 100644 --- a/ObjectiveGitTests/GTRepositoryAttributesSpec.m +++ b/ObjectiveGitTests/GTRepositoryAttributesSpec.m @@ -6,9 +6,9 @@ // Copyright (c) 2014 GitHub, Inc. All rights reserved. // -#import -#import -#import +@import ObjectiveGit; +@import Nimble; +@import Quick; #import "QuickSpec+GTFixtures.h" diff --git a/ObjectiveGitTests/GTRepositoryCommittingSpec.m b/ObjectiveGitTests/GTRepositoryCommittingSpec.m index b0ced82b4..8e0ffa3f8 100644 --- a/ObjectiveGitTests/GTRepositoryCommittingSpec.m +++ b/ObjectiveGitTests/GTRepositoryCommittingSpec.m @@ -6,9 +6,9 @@ // Copyright (c) 2013 GitHub, Inc. All rights reserved. // -#import -#import -#import +@import ObjectiveGit; +@import Nimble; +@import Quick; #import "QuickSpec+GTFixtures.h" @@ -27,13 +27,13 @@ }); it(@"can create commits", ^{ - GTTreeBuilder *builder = [[GTTreeBuilder alloc] initWithTree:nil error:NULL]; + GTTreeBuilder *builder = [[GTTreeBuilder alloc] initWithTree:nil repository:repository error:NULL]; expect(builder).notTo(beNil()); GTTreeEntry *entry = [builder addEntryWithData:[@"Another file contents" dataUsingEncoding:NSUTF8StringEncoding] fileName:@"Test file 2.txt" fileMode:GTFileModeBlob error:NULL]; expect(entry).notTo(beNil()); - GTTree *subtree = [builder writeTreeToRepository:repository error:NULL]; + GTTree *subtree = [builder writeTree:NULL]; expect(subtree).notTo(beNil()); [builder clear]; @@ -44,7 +44,7 @@ entry = [builder addEntryWithOID:subtree.OID fileName:@"subdir" fileMode:GTFileModeTree error:NULL]; expect(entry).notTo(beNil()); - GTTree *tree = [builder writeTreeToRepository:repository error:NULL]; + GTTree *tree = [builder writeTree:NULL]; expect(tree).notTo(beNil()); GTCommit *initialCommit = [repository createCommitWithTree:tree message:@"Initial commit" parents:nil updatingReferenceNamed:@"refs/heads/master" error:NULL]; diff --git a/ObjectiveGitTests/GTRepositoryResetSpec.m b/ObjectiveGitTests/GTRepositoryResetSpec.m index 976437b28..eab048715 100644 --- a/ObjectiveGitTests/GTRepositoryResetSpec.m +++ b/ObjectiveGitTests/GTRepositoryResetSpec.m @@ -6,9 +6,9 @@ // Copyright (c) 2014 GitHub, Inc. All rights reserved. // -#import -#import -#import +@import ObjectiveGit; +@import Nimble; +@import Quick; #import "QuickSpec+GTFixtures.h" @@ -25,7 +25,7 @@ countStagedFiles = ^{ __block NSUInteger count = 0; [repository enumerateFileStatusWithOptions:nil error:NULL usingBlock:^(GTStatusDelta *headToIndex, GTStatusDelta *indexToWorkingDirectory, BOOL *stop) { - if (headToIndex.status != GTStatusDeltaStatusUnmodified) count++; + if (headToIndex.status != GTDeltaTypeUnmodified) count++; }]; return count; @@ -68,7 +68,7 @@ GTCommit *commit = [repository lookUpObjectBySHA:resetTargetSHA error:NULL]; expect(commit).notTo(beNil()); - GTCommit *originalHeadCommit = [repository lookUpObjectBySHA:originalHead.targetSHA error:NULL]; + GTCommit *originalHeadCommit = [repository lookUpObjectByOID:originalHead.targetOID error:NULL]; expect(originalHeadCommit).notTo(beNil()); BOOL success = [repository resetToCommit:commit resetType:GTRepositoryResetTypeSoft error:&error]; @@ -77,14 +77,14 @@ GTReference *head = [repository headReferenceWithError:&error]; expect(head).notTo(beNil()); - expect(head.targetSHA).to(equal(resetTargetSHA)); + expect(head.targetOID.SHA).to(equal(resetTargetSHA)); success = [repository resetToCommit:originalHeadCommit resetType:GTRepositoryResetTypeSoft error:&error]; expect(@(success)).to(beTruthy()); expect(error).to(beNil()); head = [repository headReferenceWithError:&error]; - expect(head.targetSHA).to(equal(originalHead.targetSHA)); + expect(head.targetOID).to(equal(originalHead.targetOID)); }); }); diff --git a/ObjectiveGitTests/GTRepositorySpec.m b/ObjectiveGitTests/GTRepositorySpec.m index 82e629c17..2ff1aaf88 100644 --- a/ObjectiveGitTests/GTRepositorySpec.m +++ b/ObjectiveGitTests/GTRepositorySpec.m @@ -6,14 +6,18 @@ // Copyright (c) 2013 GitHub, Inc. All rights reserved. // -#import -#import -#import +@import ObjectiveGit; +@import Nimble; +@import Quick; #import "QuickSpec+GTFixtures.h" QuickSpecBegin(GTRepositorySpec) +static NSString * const readmeFile = @"README.md"; +static NSString * const readme1File = @"README1.txt"; + + __block GTRepository *repository; beforeEach(^{ @@ -64,7 +68,7 @@ describe(@"+cloneFromURL:toWorkingDirectory:options:error:transferProgressBlock:checkoutProgressBlock:", ^{ __block BOOL transferProgressCalled = NO; __block BOOL checkoutProgressCalled = NO; - __block void (^transferProgressBlock)(const git_transfer_progress *); + __block void (^transferProgressBlock)(const git_transfer_progress *, BOOL *); __block void (^checkoutProgressBlock)(NSString *, NSUInteger, NSUInteger); __block NSURL *originURL; __block NSURL *workdirURL; @@ -74,7 +78,7 @@ beforeEach(^{ transferProgressCalled = NO; checkoutProgressCalled = NO; - transferProgressBlock = ^(const git_transfer_progress *progress) { + transferProgressBlock = ^(const git_transfer_progress *progress, BOOL *stop) { transferProgressCalled = YES; }; checkoutProgressBlock = ^(NSString *path, NSUInteger completedSteps, NSUInteger totalSteps) { @@ -91,7 +95,14 @@ it(@"should handle normal clones", ^{ NSError *error = nil; - repository = [GTRepository cloneFromURL:originURL toWorkingDirectory:workdirURL options:@{ GTRepositoryCloneOptionsCloneLocal: @YES } error:&error transferProgressBlock:transferProgressBlock checkoutProgressBlock:checkoutProgressBlock]; + GTCheckoutOptions *checkoutOptions = [GTCheckoutOptions checkoutOptionsWithStrategy:GTCheckoutStrategySafe]; + checkoutOptions.progressBlock = checkoutProgressBlock; + + NSDictionary *cloneOptions = @{ + GTRepositoryCloneOptionsCloneLocal: @YES, + GTRepositoryCloneOptionsCheckoutOptions: checkoutOptions, + }; + repository = [GTRepository cloneFromURL:originURL toWorkingDirectory:workdirURL options:cloneOptions error:&error transferProgressBlock:transferProgressBlock]; expect(repository).notTo(beNil()); expect(error).to(beNil()); expect(@(transferProgressCalled)).to(beTruthy()); @@ -102,14 +113,21 @@ GTReference *head = [repository headReferenceWithError:&error]; expect(head).notTo(beNil()); expect(error).to(beNil()); - expect(head.targetSHA).to(equal(@"36060c58702ed4c2a40832c51758d5344201d89a")); - expect(@(head.referenceType)).to(equal(@(GTReferenceTypeOid))); + expect(head.targetOID.SHA).to(equal(@"36060c58702ed4c2a40832c51758d5344201d89a")); + expect(@(head.referenceType)).to(equal(@(GTReferenceTypeDirect))); }); it(@"should handle bare clones", ^{ NSError *error = nil; - NSDictionary *options = @{ GTRepositoryCloneOptionsBare: @YES, GTRepositoryCloneOptionsCloneLocal: @YES }; - repository = [GTRepository cloneFromURL:originURL toWorkingDirectory:workdirURL options:options error:&error transferProgressBlock:transferProgressBlock checkoutProgressBlock:checkoutProgressBlock]; + GTCheckoutOptions *checkoutOptions = [GTCheckoutOptions checkoutOptionsWithStrategy:GTCheckoutStrategySafe]; + checkoutOptions.progressBlock = checkoutProgressBlock; + + NSDictionary *options = @{ + GTRepositoryCloneOptionsBare: @YES, + GTRepositoryCloneOptionsCloneLocal: @YES, + GTRepositoryCloneOptionsCheckoutOptions: checkoutOptions, + }; + repository = [GTRepository cloneFromURL:originURL toWorkingDirectory:workdirURL options:options error:&error transferProgressBlock:transferProgressBlock]; expect(repository).notTo(beNil()); expect(error).to(beNil()); expect(@(transferProgressCalled)).to(beTruthy()); @@ -120,13 +138,16 @@ GTReference *head = [repository headReferenceWithError:&error]; expect(head).notTo(beNil()); expect(error).to(beNil()); - expect(head.targetSHA).to(equal(@"36060c58702ed4c2a40832c51758d5344201d89a")); - expect(@(head.referenceType)).to(equal(@(GTReferenceTypeOid))); + expect(head.targetOID.SHA).to(equal(@"36060c58702ed4c2a40832c51758d5344201d89a")); + expect(@(head.referenceType)).to(equal(@(GTReferenceTypeDirect))); }); it(@"should have set a valid remote URL", ^{ NSError *error = nil; - repository = [GTRepository cloneFromURL:originURL toWorkingDirectory:workdirURL options:nil error:&error transferProgressBlock:transferProgressBlock checkoutProgressBlock:checkoutProgressBlock]; + GTCheckoutOptions *checkoutOptions = [GTCheckoutOptions checkoutOptionsWithStrategy:GTCheckoutStrategySafe]; + checkoutOptions.progressBlock = checkoutProgressBlock; + + repository = [GTRepository cloneFromURL:originURL toWorkingDirectory:workdirURL options:@{ GTRepositoryCloneOptionsCheckoutOptions: checkoutOptions } error:&error transferProgressBlock:transferProgressBlock]; expect(repository).notTo(beNil()); expect(error).to(beNil()); @@ -163,7 +184,14 @@ return cred; }]; - repository = [GTRepository cloneFromURL:originURL toWorkingDirectory:workdirURL options:@{GTRepositoryCloneOptionsCredentialProvider: provider} error:&error transferProgressBlock:transferProgressBlock checkoutProgressBlock:checkoutProgressBlock]; + GTCheckoutOptions *checkoutOptions = [GTCheckoutOptions checkoutOptionsWithStrategy:GTCheckoutStrategySafe]; + checkoutOptions.progressBlock = checkoutProgressBlock; + NSDictionary *cloneOptions = @{ + GTRepositoryCloneOptionsCredentialProvider: provider, + GTRepositoryCloneOptionsCheckoutOptions: checkoutOptions, + }; + + repository = [GTRepository cloneFromURL:originURL toWorkingDirectory:workdirURL options:cloneOptions error:&error transferProgressBlock:transferProgressBlock]; expect(repository).notTo(beNil()); expect(error).to(beNil()); expect(@(transferProgressCalled)).to(beTruthy()); @@ -183,8 +211,8 @@ GTReference *head = [self.bareFixtureRepository headReferenceWithError:&error]; expect(head).notTo(beNil()); expect(error).to(beNil()); - expect(head.targetSHA).to(equal(@"36060c58702ed4c2a40832c51758d5344201d89a")); - expect(@(head.referenceType)).to(equal(@(GTReferenceTypeOid))); + expect(head.targetOID.SHA).to(equal(@"36060c58702ed4c2a40832c51758d5344201d89a")); + expect(@(head.referenceType)).to(equal(@(GTReferenceTypeDirect))); }); it(@"should fail to return HEAD for an unborn repo", ^{ @@ -232,6 +260,48 @@ }); }); +describe(@"-contentsOfDiffWithAncestor:ourSide:theirSide:error:", ^{ + it(@"should produce a nice merge conflict description", ^{ + NSURL *mainURL = [repository.fileURL URLByAppendingPathComponent:@"main.m"]; + NSData *mainData = [[NSFileManager defaultManager] contentsAtPath:mainURL.path]; + expect(mainData).notTo(beNil()); + + NSString *mainString = [[NSString alloc] initWithData:mainData encoding:NSUTF8StringEncoding]; + NSData *masterData = [[mainString stringByReplacingOccurrencesOfString:@"return" withString:@"//The meaning of life is 41\n return"] dataUsingEncoding:NSUTF8StringEncoding]; + NSData *otherData = [[mainString stringByReplacingOccurrencesOfString:@"return" withString:@"//The meaning of life is 42\n return"] dataUsingEncoding:NSUTF8StringEncoding]; + + expect(@([[NSFileManager defaultManager] createFileAtPath:mainURL.path contents:masterData attributes:nil])).to(beTruthy()); + + GTIndex *index = [repository indexWithError:NULL]; + expect(@([index addFile:mainURL.lastPathComponent error:NULL])).to(beTruthy()); + GTReference *head = [repository headReferenceWithError:NULL]; + GTCommit *parent = [repository lookUpObjectByOID:head.targetOID objectType:GTObjectTypeCommit error:NULL]; + expect(parent).toNot(beNil()); + GTTree *masterTree = [index writeTree:NULL]; + expect(masterTree).toNot(beNil()); + + GTBranch *otherBranch = [repository lookUpBranchWithName:@"other-branch" type:GTBranchTypeLocal success:NULL error:NULL]; + expect(otherBranch).toNot(beNil()); + expect(@([repository checkoutReference:otherBranch.reference options:nil error:NULL])).to(beTruthy()); + + expect(@([[NSFileManager defaultManager] createFileAtPath:mainURL.path contents:otherData attributes:nil])).to(beTruthy()); + + index = [repository indexWithError:NULL]; + expect(@([index addFile:mainURL.lastPathComponent error:NULL])).to(beTruthy()); + GTTree *otherTree = [index writeTree:NULL]; + expect(otherTree).toNot(beNil()); + + GTIndex *conflictIndex = [otherTree merge:masterTree ancestor:parent.tree error:NULL]; + expect(@([conflictIndex hasConflicts])).to(beTruthy()); + + [conflictIndex enumerateConflictedFilesWithError:NULL usingBlock:^(GTIndexEntry * _Nonnull ancestor, GTIndexEntry * _Nonnull ours, GTIndexEntry * _Nonnull theirs, BOOL * _Nonnull stop) { + + NSString *conflictString = [repository contentsOfDiffWithAncestor:ancestor ourSide:ours theirSide:theirs error:NULL]; + expect(conflictString).to(equal(@"//\n// main.m\n// Test\n//\n// Created by Joe Ricioppo on 9/28/10.\n// Copyright 2010 __MyCompanyName__. All rights reserved.\n//\n\n#import \n\nint main(int argc, char *argv[])\n{\n<<<<<<< file.txt\n //The meaning of life is 42\n=======\n //The meaning of life is 41\n>>>>>>> file.txt\n return NSApplicationMain(argc, (const char **) argv);\n}\n123456789\n123456789\n123456789\n123456789!blah!\n")); + }]; + }); +}); + describe(@"-mergeBaseBetweenFirstOID:secondOID:error:", ^{ it(@"should find the merge base between two branches", ^{ NSError *error = nil; @@ -264,7 +334,7 @@ GTBranch *currentBranch = [repository currentBranchWithError:&error]; expect(currentBranch).notTo(beNil()); expect(error).to(beNil()); - expect(currentBranch.name).to(equal(@"refs/heads/master")); + expect(currentBranch.name).to(equal(@"master")); }); }); @@ -276,13 +346,13 @@ NSString *branchName = @"new-test-branch"; NSError *error = nil; - GTBranch *newBranch = [repository createBranchNamed:branchName fromOID:[[GTOID alloc] initWithSHA:currentBranch.SHA] committer:nil message:nil error:&error]; + GTBranch *newBranch = [repository createBranchNamed:branchName fromOID:currentBranch.OID message:nil error:&error]; expect(newBranch).notTo(beNil()); expect(error).to(beNil()); expect(newBranch.shortName).to(equal(branchName)); expect(@(newBranch.branchType)).to(equal(@(GTBranchTypeLocal))); - expect(newBranch.SHA).to(equal(currentBranch.SHA)); + expect(newBranch.OID).to(equal(currentBranch.OID)); }); }); @@ -304,7 +374,7 @@ expect(error).to(beNil()); expect(@(branches.count)).to(equal(@1)); GTBranch *remoteBranch = branches[0]; - expect(remoteBranch.name).to(equal(@"refs/remotes/origin/master")); + expect(remoteBranch.name).to(equal(@"origin/master")); }); }); @@ -354,13 +424,65 @@ }); }); +describe(@"move head", ^{ + beforeEach(^{ + repository = self.testAppFixtureRepository; + }); + + //- (BOOL)moveHEADToReference:(GTReference *)reference error:(NSError **)error; + it(@"should move to reference", ^{ + NSError *error = nil; + GTReference *originalHead = [repository headReferenceWithError:NULL]; + + GTReference *targetReference = [repository lookUpReferenceWithName:@"refs/heads/other-branch" error:NULL]; + expect(targetReference).notTo(beNil()); + + // -> Test the move + BOOL success = [repository moveHEADToReference:targetReference error:&error]; + expect(@(success)).to(beTruthy()); + expect(error).to(beNil()); + + // Verify + GTReference *head = [repository headReferenceWithError:&error]; + expect(head).notTo(beNil()); + expect(head).notTo(equal(originalHead)); + expect(head.targetOID.SHA).to(equal(targetReference.targetOID.SHA)); + }); + + //- (BOOL)moveHEADToCommit:(GTCommit *)commit error:(NSError **)error; + it(@"should move to commit", ^{ + NSError *error = nil; + GTReference *originalHead = [repository headReferenceWithError:NULL]; + NSString *targetCommitSHA = @"f7ecd8f4404d3a388efbff6711f1bdf28ffd16a0"; + + GTCommit *commit = [repository lookUpObjectBySHA:targetCommitSHA error:NULL]; + expect(commit).notTo(beNil()); + + GTCommit *originalHeadCommit = [repository lookUpObjectByOID:originalHead.targetOID error:NULL]; + expect(originalHeadCommit).notTo(beNil()); + + // -> Test the move + BOOL success = [repository moveHEADToCommit:commit error:&error]; + expect(@(success)).to(beTruthy()); + expect(error).to(beNil()); + + // Test for detached? + + // Verify + GTReference *head = [repository headReferenceWithError:&error]; + expect(head).notTo(beNil()); + expect(head.targetOID.SHA).to(equal(targetCommitSHA)); + }); +}); + + describe(@"-checkout:strategy:error:progressBlock:", ^{ it(@"should allow references", ^{ NSError *error = nil; - GTReference *ref = [GTReference referenceByLookingUpReferencedNamed:@"refs/heads/other-branch" inRepository:repository error:&error]; + GTReference *ref = [repository lookUpReferenceWithName:@"refs/heads/other-branch" error:&error]; expect(ref).notTo(beNil()); expect(error.localizedDescription).to(beNil()); - BOOL result = [repository checkoutReference:ref strategy:GTCheckoutStrategyAllowConflicts error:&error progressBlock:nil]; + BOOL result = [repository checkoutReference:ref options:[GTCheckoutOptions checkoutOptionsWithStrategy:GTCheckoutStrategyAllowConflicts] error:&error]; expect(@(result)).to(beTruthy()); expect(error.localizedDescription).to(beNil()); }); @@ -370,12 +492,67 @@ GTCommit *commit = [repository lookUpObjectBySHA:@"1d69f3c0aeaf0d62e25591987b93b8ffc53abd77" objectType:GTObjectTypeCommit error:&error]; expect(commit).notTo(beNil()); expect(error.localizedDescription).to(beNil()); - BOOL result = [repository checkoutCommit:commit strategy:GTCheckoutStrategyAllowConflicts error:&error progressBlock:nil]; + BOOL result = [repository checkoutCommit:commit options:[GTCheckoutOptions checkoutOptionsWithStrategy:GTCheckoutStrategyAllowConflicts] error:&error]; expect(@(result)).to(beTruthy()); expect(error.localizedDescription).to(beNil()); }); }); +describe(@"-checkout:strategy:notifyFlags:error:notifyBlock:progressBlock:", ^{ + it(@"should fail ref checkout with conflict and notify", ^{ + NSError *error = nil; + GTReference *ref = [repository lookUpReferenceWithName:@"refs/heads/other-branch" error:&error]; + expect(ref).notTo(beNil()); + expect(error.localizedDescription).to(beNil()); + BOOL writeResult = [@"Conflicting data in README.md\n" writeToURL:[repository.fileURL URLByAppendingPathComponent:readmeFile] atomically:YES encoding:NSUTF8StringEncoding error:&error]; + expect(@(writeResult)).to(beTruthy()); + __block NSUInteger notifyCount = 0; + __block BOOL readmeFileConflicted = NO; + int (^notifyBlock)(GTCheckoutNotifyFlags, NSString *, GTDiffFile *, GTDiffFile *, GTDiffFile *); + notifyBlock = ^(GTCheckoutNotifyFlags why, NSString *path, GTDiffFile *baseline, GTDiffFile *target, GTDiffFile *workdir) { + notifyCount++; + if([path isEqualToString:readmeFile] && (why & GTCheckoutNotifyConflict)) { + readmeFileConflicted = YES; + } + return 0; + }; + + GTCheckoutOptions *options = [GTCheckoutOptions checkoutOptionsWithStrategy:GTCheckoutStrategySafe notifyFlags:GTCheckoutNotifyConflict notifyBlock:notifyBlock]; + BOOL result = [repository checkoutReference:ref options:options error:&error]; + expect(@(notifyCount)).to(equal(@(1))); + expect(@(readmeFileConflicted)).to(beTruthy()); + expect(@(result)).to(beFalsy()); + expect(@(error.code)).to(equal(@(GIT_ECONFLICT))); + }); + + it(@"should fail commit checkout with conflict and notify", ^{ + NSError *error = nil; + GTCommit *commit = [repository lookUpObjectBySHA:@"1d69f3c0aeaf0d62e25591987b93b8ffc53abd77" objectType:GTObjectTypeCommit error:&error]; + expect(commit).notTo(beNil()); + expect(error.localizedDescription).to(beNil()); + BOOL writeResult = [@"Conflicting data in README1.txt\n" writeToURL:[repository.fileURL URLByAppendingPathComponent:readme1File] atomically:YES encoding:NSUTF8StringEncoding error:&error]; + expect(@(writeResult)).to(beTruthy()); + __block NSUInteger notifyCount = 0; + __block BOOL readme1FileConflicted = NO; + int (^notifyBlock)(GTCheckoutNotifyFlags, NSString *, GTDiffFile *, GTDiffFile *, GTDiffFile *); + notifyBlock = ^(GTCheckoutNotifyFlags why, NSString *path, GTDiffFile *baseline, GTDiffFile *target, GTDiffFile *workdir) { + notifyCount++; + if([path isEqualToString:readme1File] && (why & GTCheckoutNotifyConflict)) { + readme1FileConflicted = YES; + } + return 0; + }; + + + GTCheckoutOptions *options = [GTCheckoutOptions checkoutOptionsWithStrategy:GTCheckoutStrategySafe notifyFlags:GTCheckoutNotifyConflict notifyBlock:notifyBlock]; + BOOL result = [repository checkoutCommit:commit options:options error:&error]; + expect(@(notifyCount)).to(equal(@(1))); + expect(@(readme1FileConflicted)).to(beTruthy()); + expect(@(result)).to(beFalsy()); + expect(@(error.code)).to(equal(@(GIT_ECONFLICT))); + }); +}); + describe(@"-remoteNamesWithError:", ^{ it(@"allows access to remote names", ^{ NSError *error = nil; @@ -409,7 +586,7 @@ GTCommit *commit = [repository lookUpObjectBySHA:resetTargetSHA error:NULL]; expect(commit).notTo(beNil()); - GTCommit *originalHeadCommit = [repository lookUpObjectBySHA:originalHead.targetSHA error:NULL]; + GTCommit *originalHeadCommit = [repository lookUpObjectByOID:originalHead.targetOID error:NULL]; expect(originalHeadCommit).notTo(beNil()); BOOL success = [repository resetToCommit:commit resetType:GTRepositoryResetTypeSoft error:&error]; @@ -418,14 +595,14 @@ GTReference *head = [repository headReferenceWithError:&error]; expect(head).notTo(beNil()); - expect(head.targetSHA).to(equal(resetTargetSHA)); + expect(head.targetOID.SHA).to(equal(resetTargetSHA)); success = [repository resetToCommit:originalHeadCommit resetType:GTRepositoryResetTypeSoft error:&error]; expect(@(success)).to(beTruthy()); expect(error).to(beNil()); head = [repository headReferenceWithError:&error]; - expect(head.targetSHA).to(equal(originalHead.targetSHA)); + expect(head.targetOID).to(equal(originalHead.targetOID)); }); }); @@ -490,6 +667,146 @@ }); }); +describe(@"-branches:", ^{ + __block NSArray *branches; + + beforeEach(^{ + GTRepository *repository = [self testAppForkFixtureRepository]; + branches = [repository branches:NULL]; + expect(branches).notTo(beNil()); + }); + + it(@"should combine a local branch with its remote branch", ^{ + NSMutableArray *localBranches = [NSMutableArray array]; + NSMutableArray *remoteBranches = [NSMutableArray array]; + for (GTBranch *branch in branches) { + if ([branch.shortName isEqual:@"BranchA"]) { + if (branch.branchType == GTBranchTypeLocal) { + [localBranches addObject:branch]; + } else { + [remoteBranches addObject:branch]; + } + } + } + + expect(@(localBranches.count)).to(equal(@1)); + + GTBranch *localBranchA = localBranches[0]; + GTBranch *trackingBranch = [localBranchA trackingBranchWithError:NULL success:NULL]; + expect(trackingBranch.remoteName).to(equal(@"origin")); + + expect(@(remoteBranches.count)).to(equal(@1)); + + GTBranch *remoteBranchA = remoteBranches[0]; + expect(remoteBranchA.remoteName).to(equal(@"github")); + }); + + it(@"should contain local branches", ^{ + NSInteger index = [branches indexOfObjectPassingTest:^(GTBranch *branch, NSUInteger idx, BOOL *stop) { + return [branch.shortName isEqual:@"new-shite"]; + }]; + expect(@(index)).notTo(equal(@(NSNotFound))); + }); + + it(@"should contain remote branches which exist on multiple remotes", ^{ + NSUInteger matches = 0; + for (GTBranch *branch in branches) { + if ([branch.shortName isEqual:@"blah"] && branch.branchType == GTBranchTypeRemote) { + matches++; + } + } + expect(@(matches)).to(equal(@2)); + }); +}); + +describe(@"-userSignatureForNow", ^{ + static NSString * const userName = @"johnsmith"; + static NSString * const email = @"johnsmith@gmail.com"; + + __block GTConfiguration *configuration; + + beforeEach(^{ + configuration = [repository configurationWithError:NULL]; + expect(configuration).notTo(beNil()); + }); + + it(@"should use the values from the config", ^{ + [configuration setString:userName forKey:@"user.name"]; + [configuration setString:email forKey:@"user.email"]; + + GTSignature *signature = [repository userSignatureForNow]; + expect(signature.name).to(equal(userName)); + expect(signature.email).to(equal(email)); + }); + + describe(@"invalid values", ^{ + it(@"should use a default value if the name is empty", ^{ + [configuration setString:@"" forKey:@"user.name"]; + [configuration setString:email forKey:@"user.email"]; + + GTSignature *signature = [repository userSignatureForNow]; + expect(@(signature.name.length)).to(beGreaterThan(@0)); + expect(@(signature.email.length)).to(beGreaterThan(@0)); + }); + + it(@"should use a default value if the email is empty", ^{ + [configuration setString:userName forKey:@"user.name"]; + [configuration setString:@"" forKey:@"user.email"]; + + GTSignature *signature = [repository userSignatureForNow]; + expect(@(signature.name.length)).to(beGreaterThan(@0)); + expect(@(signature.email.length)).to(beGreaterThan(@0)); + }); + + it(@"should use a default value if the email contains angled brackets", ^{ + [configuration setString:userName forKey:@"user.name"]; + [configuration setString:@"" forKey:@"user.email"]; + + GTSignature *signature = [repository userSignatureForNow]; + expect(@(signature.name.length)).to(beGreaterThan(@0)); + expect(@(signature.email.length)).to(beGreaterThan(@0)); + }); + }); +}); + +describe(@"-calculateState:withError:", ^{ + it(@"should find if the repository is mid-merge", ^{ + GTRepository *repository = [self conflictedFixtureRepository]; + GTRepositoryStateType state; + BOOL result; + result = [repository calculateState:&state withError:NULL]; + expect(@(result)).to(beTruthy()); + expect(@(state)).to(equal(@(GTRepositoryStateMerge))); + }); + + it(@"should return none otherwise", ^{ + GTRepository *repository = [self testAppFixtureRepository]; + GTRepositoryStateType state; + BOOL result; + result = [repository calculateState:&state withError:NULL]; + expect(@(result)).to(beTruthy()); + expect(@(state)).to(equal(@(GTRepositoryStateNone))); + }); +}); + +describe(@"-cleanupStateWithError:", ^{ + it(@"should return a repository to a pre-merge state", ^{ + GTRepository *repository = [self conflictedFixtureRepository]; + + GTRepositoryStateType state; + BOOL result; + result = [repository calculateState:&state withError:NULL]; + expect(@(result)).to(beTruthy()); + expect(@(state)).to(equal(@(GTRepositoryStateMerge))); + + expect(@([repository cleanupStateWithError:NULL])).to(beTruthy()); + + result = [repository calculateState:&state withError:NULL]; + expect(@(result)).to(beTruthy()); + expect(@(state)).to(equal(@(GTRepositoryStateNone))); + }); +}); + afterEach(^{ [self tearDown]; }); diff --git a/ObjectiveGitTests/GTRepositoryStashingSpec.m b/ObjectiveGitTests/GTRepositoryStashingSpec.m index d9973e615..4b5891e56 100644 --- a/ObjectiveGitTests/GTRepositoryStashingSpec.m +++ b/ObjectiveGitTests/GTRepositoryStashingSpec.m @@ -6,9 +6,9 @@ // Copyright (c) 2013 GitHub, Inc. All rights reserved. // -#import -#import -#import +@import ObjectiveGit; +@import Nimble; +@import Quick; #import "QuickSpec+GTFixtures.h" @@ -120,6 +120,80 @@ expect(@(lastIndex)).to(equal(@2)); }); +it(@"should apply stashes", ^{ + expect(@([@"foobar" writeToURL:[repository.fileURL URLByAppendingPathComponent:@"new-test-file"] atomically:YES encoding:NSUTF8StringEncoding error:NULL])).to(beTruthy()); + + NSError *error = nil; + GTCommit *stash = [repository stashChangesWithMessage:nil flags:GTRepositoryStashFlagIncludeUntracked error:&error]; + expect(stash).notTo(beNil()); + expect(error).to(beNil()); + + __block BOOL progressCalled = NO; + BOOL success = [repository applyStashAtIndex:0 flags:GTRepositoryStashApplyFlagDefault checkoutOptions:nil error:&error progressBlock:^void(GTRepositoryStashApplyProgress step, BOOL *stop) { + progressCalled = YES; + }]; + expect(@(success)).to(beTruthy()); + expect(@(progressCalled)).to(beTruthy()); + expect(error).to(beNil()); + + expect([NSString stringWithContentsOfURL:[repository.fileURL URLByAppendingPathComponent:@"new-test-file"] encoding:NSUTF8StringEncoding error:NULL]).to(equal(@"foobar")); +}); + + +it(@"should drop stashes", ^{ + expect(@([@"foobar" writeToURL:[repository.fileURL URLByAppendingPathComponent:@"new-test-file"] atomically:YES encoding:NSUTF8StringEncoding error:NULL])).to(beTruthy()); + + NSError *error = nil; + GTCommit *stash = [repository stashChangesWithMessage:nil flags:GTRepositoryStashFlagIncludeUntracked error:&error]; + expect(stash).notTo(beNil()); + expect(error).to(beNil()); + + BOOL success = [repository dropStashAtIndex:0 error:&error]; + expect(@(success)).to(beTruthy()); + expect(error).to(beNil()); +}); + +it(@"should fail to apply/drop unknown stashes", ^{ + NSError *error = nil; + BOOL success = NO; + + __block NSUInteger lastStashIndex = 0; + [repository enumerateStashesUsingBlock:^(NSUInteger index, NSString * _Nullable message, GTOID * _Nullable oid, BOOL * _Nonnull stop) { + lastStashIndex = index; + }]; + + success = [repository applyStashAtIndex:(lastStashIndex + 1) flags:GTRepositoryStashApplyFlagDefault checkoutOptions:nil error:&error progressBlock:nil]; + expect(@(success)).to(beFalsy()); + expect(error).notTo(beNil()); + expect(error.domain).to(equal(GTGitErrorDomain)); + expect(@(error.code)).to(equal(@(GIT_ENOTFOUND))); + + success = [repository dropStashAtIndex:(lastStashIndex + 1) error:&error]; + expect(@(success)).to(beFalsy()); + expect(error).notTo(beNil()); + expect(error.domain).to(equal(GTGitErrorDomain)); + expect(@(error.code)).to(equal(@(GIT_ENOTFOUND))); +}); + +it(@"should fail to apply conflicting stashes", ^{ + expect(@([@"foobar" writeToURL:[repository.fileURL URLByAppendingPathComponent:@"new-test-file"] atomically:YES encoding:NSUTF8StringEncoding error:NULL])).to(beTruthy()); + + NSError *error = nil; + GTCommit *stash = [repository stashChangesWithMessage:nil flags:GTRepositoryStashFlagIncludeUntracked error:&error]; + expect(stash).notTo(beNil()); + expect(error).to(beNil()); + + + expect(@([@"barfoo" writeToURL:[repository.fileURL URLByAppendingPathComponent:@"new-test-file"] atomically:YES encoding:NSUTF8StringEncoding error:NULL])).to(beTruthy()); + + BOOL success = [repository applyStashAtIndex:0 flags:GTRepositoryStashApplyFlagDefault checkoutOptions:nil error:&error progressBlock:nil]; + expect(@(success)).to(beFalsy()); + expect(error).notTo(beNil()); + + expect(error.domain).to(equal(GTGitErrorDomain)); + expect(@(error.code)).to(equal(@(GIT_ECONFLICT))); +}); + afterEach(^{ [self tearDown]; }); diff --git a/ObjectiveGitTests/GTSignatureSpec.m b/ObjectiveGitTests/GTSignatureSpec.m index 266f07295..17281a0b1 100644 --- a/ObjectiveGitTests/GTSignatureSpec.m +++ b/ObjectiveGitTests/GTSignatureSpec.m @@ -6,9 +6,9 @@ // Copyright (c) 2013 GitHub, Inc. All rights reserved. // -#import -#import -#import +@import ObjectiveGit; +@import Nimble; +@import Quick; #import "QuickSpec+GTFixtures.h" @@ -49,7 +49,7 @@ const git_signature *git_signature = NULL; { - GTSignature *testSignature __attribute__((objc_precise_lifetime)) = [[GTSignature alloc] initWithName:name email:email time:time]; + GTSignature *testSignature = [[GTSignature alloc] initWithName:name email:email time:time]; git_signature = testSignature.git_signature; } diff --git a/ObjectiveGitTests/GTSubmoduleSpec.m b/ObjectiveGitTests/GTSubmoduleSpec.m index bfc569366..0a25f5e35 100644 --- a/ObjectiveGitTests/GTSubmoduleSpec.m +++ b/ObjectiveGitTests/GTSubmoduleSpec.m @@ -6,9 +6,9 @@ // Copyright (c) 2013 GitHub, Inc. All rights reserved. // -#import -#import -#import +@import ObjectiveGit; +@import Nimble; +@import Quick; #import "QuickSpec+GTFixtures.h" @@ -61,14 +61,13 @@ }); it(@"should write to the parent .git/config", ^{ - NSString *testURLString = @"fake_url"; + NSString *testURLString = @"git://fake_url"; GTSubmodule *submodule = [repo submoduleWithName:@"Test_App" error:NULL]; expect(submodule).notTo(beNil()); expect(@(git_submodule_url(submodule.git_submodule))).notTo(equal(testURLString)); - git_submodule_set_url(submodule.git_submodule, testURLString.UTF8String); - git_submodule_save(submodule.git_submodule); + git_submodule_set_url(repo.git_repository, git_submodule_name(submodule.git_submodule), testURLString.UTF8String); __block NSError *error = nil; expect(@([submodule writeToParentConfigurationDestructively:YES error:&error])).to(beTruthy()); @@ -79,26 +78,6 @@ expect(@(git_submodule_url(submodule.git_submodule))).to(equal(testURLString)); }); -it(@"should reload all submodules", ^{ - GTSubmodule *submodule = [repo submoduleWithName:@"new_submodule" error:NULL]; - expect(submodule).to(beNil()); - - NSURL *gitmodulesURL = [repo.fileURL URLByAppendingPathComponent:@".gitmodules"]; - NSMutableString *gitmodules = [NSMutableString stringWithContentsOfURL:gitmodulesURL usedEncoding:NULL error:NULL]; - expect(gitmodules).notTo(beNil()); - - [gitmodules appendString:@"[submodule \"new_submodule\"]\n\turl = some_url\n\tpath = new_submodule_path"]; - expect(@([gitmodules writeToURL:gitmodulesURL atomically:YES encoding:NSUTF8StringEncoding error:NULL])).to(beTruthy()); - - __block NSError *error = nil; - expect(@([repo reloadSubmodules:&error])).to(beTruthy()); - expect(error).to(beNil()); - - submodule = [repo submoduleWithName:@"new_submodule" error:NULL]; - expect(submodule).notTo(beNil()); - expect(submodule.path).to(equal(@"new_submodule_path")); -}); - it(@"should add its HEAD to its parent's index", ^{ GTSubmodule *submodule = [repo submoduleWithName:@"Test_App" error:NULL]; expect(submodule).notTo(beNil()); @@ -107,13 +86,23 @@ expect(submoduleRepository).notTo(beNil()); GTCommit *commit = [submoduleRepository lookUpObjectByRevParse:@"HEAD^" error:NULL]; - BOOL success = [submoduleRepository checkoutCommit:commit strategy:GTCheckoutStrategyForce error:NULL progressBlock:nil]; + BOOL success = [submoduleRepository checkoutCommit:commit options:[GTCheckoutOptions checkoutOptionsWithStrategy:GTCheckoutStrategyForce] error:NULL]; expect(@(success)).to(beTruthy()); success = [submodule addToIndex:NULL]; expect(@(success)).to(beTruthy()); }); +it(@"should update the ignore rule", ^{ + GTSubmodule *submodule = [repo submoduleWithName:@"Test_App" error:NULL]; + expect(submodule).notTo(beNil()); + expect(@(submodule.ignoreRule)).to(equal(@(GTSubmoduleIgnoreNone))); + + GTSubmodule *updatedSubmodule = [submodule submoduleByUpdatingIgnoreRule:GTSubmoduleIgnoreAll error:NULL]; + expect(@(updatedSubmodule.ignoreRule)).to(equal(@(GTSubmoduleIgnoreAll))); + expect(@(submodule.ignoreRule)).to(equal(@(GTSubmoduleIgnoreNone))); +}); + describe(@"clean, checked out submodule", ^{ __block GTSubmodule *submodule; @@ -225,13 +214,11 @@ }); it(@"should honor the ignore rule", ^{ - submodule.ignoreRule = GTSubmoduleIgnoreDirty; - GTSubmoduleStatus expectedStatus = GTSubmoduleStatusExistsInHEAD | GTSubmoduleStatusExistsInIndex | GTSubmoduleStatusExistsInConfig | GTSubmoduleStatusExistsInWorkingDirectory | GTSubmoduleStatusModifiedInIndex | GTSubmoduleStatusModifiedInWorkingDirectory; - expect(@([submodule status:NULL])).to(equal(@(expectedStatus))); + expect(@([submodule statusWithIgnoreRule:GTSubmoduleIgnoreDirty error:NULL])).to(equal(@(expectedStatus))); }); it(@"should open a repository" ,^{ @@ -253,15 +240,12 @@ NSString *configKey = @"submodule.Test_App2.url"; NSString *newOrigin = @"https://github.com/libgit2/objective-git.git"; - [config setString:newOrigin forKey:configKey]; - expect(@([config refresh:NULL])).to(beTruthy()); + [config setString:newOrigin forKey:configKey]; expect([config stringForKey:configKey]).to(equal(newOrigin)); __block NSError *error = nil; expect(@([submodule sync:&error])).to(beTruthy()); - - expect(@([config refresh:NULL])).to(beTruthy()); expect([config stringForKey:configKey]).to(equal(@"../Test_App")); }); }); diff --git a/ObjectiveGitTests/GTTagSpec.m b/ObjectiveGitTests/GTTagSpec.m index b6ab16506..bdbb5a5b4 100644 --- a/ObjectiveGitTests/GTTagSpec.m +++ b/ObjectiveGitTests/GTTagSpec.m @@ -6,9 +6,9 @@ // Copyright (c) 2013 GitHub, Inc. All rights reserved. // -#import -#import -#import +@import ObjectiveGit; +@import Nimble; +@import Quick; #import "QuickSpec+GTFixtures.h" @@ -39,6 +39,18 @@ expect(signature.email).to(equal(@"schacon@gmail.com")); }); +it(@"can delete tags", ^{ + NSError *error = nil; + + BOOL success = [tag delete:&error]; + expect(@(success)).to(beTruthy()); + expect(error).to(beNil()); + + success = [tag delete:&error]; + expect(@(success)).to(beFalsy()); + expect(error).notTo(beNil()); +}); + afterEach(^{ [self tearDown]; }); diff --git a/ObjectiveGitTests/GTTimeAdditionsSpec.m b/ObjectiveGitTests/GTTimeAdditionsSpec.m index c63cb9dbf..21c649141 100644 --- a/ObjectiveGitTests/GTTimeAdditionsSpec.m +++ b/ObjectiveGitTests/GTTimeAdditionsSpec.m @@ -6,9 +6,9 @@ // Copyright (c) 2013 GitHub, Inc. All rights reserved. // -#import -#import -#import +@import ObjectiveGit; +@import Nimble; +@import Quick; #import "QuickSpec+GTFixtures.h" diff --git a/ObjectiveGitTests/GTTreeBuilderSpec.m b/ObjectiveGitTests/GTTreeBuilderSpec.m index 1308e130f..4c0d9a3b1 100644 --- a/ObjectiveGitTests/GTTreeBuilderSpec.m +++ b/ObjectiveGitTests/GTTreeBuilderSpec.m @@ -6,9 +6,9 @@ // Copyright (c) 2013 Johnnie Walker // -#import -#import -#import +@import ObjectiveGit; +@import Nimble; +@import Quick; #import "QuickSpec+GTFixtures.h" @@ -16,9 +16,16 @@ QuickSpecBegin(GTTreeBuilderSpec) +__block GTRepository *repo; + +beforeEach(^{ + repo = self.bareFixtureRepository; + expect(repo).notTo(beNil()); +}); + it(@"should be possible to make a new tree builder without a tree", ^{ NSError *error = nil; - GTTreeBuilder *builder = [[GTTreeBuilder alloc] initWithTree:nil error:&error]; + GTTreeBuilder *builder = [[GTTreeBuilder alloc] initWithTree:nil repository:repo error:&error]; expect(error).to(beNil()); expect(builder).notTo(beNil()); }); @@ -26,13 +33,10 @@ it(@"should be possible to make a new tree builder from an existing tree", ^{ NSError *error = nil; - GTRepository *repo = self.bareFixtureRepository; - expect(repo).notTo(beNil()); - GTTree *tree = (GTTree *)[repo lookUpObjectBySHA:testTreeSHA error:NULL]; expect(tree).notTo(beNil()); - GTTreeBuilder *builder = [[GTTreeBuilder alloc] initWithTree:tree error:&error]; + GTTreeBuilder *builder = [[GTTreeBuilder alloc] initWithTree:tree repository:repo error:&error]; expect(error).to(beNil()); expect(builder).notTo(beNil()); }); @@ -43,7 +47,7 @@ __block GTOID *OID; beforeEach(^{ - builder = [[GTTreeBuilder alloc] initWithTree:nil error:&error]; + builder = [[GTTreeBuilder alloc] initWithTree:nil repository:repo error:&error]; expect(builder).notTo(beNil()); expect(error).to(beNil()); @@ -74,9 +78,6 @@ }); it(@"should be possible to filter a builder", ^{ - GTRepository *repo = self.bareFixtureRepository; - expect(repo).notTo(beNil()); - GTBlob *blob = [GTBlob blobWithString:@"Hi, how are you?" inRepository:repo error:&error]; expect(blob).notTo(beNil()); expect(error).to(beNil()); @@ -102,35 +103,27 @@ expect(foundEntry.SHA).to(equal(entry.SHA)); }); - it(@"should write new blobs when the tree is written", ^{ - GTRepository *repo = self.bareFixtureRepository; - expect(repo).notTo(beNil()); - + it(@"should be possible to write a blob with data", ^{ GTTreeEntry *entry = [builder addEntryWithData:[@"Hello, World!" dataUsingEncoding:NSUTF8StringEncoding] fileName:@"test.txt" fileMode:GTFileModeBlob error:NULL]; expect(entry).notTo(beNil()); GTObjectDatabase *database = [repo objectDatabaseWithError:NULL]; expect(database).notTo(beNil()); - expect(@([database containsObjectWithOID:entry.OID])).to(beFalsy()); + expect(@([database containsObjectWithOID:entry.OID])).to(beTruthy()); - GTTree *tree = [builder writeTreeToRepository:repo error:NULL]; + GTTree *tree = [builder writeTree:NULL]; expect(tree).notTo(beNil()); - - expect(@([database containsObjectWithOID:entry.OID])).to(beTruthy()); }); it(@"should be possible to write a builder to a repository", ^{ - GTRepository *repo = self.bareFixtureRepository; - expect(repo).notTo(beNil()); - GTBlob *blob = [GTBlob blobWithString:@"Hi, how are you?" inRepository:repo error:&error]; expect(blob).notTo(beNil()); expect(error).to(beNil()); [builder addEntryWithOID:blob.OID fileName:@"hi.txt" fileMode:GTFileModeBlob error:&error]; - GTTree *writtenTree = [builder writeTreeToRepository:repo error:&error]; + GTTree *writtenTree = [builder writeTree:&error]; expect(writtenTree).notTo(beNil()); expect(error).to(beNil()); diff --git a/ObjectiveGitTests/GTTreeSpec.m b/ObjectiveGitTests/GTTreeSpec.m index 05d1e5677..70a1c10d2 100644 --- a/ObjectiveGitTests/GTTreeSpec.m +++ b/ObjectiveGitTests/GTTreeSpec.m @@ -6,9 +6,9 @@ // Copyright (c) 2013 GitHub, Inc. All rights reserved. // -#import -#import -#import +@import ObjectiveGit; +@import Nimble; +@import Quick; #import "QuickSpec+GTFixtures.h" @@ -99,6 +99,30 @@ expect([tree entryWithName:@"_does not exist"]).to(beNil()); }); +describe(@"fetching entries from paths", ^{ + it(@"should be able to fetch existing paths",^{ + NSError *error = nil; + GTTreeEntry *entry; + + entry = [tree entryWithPath:@"README" error:&error]; + expect(error).to(beNil()); + expect(entry).notTo(beNil()); + + entry = [tree entryWithPath:@"subdir/README" error:&error]; + expect(error).to(beNil()); + expect(entry).notTo(beNil()); + }); + + it(@"should return nil and fill error for non-existent paths",^{ + NSError *error = nil; + GTTreeEntry *entry; + + entry = [tree entryWithPath:@"does/not/exist" error:&error]; + expect(error).notTo(beNil()); + expect(entry).to(beNil()); + }); +}); + afterEach(^{ [self tearDown]; }); diff --git a/ObjectiveGitTests/GTUtilityFunctions.h b/ObjectiveGitTests/GTUtilityFunctions.h new file mode 100644 index 000000000..721d62a5d --- /dev/null +++ b/ObjectiveGitTests/GTUtilityFunctions.h @@ -0,0 +1,29 @@ +// +// GTUtilityFunctions.h +// ObjectiveGitFramework +// +// Created by Ben Chatelain on 6/28/15. +// Copyright (c) 2015 GitHub, Inc. All rights reserved. +// + +@import ObjectiveGit; +@import Nimble; +@import Quick; + +@class GTBranch; +@class GTCommit; +@class GTRepository; + +#pragma mark - Commit + +typedef GTCommit *(^CreateCommitBlock)(NSString *message, NSData *fileData, NSString *fileName, GTRepository *repo); + +// Helper to quickly create commits +extern CreateCommitBlock createCommitInRepository; + +#pragma mark - Branch + +typedef GTBranch *(^BranchBlock)(NSString *, GTRepository *); + +// Helper to retrieve a branch by name +extern BranchBlock localBranchWithName; diff --git a/ObjectiveGitTests/GTUtilityFunctions.m b/ObjectiveGitTests/GTUtilityFunctions.m new file mode 100644 index 000000000..a09b1ce6e --- /dev/null +++ b/ObjectiveGitTests/GTUtilityFunctions.m @@ -0,0 +1,49 @@ +// +// GTUtilityFunctions.m +// ObjectiveGitFramework +// +// Created by Ben Chatelain on 6/28/15. +// Copyright (c) 2015 GitHub, Inc. All rights reserved. +// + +@import ObjectiveGit; +@import Nimble; +@import Quick; + +#import "GTUtilityFunctions.h" + +#pragma mark - Commit + +CreateCommitBlock createCommitInRepository = ^ GTCommit * (NSString *message, NSData *fileData, NSString *fileName, GTRepository *repo) { + GTReference *head = [repo headReferenceWithError:NULL]; + GTBranch *branch = [GTBranch branchWithReference:head]; + GTCommit *headCommit = [branch targetCommitWithError:NULL]; + + GTTreeBuilder *treeBuilder = [[GTTreeBuilder alloc] initWithTree:headCommit.tree repository:repo error:nil]; + [treeBuilder addEntryWithData:fileData fileName:fileName fileMode:GTFileModeBlob error:nil]; + + GTTree *testTree = [treeBuilder writeTree:nil]; + + // We need the parent commit to make the new one + GTReference *headReference = [repo headReferenceWithError:nil]; + + GTEnumerator *commitEnum = [[GTEnumerator alloc] initWithRepository:repo error:nil]; + [commitEnum pushSHA:[headReference targetOID].SHA error:nil]; + GTCommit *parent = [commitEnum nextObject]; + + GTCommit *testCommit = [repo createCommitWithTree:testTree message:message parents:@[ parent ] updatingReferenceNamed:headReference.name error:nil]; + expect(testCommit).notTo(beNil()); + + return testCommit; +}; + +#pragma mark - Branch + +BranchBlock localBranchWithName = ^ GTBranch * (NSString *branchName, GTRepository *repo) { + BOOL success = NO; + GTBranch *branch = [repo lookUpBranchWithName:branchName type:GTBranchTypeLocal success:&success error:NULL]; + expect(branch).notTo(beNil()); + expect(branch.shortName).to(equal(branchName)); + + return branch; +}; diff --git a/ObjectiveGitTests/Libgit2FeaturesSpec.m b/ObjectiveGitTests/Libgit2FeaturesSpec.m new file mode 100644 index 000000000..1a57524f5 --- /dev/null +++ b/ObjectiveGitTests/Libgit2FeaturesSpec.m @@ -0,0 +1,46 @@ +// +// Libgit2FeaturesSpec.m +// ObjectiveGitFramework +// +// Created by Ben Chatelain on 7/6/15. +// Copyright (c) 2015 GitHub, Inc. All rights reserved. +// + +@import ObjectiveGit; +@import Nimble; +@import Quick; + +#import "QuickSpec+GTFixtures.h" + +QuickSpecBegin(Libgit2FeaturesSpec) + +describe(@"libgit", ^{ + + __block git_feature_t git_features = 0; + + beforeEach(^{ + git_features = git_libgit2_features(); + }); + + it(@"should be built with THREADS enabled", ^{ + expect(@(git_features & GIT_FEATURE_THREADS)).to(beTruthy()); + }); + + it(@"should be built with HTTPS enabled", ^{ + expect(@(git_features & GIT_FEATURE_HTTPS)).to(beTruthy()); + }); + + it(@"should be built with SSH enabled", ^{ + expect(@(git_features & GIT_FEATURE_SSH)).to(beTruthy()); + }); + + it(@"should have ssh memory credentials", ^{ + NSError *error; + GTCredential *cred = [GTCredential credentialWithUserName:@"null" publicKeyString:@"pub" privateKeyString:@"priv" passphrase:@"pass" error:&error]; + + expect(cred).notTo(beNil()); + expect(error).to(beNil()); + }); +}); + +QuickSpecEnd diff --git a/ObjectiveGitTests/NSArray+StringArraySpec.m b/ObjectiveGitTests/NSArray+StringArraySpec.m index 6a2e903ec..757e86425 100644 --- a/ObjectiveGitTests/NSArray+StringArraySpec.m +++ b/ObjectiveGitTests/NSArray+StringArraySpec.m @@ -6,9 +6,9 @@ // Copyright (c) 2013 GitHub, Inc. All rights reserved. // -#import -#import -#import +@import ObjectiveGit; +@import Nimble; +@import Quick; #import "QuickSpec+GTFixtures.h" diff --git a/ObjectiveGitTests/NSDataGitSpec.m b/ObjectiveGitTests/NSDataGitSpec.m index bc3c4fe37..bc54ea77a 100644 --- a/ObjectiveGitTests/NSDataGitSpec.m +++ b/ObjectiveGitTests/NSDataGitSpec.m @@ -6,9 +6,9 @@ // Copyright (c) 2014 GitHub, Inc. All rights reserved. // -#import -#import -#import +@import ObjectiveGit; +@import Nimble; +@import Quick; #import "QuickSpec+GTFixtures.h" diff --git a/ObjectiveGitTests/NSErrorGitSpec.m b/ObjectiveGitTests/NSErrorGitSpec.m index faa611796..692174371 100644 --- a/ObjectiveGitTests/NSErrorGitSpec.m +++ b/ObjectiveGitTests/NSErrorGitSpec.m @@ -6,9 +6,9 @@ // Copyright (c) 2013 GitHub, Inc. All rights reserved. // -#import -#import -#import +@import ObjectiveGit; +@import Nimble; +@import Quick; #import "QuickSpec+GTFixtures.h" diff --git a/ObjectiveGitTests/ObjectiveGitTests-Info.plist b/ObjectiveGitTests/ObjectiveGitTests-Info.plist index b2481283d..169b6f710 100644 --- a/ObjectiveGitTests/ObjectiveGitTests-Info.plist +++ b/ObjectiveGitTests/ObjectiveGitTests-Info.plist @@ -7,7 +7,7 @@ CFBundleExecutable ${EXECUTABLE_NAME} CFBundleIdentifier - com.libgit2.${PRODUCT_NAME:rfc1034identifier} + $(PRODUCT_BUNDLE_IDENTIFIER) CFBundleInfoDictionaryVersion 6.0 CFBundlePackageType diff --git a/ObjectiveGitTests/QuickSpec+GTFixtures.h b/ObjectiveGitTests/QuickSpec+GTFixtures.h index c2a2e5dc3..7e5524390 100644 --- a/ObjectiveGitTests/QuickSpec+GTFixtures.h +++ b/ObjectiveGitTests/QuickSpec+GTFixtures.h @@ -6,13 +6,15 @@ // Copyright (c) 2013 GitHub, Inc. All rights reserved. // -#import +@import ObjectiveGit; +@import Quick; @class GTRepository; // FIXME: This category is a total hack, but there's no other way to run // teardown logic for every example yet: // https://github.com/Quick/Quick/issues/163 +// TODO: https://github.com/Quick/Quick/blob/master/Documentation/en-us/ConfiguringQuick.md#adding-global-beforeeach-and-aftereach-closures @interface QuickSpec (GTFixtures) // The file URL for a temporary directory which will live for the length of each @@ -22,6 +24,9 @@ // A fully fledged repository, great for testing nearly everything. - (GTRepository *)testAppFixtureRepository; +/// A fork of Test_App. +- (GTRepository *)testAppForkFixtureRepository; + // A bare repository with a minimal history. - (GTRepository *)bareFixtureRepository; diff --git a/ObjectiveGitTests/QuickSpec+GTFixtures.m b/ObjectiveGitTests/QuickSpec+GTFixtures.m index 0b9dfd25f..a54270a39 100644 --- a/ObjectiveGitTests/QuickSpec+GTFixtures.m +++ b/ObjectiveGitTests/QuickSpec+GTFixtures.m @@ -8,8 +8,9 @@ #import "QuickSpec+GTFixtures.h" -#import -#import +@import ObjectiveC; +@import ObjectiveGit; +@import ZipArchive; static const NSInteger FixturesErrorUnzipFailed = 666; @@ -64,8 +65,12 @@ - (void)cleanUp { #pragma mark Fixtures +- (NSString *)rootTempDirectory { + return [NSTemporaryDirectory() stringByAppendingPathComponent:@"com.libgit2.objectivegit"]; +} + - (void)setUpTempDirectoryPath { - self.tempDirectoryPath = [[NSTemporaryDirectory() stringByAppendingPathComponent:@"com.libgit2.objectivegit"] stringByAppendingPathComponent:NSProcessInfo.processInfo.globallyUniqueString]; + self.tempDirectoryPath = [self.rootTempDirectory stringByAppendingPathComponent:NSProcessInfo.processInfo.globallyUniqueString]; NSError *error = nil; BOOL success = [NSFileManager.defaultManager createDirectoryAtPath:self.tempDirectoryPath withIntermediateDirectories:YES attributes:nil error:&error]; @@ -84,9 +89,15 @@ - (void)setUpRepositoryFixtureIfNeeded:(NSString *)repositoryName { NSString *zippedRepositoriesPath = [[NSBundle bundleForClass:self.class] pathForResource:@"fixtures" ofType:@"zip"]; - error = nil; - success = [self unzipFile:repositoryName fromArchiveAtPath:zippedRepositoriesPath intoDirectory:self.repositoryFixturesPath error:&error]; - XCTAssertTrue(success, @"Couldn't unzip fixture \"%@\" from %@ to %@: %@", repositoryName, zippedRepositoriesPath, self.repositoryFixturesPath, error); + NSString *cleanRepositoryPath = [self.rootTempDirectory stringByAppendingPathComponent:@"clean_repository"]; + if (![NSFileManager.defaultManager fileExistsAtPath:cleanRepositoryPath isDirectory:nil]) { + error = nil; + success = [self unzipFromArchiveAtPath:zippedRepositoriesPath intoDirectory:cleanRepositoryPath error:&error]; + XCTAssertTrue(success, @"Couldn't unzip fixture \"%@\" from %@ to %@: %@", repositoryName, zippedRepositoriesPath, cleanRepositoryPath, error); + } + + success = [[NSFileManager defaultManager] copyItemAtPath:[cleanRepositoryPath stringByAppendingPathComponent:repositoryName] toPath:path error:&error]; + XCTAssertTrue(success, @"Couldn't copy directory %@", error); } - (NSString *)pathForFixtureRepositoryNamed:(NSString *)repositoryName { @@ -95,26 +106,22 @@ - (NSString *)pathForFixtureRepositoryNamed:(NSString *)repositoryName { return [self.repositoryFixturesPath stringByAppendingPathComponent:repositoryName]; } -- (BOOL)unzipFile:(NSString *)member fromArchiveAtPath:(NSString *)zipPath intoDirectory:(NSString *)destinationPath error:(NSError **)error { - NSTask *task = [[NSTask alloc] init]; - task.launchPath = @"/usr/bin/unzip"; - task.arguments = @[ @"-qq", @"-d", destinationPath, zipPath, [member stringByAppendingString:@"*"] ]; +- (BOOL)unzipFromArchiveAtPath:(NSString *)zipPath intoDirectory:(NSString *)destinationPath error:(NSError **)error { + BOOL success = [SSZipArchive unzipFileAtPath:zipPath toDestination:destinationPath overwrite:YES password:nil error:error]; - [task launch]; - [task waitUntilExit]; - - BOOL success = (task.terminationStatus == 0); if (!success) { - if (error != NULL) *error = [NSError errorWithDomain:FixturesErrorDomain code:FixturesErrorUnzipFailed userInfo:@{ NSLocalizedDescriptionKey: NSLocalizedString(@"Unzip failed", @"") }]; + NSLog(@"Unzip failed"); + return NO; } - return success; + return YES; } #pragma mark API - (GTRepository *)fixtureRepositoryNamed:(NSString *)name { - GTRepository *repository = [[GTRepository alloc] initWithURL:[NSURL fileURLWithPath:[self pathForFixtureRepositoryNamed:name]] error:NULL]; + NSURL *url = [NSURL fileURLWithPath:[self pathForFixtureRepositoryNamed:name]]; + GTRepository *repository = [[GTRepository alloc] initWithURL:url error:NULL]; XCTAssertNotNil(repository, @"Couldn't create a repository for %@", name); return repository; } @@ -123,6 +130,10 @@ - (GTRepository *)testAppFixtureRepository { return [self fixtureRepositoryNamed:@"Test_App"]; } +- (GTRepository *)testAppForkFixtureRepository { + return [self fixtureRepositoryNamed:@"Test_App_fork"]; +} + - (GTRepository *)testUnicodeFixtureRepository { return [self fixtureRepositoryNamed:@"unicode-files-repo"]; } diff --git a/ObjectiveGitTests/SwiftSpec.swift b/ObjectiveGitTests/SwiftSpec.swift index 46b8aaa00..90085614c 100644 --- a/ObjectiveGitTests/SwiftSpec.swift +++ b/ObjectiveGitTests/SwiftSpec.swift @@ -1,17 +1,18 @@ // // SwiftSpec.swift -// Archimedes +// ObjectiveGitFramework // // Created by Justin Spahr-Summers on 2014-10-02. // Copyright (c) 2014 GitHub. All rights reserved. // -import Foundation import Nimble import Quick +import XCTest // Without this, the Swift stdlib won't be linked into the test target (even if // “Embedded Content Contains Swift Code” is enabled). +// https://github.com/Quick/Quick/issues/164 class SwiftSpec: QuickSpec { override func spec() { expect(true).to(beTruthy()) diff --git a/ObjectiveGitTests/fixtures/fixtures.zip b/ObjectiveGitTests/fixtures/fixtures.zip index f0e6f4baa..9cc434a23 100644 Binary files a/ObjectiveGitTests/fixtures/fixtures.zip and b/ObjectiveGitTests/fixtures/fixtures.zip differ diff --git a/README.md b/README.md index 0ee413a9a..db22e4241 100644 --- a/README.md +++ b/README.md @@ -1,76 +1,156 @@ # ObjectiveGit +[![Carthage compatible](https://img.shields.io/badge/Carthage-compatible-4BC51D.svg?style=flat)](https://github.com/Carthage/Carthage) +[![Build Status](https://travis-ci.org/libgit2/objective-git.svg?branch=master)](https://travis-ci.org/libgit2/objective-git) + ObjectiveGit provides Cocoa bindings to the -[libgit2](https://github.com/libgit2/libgit2) library. +[libgit2](https://github.com/libgit2/libgit2) library, packaged as a dynamic framework for OS X and iOS 8 or better. + +## Features + +A brief summary of the available functionality: + +* Read: log, diff, blame, reflog, status +* Write: init, checkout, commit, branch, tag, reset +* Internals: configuration, tree, blob, object database +* Network: clone, fetch, push, pull +* Transports: HTTP, HTTPS, SSH, local filesystem + +Not all libgit2 features are available, but if you run across something missing, please consider [contributing a pull request](#contributing)! + +Many classes in the ObjectiveGit API wrap a C struct from libgit2 and expose the underlying data and operations using Cocoa idioms. The underlying libgit2 types are prefixed with `git_` and are often accessible via a property so that your application can take advantage of the [libgit2 API](https://libgit2.github.com/libgit2/#HEAD) directly. -Not all libgit2 features are available yet. If you run across something missing, -please consider [contributing a pull request](#contributing)! +The ObjectiveGit API makes extensive use of the Cocoa NSError pattern. The public API is also decorated with nullability attributes so that you will get compile-time feedback of whether nil is allowed or not. This also makes the framework much nicer to use in Swift. ## Getting Started -To start building the framework, you must install the required dependencies, -[xctool](https://github.com/facebook/xctool) and -[cmake](https://github.com/Kitware/CMake). We recommend using -[Homebrew](http://brew.sh) to install these two tools. +### Xcode -Once you have the dependencies you should clone this repository and then run -`script/bootstrap`. This will automatically pull down and install any other -dependencies. +ObjectiveGit requires Xcode 7 or greater to build the framework and run unit tests. Projects that must use an older version of Xcode can use +[Carthage](#carthage) to install pre-built binaries +or download them [manually](#manually). -Note that the `bootstrap` script automatically installs some libraries that -ObjectiveGit relies upon, using Homebrew. If you want this behavior, please -make sure you have Homebrew installed. +### Other Tools + +Simply run the [`script/bootstrap`](script/bootstrap) script to automatically install +dependencies needed to start building the framework. This script uses +[Homebrew](http://brew.sh) to install these tools. If your Mac does not have +Homebrew, you will need to install the following manually: + +- [cmake](https://github.com/Kitware/CMake) +- libtool +- autoconf +- automake +- pkg-config +- libssh2 + - symlinks: lib/libssh2.a include/libssh2.h include/libssh2_sftp.h include/libssh2_publickey.h To develop ObjectiveGit on its own, open the `ObjectiveGitFramework.xcworkspace` file. -## Importing ObjectiveGit on OS X +# Installation + +There are three ways of including ObjectiveGit in a project: + +1. [Carthage](#carthage) <-- recommended +1. [Manual](#manual) +1. [Subproject](#subproject) + + +## Carthage + +1. Add ObjectiveGit to your [`Cartfile`](https://github.com/Carthage/Carthage/blob/master/Documentation/Artifacts.md#cartfile). + + ``` + github "libgit2/objective-git" + ``` + +1. Run `carthage update`. +1. **Mac targets** + * On your application targets' "General" settings tab, in the "Embedded Binaries" section, drag and drop the `ObjectiveGit.framework` from the [`Carthage/Build/Mac`](https://github.com/Carthage/Carthage/blob/master/Documentation/Artifacts.md#carthagebuild) folder on disk. + + ![Embedded Binaries](http://i.imgur.com/W9EVyIX.png) + +1. **iOS targets** + * On your application targets' "General" settings tab, in the "Linked Frameworks and Libraries" section, drag and drop the `ObjectiveGit.framework` from the [`Carthage/Build/iOS`](https://github.com/Carthage/Carthage/blob/master/Documentation/Artifacts.md#carthagebuild) folder on disk. + ![Linked Frameworks](http://i.imgur.com/y4caRw0.png) + + * On your application targets' "Build Phases" settings tab, click the “+” icon and choose “New Run Script Phase”. Create a Run Script with the following contents: + + ``` + /usr/local/bin/carthage copy-frameworks + ``` + + and add the paths to the frameworks you want to use under “Input Files”, e.g.: + + ``` + $(SRCROOT)/Carthage/Build/iOS/ObjectiveGit.framework + ``` -It is simple enough to add the ObjectiveGit framework to a desktop application -project. An example of this is the -[CommitViewer](https://github.com/Abizern/CommitViewer) example on GitHub. In summary: + ![Carthage Copy Frameworks](http://i.imgur.com/zXai6rb.png) -1. Drag the `ObjectiveGitFramework.xcodeproj` file into the project navigator. -1. Add the ObjectiveGit framework as a target dependency of your application. +1. Commit the [`Cartfile.resolved`](https://github.com/Carthage/Carthage/blob/master/Documentation/Artifacts.md#cartfileresolved) + +2. Under “Build Settings”, add the following to “Header Search Paths”: `$(SRCROOT)/Carthage/Build/iOS/ObjectiveGit.framework/Headers/` to avoid [`git2/filter.h file not found` errors](https://github.com/libgit2/objective-git/issues/441). + +The different instructions for iOS works around an [App Store submission bug](http://www.openradar.me/radar?id=6409498411401216) triggered by universal binaries. + + +### Copying debug symbols for debugging and crash reporting + +_dSYM files are not currently included in the GitHub release zip files. You will need to pass **--no-use-binaries** to carthage in order to build locally and generate the dSYM files alongside the framework._ + +1. On your application target's "Build Phases" settings tab, click the "+" icon and choose "New Copy Files Phase". +2. Click the “Destination” drop-down menu and select "Products Directory". +3. Drag and drop the `ObjectiveGit.framework.dSYM` file from `Carthage/Build/[platform]` into the list. + +![Copy dSYM Files](http://i.imgur.com/WKJdHHQ.png) + + +## Manual + +1. Download the latest `ObjectiveGit.framework.zip` from [releases](https://github.com/libgit2/objective-git/releases). +1. Unzip the file. +1. Follow the Carthage instructions #3 or #4, depending on platform. + +Note that the iOS framework we release is a "fat" framework containing slices for both the iOS Simulator and devices. This makes it easy to get started with your iOS project. However, Apple does not currently allow apps containing frameworks with simulator slices to be submitted to the app store. Carthage (above) already has a solution for this. If you're looking to roll your own, take a look at Realm's [strip frameworks script](https://github.com/realm/realm-cocoa/blob/master/scripts/strip-frameworks.sh). + + +## Subproject + +### Examples + +* OS X: [CommitViewer](https://github.com/Abizern/CommitViewer) +* iOS: [ObjectiveGit iOS Example](https://github.com/Raekye/ObjectiveGit-iOS-Example) + +1. Add ObjectiveGit as a submodule to your project: + + ``` + git submodule add https://github.com/libgit2/objective-git.git External/ObjectiveGit + ``` + +1. Run `script/bootstrap`. +1. Drag the `ObjectiveGitFramework.xcodeproj` file into the Project Navigator pane of your project. +1. Add `ObjectiveGit-Mac` or `ObjectiveGit-iOS` as a target dependency of your application, depending on platform. 1. Link your application with `ObjectiveGit.framework`. -1. Add a new "Copy Files" build phase, set the destination to "Frameworks" and - add `ObjectiveGit.framework` to that. This will package the framework with - your application as an embedded private framework. -1. Set the “Header Search Paths” (`HEADER_SEARCH_PATHS`) build setting to the - correct path for the libgit2 headers in your project. For example, if you - added the submodule to your project as `External/ObjectiveGit`, you would - set this build setting to `External/ObjectiveGit/External/libgit2/include`. - If you see build errors saying that `git2/filter.h` cannot be found, then - double-check that you set this setting correctly. -1. Don't forget to `#import ` as you would with any - other framework. - -## Importing ObjectiveGit on iOS - -Getting started is slightly more difficult on iOS because third-party frameworks -are not officially supported. ObjectiveGit offers a static library instead. An example -of this is the [ObjectiveGit iOS Example](https://github.com/Raekye/ObjectiveGit-iOS-Example) -on GitHub. In summary: - -1. Drag `ObjectiveGitFramework.xcodeproj` into the Project Navigator. -1. Add `ObjectiveGit-iOS` as a target dependency of your application. -1. Link your application to `libObjectiveGit-iOS.a`, `libz.dylib`, and `libiconv.dylib`. -1. In your target's build settings: - 1. Set "Always Search User Paths" to `YES` - 1. Add `$(BUILT_PRODUCTS_DIR)/usr/local/include` and - `PATH/TO/OBJECTIVE-GIT/External/libgit2/include` to the "User Header - Search Paths" - 1. Add `-all_load` to the "Other Linker Flags" +1. Set the “Header Search Paths” (`HEADER_SEARCH_PATHS`) build setting to the correct path for the libgit2 headers in your project. For example, if you added the submodule to your project as `External/ObjectiveGit`, you would set this build setting to `External/ObjectiveGit/External/libgit2/include`. If you see build errors saying that `git2/filter.h` cannot be found, then double-check that you set this setting correctly. +1. Add a new "Copy Files" build phase, set the destination to "Frameworks" and add `ObjectiveGit.framework` to the list. This will package the framework with your application as an embedded private framework. + * It's hard to tell the difference between the platforms, but the Mac framework is in `build/Debug` whereas the iOS framework is in `build/Debug-iphoneos` +1. Don't forget to `#import ` or `@import ObjectiveGit;` as you would with any other framework. + + ## Contributing -Fork the repository on GitHub, make it awesomer (preferably in a branch named -for the topic), send a pull request. +1. Fork this repository +1. Make it awesomer (preferably in a branch named for the topic) +1. Send a pull request All contributions should match GitHub's [Objective-C coding -conventions](https://github.com/github/objective-c-conventions). +conventions](https://github.com/github/objective-c-style-guide). You can see all the amazing people that have contributed to this project -[here](https://github.com/libgit2/objective-git/contributors). +[here](https://github.com/libgit2/objective-git/graphs/contributors). + ## License diff --git a/script/LICENSE.md b/script/LICENSE.md deleted file mode 100644 index 8d9238408..000000000 --- a/script/LICENSE.md +++ /dev/null @@ -1,18 +0,0 @@ -**Copyright (c) 2013 Justin Spahr-Summers** - -Permission is hereby granted, free of charge, to any person obtaining a copy of -this software and associated documentation files (the "Software"), to deal in -the Software without restriction, including without limitation the rights to -use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of -the Software, and to permit persons to whom the Software is furnished to do so, -subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS -FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR -COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER -IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN -CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/script/README.md b/script/README.md deleted file mode 100644 index f66206fb3..000000000 --- a/script/README.md +++ /dev/null @@ -1,82 +0,0 @@ -# objc-build-scripts - -This project is a collection of scripts created with two goals: - - 1. To standardize how Objective-C projects are bootstrapped after cloning - 1. To easily build Objective-C projects on continuous integration servers - -## Scripts - -Right now, there are two important scripts: [`bootstrap`](#bootstrap) and -[`cibuild`](#cibuild). Both are Bash scripts, to maximize compatibility and -eliminate pesky system configuration issues (like setting up a working Ruby -environment). - -The structure of the scripts on disk is meant to follow that of a typical Ruby -project: - -``` -script/ - bootstrap - cibuild -``` - -### bootstrap - -This script is responsible for bootstrapping (initializing) your project after -it's been checked out. Here, you should install or clone any dependencies that -are required for a working build and development environment. - -By default, the script will verify that [xctool][] is installed, then initialize -and update submodules recursively. If any submodules contain `script/bootstrap`, -that will be run as well. - -To check that other tools are installed, you can set the `REQUIRED_TOOLS` -environment variable before running `script/bootstrap`, or edit it within the -script directly. Note that no installation is performed automatically, though -this can always be added within your specific project. - -### cibuild - -This script is responsible for building the project, as you would want it built -for continuous integration. This is preferable to putting the logic on the CI -server itself, since it ensures that any changes are versioned along with the -source. - -By default, the script will run [`bootstrap`](#bootstrap), look for any Xcode -workspace or project in the working directory, then build all targets/schemes -(as found by `xcodebuild -list`) using [xctool][]. - -You can also specify the schemes to build by passing them into the script: - -```sh -script/cibuild ReactiveCocoa-Mac ReactiveCocoa-iOS -``` - -As with the `bootstrap` script, there are several environment variables that can -be used to customize behavior. They can be set on the command line before -invoking the script, or the defaults changed within the script directly. - -## Getting Started - -To add the scripts to your project, read the contents of this repository into -a `script` folder: - -``` -$ git remote add objc-build-scripts https://github.com/jspahrsummers/objc-build-scripts.git -$ git fetch objc-build-scripts -$ git read-tree --prefix=script/ -u objc-build-scripts/master -``` - -Then commit the changes, to incorporate the scripts into your own repository's -history. You can also freely tweak the scripts for your specific project's -needs. - -To merge in upstream changes later: - -``` -$ git fetch -p objc-build-scripts -$ git merge --ff --squash -Xsubtree=script objc-build-scripts/master -``` - -[xctool]: https://github.com/facebook/xctool diff --git a/script/bootstrap b/script/bootstrap index fa19a6001..aca53e814 100755 --- a/script/bootstrap +++ b/script/bootstrap @@ -1,6 +1,6 @@ #!/bin/bash -export SCRIPT_DIR=$(dirname "$0") +export SCRIPT_DIR=$(cd "$(dirname "$0")" && pwd) ## ## Configuration Variables @@ -9,7 +9,8 @@ export SCRIPT_DIR=$(dirname "$0") config () { # A whitespace-separated list of executables that must be present and locatable. - : ${REQUIRED_TOOLS="xctool cmake"} + # These will each be installed through Homebrew if not found. + : ${REQUIRED_TOOLS="cmake libssh2 libtool autoconf automake pkg-config"} export REQUIRED_TOOLS } @@ -22,12 +23,6 @@ main () { config - if [ -n "$REQUIRED_TOOLS" ] - then - echo "*** Checking dependencies..." - check_deps - fi - local submodules=$(git submodule status) local result=$? @@ -41,39 +36,50 @@ main () echo "*** Updating submodules..." update_submodules fi + + if [ -n "$REQUIRED_TOOLS" ] + then + echo "*** Checking dependencies..." + check_deps + fi } check_deps () { - for tool in $REQUIRED_TOOLS - do - which -s "$tool" - if [ "$?" -ne "0" ] - then - echo "*** Error: $tool not found. Please install it and bootstrap again." - exit 1 - fi - done + # Check if Homebrew is installed + which -s brew + local result=$? + + if [ "$result" -ne "0" ] + then + echo + echo "Homebrew is not installed (http://brew.sh). You will need to manually ensure the following tools are installed:" + echo " $REQUIRED_TOOLS" + echo + echo "Additionally, the following libssh2 files must be symlinked under /usr/local:" + echo " lib/libssh2.a include/libssh2.h include/libssh2_sftp.h include/libssh2_publickey.h" + exit $result + fi # Ensure that we have libgit2's dependencies installed. - installed=`brew list` - libs="libssh2 libtool autoconf automake" + installed=`brew list --formula` - for lib in $libs + for tool in $REQUIRED_TOOLS do # Skip packages that are already installed. - echo "$installed" | grep -q "$lib" && code=$? || code=$? + echo "$installed" | grep -q "$tool" && code=$? || code=$? if [ "$code" -eq "0" ] then + echo "*** $tool is available" continue elif [ "$code" -ne "1" ] then exit $code fi - echo "*** Installing $lib with Homebrew..." - brew install "$lib" + echo "*** Installing $tool with Homebrew..." + brew install "$tool" done brew_prefix=`brew --prefix` @@ -114,7 +120,9 @@ bootstrap_submodule () update_submodules () { - git submodule sync --quiet && git submodule update --init && git submodule foreach --quiet bootstrap_submodule + git submodule sync --quiet && \ + git submodule update --init && \ + git submodule foreach --quiet bootstrap_submodule } export -f bootstrap_submodule diff --git a/script/cibuild b/script/cibuild index bbc1112fe..0897947e5 100755 --- a/script/cibuild +++ b/script/cibuild @@ -1,150 +1,77 @@ -#!/bin/bash +#!/bin/bash -ex +# +# script/cibuild +# ObjectiveGit +# +# Executes the build and runs tests for Mac and iOS. Designed to be invoked by +# Travis as a matrix build so that the two platform builds can run in parallel. +# +# Dependent tools & scripts: +# - script/bootstrap +# - script/update_libssl_ios +# - [xcodebuild](https://developer.apple.com/library/mac/documentation/Darwin/Reference/ManPages/man1/xcodebuild.1.html) +# - xcpretty (gem) +# - xcpretty-travis-formatter (gem) +# +# Environment Variables: +# - SCHEME: specifies which Xcode scheme to build. Set to one of the following: +# - ObjectiveGit Mac +# - ObjectiveGit iOS +# - TRAVIS: indicates when the build is being run by travis, used to invoke +# the xcpretty-travis-formatter gem for output. + +if [ -z "$SCHEME" ]; then + echo "The SCHEME environment variable is empty. Please set this to one of:" + echo "- ObjectiveGit Mac" + echo "- ObjectiveGit iOS" + exit 1 +fi -export SCRIPT_DIR=$(dirname "$0") ## ## Configuration Variables ## -SCHEMES="$@" +set -o pipefail +SCRIPT_DIR=$(cd "$(dirname "$0")" && pwd) +XCWORKSPACE="ObjectiveGitFramework.xcworkspace" +XCODE_OPTIONS=$(RUN_CLANG_STATIC_ANALYZER=NO ONLY_ACTIVE_ARCH=NO CODE_SIGN_IDENTITY="" CODE_SIGNING_REQUIRED=NO) -config () -{ - # The workspace to build. - # - # If not set and no workspace is found, the -workspace flag will not be passed - # to `xctool`. - # - # Only one of `XCWORKSPACE` and `XCODEPROJ` needs to be set. The former will - # take precedence. - : ${XCWORKSPACE=$(find_pattern "*.xcworkspace")} - - # The project to build. - # - # If not set and no project is found, the -project flag will not be passed - # to `xctool`. - # - # Only one of `XCWORKSPACE` and `XCODEPROJ` needs to be set. The former will - # take precedence. - : ${XCODEPROJ=$(find_pattern "*.xcodeproj")} - - # A bootstrap script to run before building. - # - # If this file does not exist, it is not considered an error. - : ${BOOTSTRAP="$SCRIPT_DIR/bootstrap"} - - # Extra options to pass to xctool. - : ${XCTOOL_OPTIONS="RUN_CLANG_STATIC_ANALYZER=NO"} - - # A whitespace-separated list of default schemes to build. - # - # Individual names can be quoted to avoid word splitting. - : ${SCHEMES:=$(xcodebuild -list -project "$XCODEPROJ" 2>/dev/null | awk -f "$SCRIPT_DIR/schemes.awk")} - - export XCWORKSPACE - export XCODEPROJ - export BOOTSTRAP - export XCTOOL_OPTIONS - export SCHEMES -} +if [ -n "$TRAVIS" ]; then + # Use a special formatter when running on TravisCI + XCPRETTY_FORMAT_OPTIONS="-f `xcpretty-travis-formatter`" +else + XCPRETTY_FORMAT_OPTIONS="--color" +fi ## ## Build Process ## -main () -{ - config - - if [ -f "$BOOTSTRAP" ] - then - echo "*** Bootstrapping..." - "$BOOTSTRAP" || exit $? - fi - - echo "*** The following schemes will be built:" - echo "$SCHEMES" | xargs -n 1 echo " " - echo - - echo "$SCHEMES" | xargs -n 1 | ( - local status=0 - - while read scheme - do - build_scheme "$scheme" || status=1 - done - - exit $status - ) -} - -find_pattern () -{ - ls -d $1 2>/dev/null | head -n 1 -} - -run_xctool () -{ - if [ -n "$XCWORKSPACE" ] - then - xctool -workspace "$XCWORKSPACE" $XCTOOL_OPTIONS "$@" 2>&1 - elif [ -n "$XCODEPROJ" ] - then - xctool -project "$XCODEPROJ" $XCTOOL_OPTIONS "$@" 2>&1 - else - echo "*** No workspace or project file found." - exit 1 - fi -} - -parse_build () -{ - awk -f "$SCRIPT_DIR/xctool.awk" 2>&1 >/dev/null -} - -build_scheme () -{ - local scheme=$1 - - echo "*** Building and testing $scheme..." - echo - - local sdkflag= - local action=test - - # Determine whether we can run unit tests for this target. - run_xctool -scheme "$scheme" run-tests | parse_build - - local awkstatus=$? - - if [ "$awkstatus" -eq "1" ] - then - # SDK not found, try for iphonesimulator. - sdkflag="-sdk iphonesimulator" - - # Determine whether the unit tests will run with iphonesimulator - run_xctool $sdkflag -scheme "$scheme" run-tests | parse_build - - awkstatus=$? - - if [ "$awkstatus" -ne "0" ] - then - # Unit tests will not run on iphonesimulator. - sdkflag="" - fi - fi - - if [ "$awkstatus" -ne "0" ] - then - # Unit tests aren't supported. - action=build - fi - - run_xctool $sdkflag -scheme "$scheme" $action -} - -export -f build_scheme -export -f run_xctool -export -f parse_build - -main +echo "*** Bootstrapping..." +"$SCRIPT_DIR/bootstrap" + +if [ "$SCHEME" == "ObjectiveGit Mac" ]; then + echo "*** Building and testing $SCHEME..." + echo + + xcodebuild -workspace "$XCWORKSPACE" \ + -scheme "$SCHEME" \ + ${XCODE_OPTIONS[*]} \ + build test \ + 2>&1 #| xcpretty $XCPRETTY_FORMAT_OPTIONS +elif [ "$SCHEME" == "ObjectiveGit iOS" ]; then + echo "*** Prebuilding OpenSSL" + "$SCRIPT_DIR/update_libssl_ios" + + echo "*** Building and testing $SCHEME..." + echo + + xcodebuild -workspace "$XCWORKSPACE" \ + -scheme "$SCHEME" \ + -destination "platform=iOS Simulator,name=iPhone 11" \ + -sdk iphonesimulator \ + ${XCODE_OPTIONS[*]} \ + build test \ + 2>&1 #| xcpretty $XCPRETTY_FORMAT_OPTIONS +fi diff --git a/script/clean_externals b/script/clean_externals new file mode 100755 index 000000000..a25b6c530 --- /dev/null +++ b/script/clean_externals @@ -0,0 +1,22 @@ +#!/bin/bash -ex + +# +# clean_externals +# ObjectiveGit +# +# Removes the outputs from the various static library targets. +# Necessary when switching platforms/architectures as Xcode does not clean +# these for you. +# + +# A list of external static libraries included in the SwiftGit2 framework +libraries=( + External/libgit2.a + External/libgit2-ios/libgit2-ios.a + External/libssh2-ios/lib/libssh2-ios.a + External/ios-openssl/lib/libssl.a + External/ios-openssl/lib/libcrypto.a + External/ios-openssl/include +) + +rm -vrf "${libraries[@]}" diff --git a/script/ios_build_functions.sh b/script/ios_build_functions.sh index 36f5b14c7..515ca81b1 100755 --- a/script/ios_build_functions.sh +++ b/script/ios_build_functions.sh @@ -1,6 +1,6 @@ #!/bin/bash -SCRIPT_DIR=$(dirname "$0") +SCRIPT_DIR=$(cd "$(dirname "$0")" && pwd) source "${SCRIPT_DIR}/xcode_functions.sh" function setup_build_environment () @@ -9,7 +9,7 @@ function setup_build_environment () # e.g. via brew. Xcode's Run Script phase doesn't seem to honor # ~/.MacOSX/environment.plist PATH="/usr/local/bin:/opt/boxen/homebrew/bin:$PATH" - + pushd "$SCRIPT_DIR/.." > /dev/null ROOT_PATH="$PWD" popd > /dev/null @@ -22,7 +22,7 @@ function setup_build_environment () MACOSX_DEPLOYMENT_TARGET="" XCODE_MAJOR_VERSION=$(xcode_major_version) - + CAN_BUILD_64BIT="0" # If IPHONEOS_DEPLOYMENT_TARGET has not been specified @@ -32,7 +32,7 @@ function setup_build_environment () then IPHONEOS_DEPLOYMENT_TARGET="6.0" fi - + # Determine if we can be building 64-bit binaries if [ "${XCODE_MAJOR_VERSION}" -ge "5" ] && [ $(echo ${IPHONEOS_DEPLOYMENT_TARGET} '>=' 6.0 | bc -l) == "1" ] then @@ -46,12 +46,19 @@ function setup_build_environment () # builds to be first ARCHS="x86_64 ${ARCHS} arm64" fi + + # Setup a shared area for our build artifacts + INSTALL_PATH="${ROOT_PATH}/External/build" + mkdir -p "${INSTALL_PATH}" + mkdir -p "${INSTALL_PATH}/log" + mkdir -p "${INSTALL_PATH}/include" + mkdir -p "${INSTALL_PATH}/lib/pkgconfig" } function build_all_archs () { setup_build_environment - + local setup=$1 local build_arch=$2 local finish_build=$3 @@ -81,10 +88,17 @@ function build_all_archs () SDKNAME="${PLATFORM}${SDKVERSION}" SDKROOT="$(ios_sdk_path ${SDKNAME})" - + + LOG="${INSTALL_PATH}/log/${LIBRARY_NAME}-${ARCH}.log" + [ -f "${LOG}" ] && rm "${LOG}" + echo "Building ${LIBRARY_NAME} for ${SDKNAME} ${ARCH}" + echo "Build log can be found in ${LOG}" echo "Please stand by..." + ARCH_INSTALL_PATH="${INSTALL_PATH}/${SDKNAME}-${ARCH}.sdk" + mkdir -p "${ARCH_INSTALL_PATH}" + # run the per arch build command eval $build_arch done diff --git a/script/pkg-config-static b/script/pkg-config-static new file mode 100755 index 000000000..64c6ea205 --- /dev/null +++ b/script/pkg-config-static @@ -0,0 +1,2 @@ +#!/bin/sh +pkg-config --static "$@" diff --git a/script/repackage-dylibs.rb b/script/repackage-dylibs.rb new file mode 100755 index 000000000..3af9ef430 --- /dev/null +++ b/script/repackage-dylibs.rb @@ -0,0 +1,124 @@ +#!/usr/bin/ruby + +# This script looks up an executable's list of shared libraries, copies +# non-standard ones (ie. anything not under /usr or /System/) into the target's +# bundle and updates the executable install_name to point to the "packaged" +# version. + +# Usage: +# Add the script as a Run Script build phase in the target using Xcode. + +# FIXMEs: +# - only handles dylibs +# - only tested against a framework target +# - doesn't care about codesigning + + +require 'fileutils' +require 'ostruct' + +def err(msg) + puts "error: " + msg + exit 1 +end + +def warn(msg) + puts "warning: " + msg +end + +def note(msg) + puts "note: " + msg +end + +envvars = %w( + TARGET_BUILD_DIR + EXECUTABLE_PATH + FRAMEWORKS_FOLDER_PATH +) + +envvars.each do |var| + raise "Must be run in an Xcode Run Phase" unless ENV[var] + Kernel.const_set var, ENV[var] +end + +TARGET_EXECUTABLE_PATH = File.join(TARGET_BUILD_DIR, EXECUTABLE_PATH) +TARGET_FRAMEWORKS_PATH = File.join(TARGET_BUILD_DIR, FRAMEWORKS_FOLDER_PATH) + +def extract_link_dependencies(executable) + deps = `otool -L "#{executable}"` + + lines = deps.split("\n").map(&:strip) + lines.shift + # lines.shift + lines.map do |dep| + path, compat, current = /^(.*) \(compatibility version (.*), current version (.*)\)$/.match(dep)[1..3] + err "Failed to parse #{dep}" if path.nil? + + dep = OpenStruct.new + dep.is_self = (File.basename(path) == File.basename(executable)) + dep.executable = executable + dep.install_name = path + dep.current_version = current + dep.compat_version = compat + dep.type = File.extname(path) + dep.name = File.basename(path) + dep.is_packaged = !!(dep.install_name =~ /^@rpath/) + dep.path = if dep.install_name =~ /^@rpath/ + File.join(TARGET_FRAMEWORKS_PATH, dep.name) + else + dep.install_name + end + + dep + end +end + +def repackage_dependency(dep) + return if dep.is_self or dep.is_packaged or dep.path =~ /^(\/usr\/lib|\/System\/Library)/ + + note "Packaging #{dep.name}…" + + FileUtils.mkdir(TARGET_FRAMEWORKS_PATH) unless Dir.exist?(TARGET_FRAMEWORKS_PATH) + packaged_path = File.join(TARGET_FRAMEWORKS_PATH, dep.name) + + case dep.type + when ".dylib" + if File.exist? packaged_path + warn "#{dep.path} already in Frameworks directory, removing" + FileUtils.rm packaged_path + end + + note "Copying #{dep[:path]} to TARGET_FRAMEWORKS_PATH" + FileUtils.cp dep[:path], TARGET_FRAMEWORKS_PATH + FileUtils.chmod "u=rw", packaged_path + + out = `install_name_tool -change "#{dep.path}" "@rpath/#{dep.name}" "#{dep.executable}"` + if $? != 0 + err "install_name_tool failed with error #{$?}:\n#{out}" + end + + dep.path = packaged_path + dep.install_name = "@rpath/#{dep.name}" + dep.is_packaged = true + else + warn "Unhandled type #{dep.type} for #{dep.path}, ignoring" + end +end + +def fix_install_id(dep) + note "Fixing #{dep.name} install_name id…" + out = `install_name_tool -id "@rpath/#{dep.name}" "#{dep.executable}"` + if $? != 0 + err "install_name_tool failed with error #{$?}:\n#{out}" + end +end + +deps = extract_link_dependencies(TARGET_EXECUTABLE_PATH) +while (dep = deps.shift) do + repackage_dependency dep + fix_install_id dep if dep.is_self and dep.executable != TARGET_EXECUTABLE_PATH + deps += extract_link_dependencies(dep[:path]) if dep.is_packaged and not dep.is_self +end + +note "Packaging done" +exit 0 diff --git a/script/schemes.awk b/script/schemes.awk deleted file mode 100644 index 4c94df914..000000000 --- a/script/schemes.awk +++ /dev/null @@ -1,10 +0,0 @@ -BEGIN { - FS = "\n"; -} - -/Schemes:/ { - while (getline && $0 != "") { - sub(/^ +/, ""); - print "'" $0 "'"; - } -} diff --git a/script/targets.awk b/script/targets.awk deleted file mode 100644 index 117660dcd..000000000 --- a/script/targets.awk +++ /dev/null @@ -1,12 +0,0 @@ -BEGIN { - FS = "\n"; -} - -/Targets:/ { - while (getline && $0 != "") { - if ($0 ~ /Tests/) continue; - - sub(/^ +/, ""); - print "'" $0 "'"; - } -} diff --git a/script/update_libgit2 b/script/update_libgit2 index 1b8742357..2c89cec38 100755 --- a/script/update_libgit2 +++ b/script/update_libgit2 @@ -7,7 +7,7 @@ set -e # ~/.MacOSX/environment.plist PATH="/usr/local/bin:$PATH" -if [ "External/libgit2.a" -nt "External/libgit2" ] +if [ "External/libgit2-mac.a" -nt "External/libgit2" ] then echo "No update needed." exit 0 @@ -22,13 +22,20 @@ fi mkdir build cd build -cmake -DBUILD_SHARED_LIBS:BOOL=OFF -DBUILD_CLAR:BOOL=OFF -DTHREADSAFE:BOOL=ON .. +# OpenSSL is keg-only, so add its pkgconfig location manually +export PKG_CONFIG_PATH=/usr/local/opt/openssl/lib/pkgconfig + +cmake -DBUILD_SHARED_LIBS:BOOL=OFF \ + -DLIBSSH2_INCLUDE_DIRS:PATH=/usr/local/include/ \ + -DBUILD_CLAR:BOOL=OFF \ + -DTHREADSAFE:BOOL=ON \ + .. cmake --build . product="libgit2.a" -install_path="../../${product}" -if [ "${product}" -nt "${install_path}" ]; then - cp -v "${product}" "${install_path}" +install_path="../../" +if [ "libgit2.a" -nt "${install_path}/libgit2-mac.a" ]; then + cp -v "libgit2.a" "${install_path}/libgit2-mac.a" fi echo "libgit2 has been updated." diff --git a/script/update_libgit2_ios b/script/update_libgit2_ios index dfebd3bbd..2586f128b 100755 --- a/script/update_libgit2_ios +++ b/script/update_libgit2_ios @@ -3,76 +3,68 @@ set -e # source the common build functions -SCRIPT_DIR=$(dirname "$0") +SCRIPT_DIR=$(cd "$(dirname "$0")" && pwd) source "${SCRIPT_DIR}/ios_build_functions.sh" function setup () { - if [ "${ROOT_PATH}/External/libgit2-ios/libgit2-ios.a" -nt "${ROOT_PATH}/External/libgit2" ] + if [ "${INSTALL_PATH}/lib/libgit2.a" -nt "${ROOT_PATH}/External/libgit2" ] then echo "No update needed." exit 0 fi LIBRARY_NAME="libgit2" - LIB_PATH="${ROOT_PATH}/External/libgit2-ios" - rm -rf "${LIB_PATH}" - - pushd "${ROOT_PATH}/External/libgit2" > /dev/null } function build_libgit2 () { - rm -rf "build" - mkdir "build" - pushd "build" > /dev/null + # Force CMake to rebuild + rm -rf "${ARCH_INSTALL_PATH}/libgit2" - # LOL Cmake - if [ "${ARCH}" != "i386" ] && [ "${ARCH}" != "x86_64" ] - then - SYS_ROOT="-DCMAKE_OSX_SYSROOT=${SDKROOT}" - fi + mkdir -p "${ARCH_INSTALL_PATH}/libgit2" + pushd "${ARCH_INSTALL_PATH}/libgit2" > /dev/null - # install the each built arch somewhere sane - INSTALL_PREFIX="${LIB_PATH}/${SDKNAME}-${ARCH}.sdk" + # LOL Cmake + SYS_ROOT="-DCMAKE_OSX_SYSROOT=${SDKROOT}" - mkdir -p "${INSTALL_PREFIX}" + # We only want to discover our static library + export PKG_CONFIG="${SCRIPT_DIR}"/pkg-config-static - LOG="${INSTALL_PREFIX}/build-libgit2.log" - echo "$LOG" + # Limit pkg-config to what we're currently expecting it to use + # PKG_CONFIG_PATH="${INSTALL_PATH}/lib/pkgconfig/" + # LDFLAGS="-L $(xcrun --sdk iphoneos --show-sdk-path)/usr/lib" + # export PKG_CONFIG_PATH + # export LDFLAGS - cmake -DCMAKE_C_COMPILER=clang \ + cmake \ -DCMAKE_C_COMPILER_WORKS:BOOL=ON \ -DBUILD_SHARED_LIBS:BOOL=OFF \ - -DOPENSSL_INCLUDE_DIR:PATH=../../External/ios-openssl/include/ \ - -DCMAKE_LIBRARY_PATH:PATH=../../External/libssh2-ios/lib/ \ - -DCMAKE_INCLUDE_PATH:PATH=../../External/libssh2-ios/include/libssh2/ \ - -DOPENSSL_SSL_LIBRARY:FILEPATH=../../External/ios-openssl/lib/libssl.a \ - -DCMAKE_LIBRARY_PATH:PATH="${SDKROOT}/usr/lib/" \ - -DOPENSSL_CRYPTO_LIBRARY:FILEPATH=../../External/ios-openssl/lib/libcrypto.a \ - -DCMAKE_INSTALL_PREFIX:PATH="${INSTALL_PREFIX}/" \ + -DCMAKE_PREFIX_PATH:PATH="${INSTALL_PATH}/" \ + -DPKG_CONFIG_USE_CMAKE_PREFIX_PATH:BOOL=ON \ + -DCMAKE_INSTALL_PREFIX:PATH="${ARCH_INSTALL_PATH}/" \ -DBUILD_CLAR:BOOL=OFF \ -DTHREADSAFE:BOOL=ON \ + -DCURL:BOOL=OFF \ + -DCMAKE_C_FLAGS:STRING="-fembed-bitcode" \ "${SYS_ROOT}" \ -DCMAKE_OSX_ARCHITECTURES:STRING="${ARCH}" \ - .. >> "${LOG}" 2>&1 + "${ROOT_PATH}/External/libgit2" >> "${LOG}" 2>&1 cmake --build . --target install >> "${LOG}" 2>&1 + popd > /dev/null # push the built library into the list - BUILT_LIB_PATHS+=("${INSTALL_PREFIX}/lib/libgit2.a") - popd > /dev/null + BUILT_LIB_PATHS+=("${ARCH_INSTALL_PATH}/lib/libgit2.a") } function fat_binary () { echo "Building fat binary..." - lipo -create "${BUILT_LIB_PATHS[@]}" -output "${ROOT_PATH}/External/libgit2-ios/libgit2-ios.a" + lipo -create "${BUILT_LIB_PATHS[@]}" -output "${INSTALL_PATH}/lib/libgit2.a" echo "Building done." - - popd > /dev/null } build_all_archs setup build_libgit2 fat_binary diff --git a/script/update_libssh2_ios b/script/update_libssh2_ios index 18d8a9fc2..b015047c5 100755 --- a/script/update_libssh2_ios +++ b/script/update_libssh2_ios @@ -3,12 +3,12 @@ set -e # source the common build functions -SCRIPT_DIR=$(dirname "$0") +SCRIPT_DIR=$(cd "$(dirname "$0")" && pwd) source "${SCRIPT_DIR}/ios_build_functions.sh" function setup () { - if [ -f "${ROOT_PATH}/External/libssh2-ios/lib/libssh2-ios.a" ] + if [ -f "${INSTALL_PATH}/lib/libssh2.a" ] then echo "No update needed." exit 0 @@ -16,38 +16,36 @@ function setup () LIBRARY_NAME="libssh2" } -function build_ssh2 () +function build_ssh2 () { - mkdir -p "${ROOT_PATH}/External/libssh2-ios/lib" "${ROOT_PATH}/External/libssh2-ios/lib" "${ROOT_PATH}/External/libssh2-ios/src" + cp -R "${ROOT_PATH}/External/libssh2" "${ARCH_INSTALL_PATH}/libssh2" + pushd "${ARCH_INSTALL_PATH}/libssh2" > /dev/null - rm -rf "${ROOT_PATH}/External/libssh2-ios/src/libssh2" - cp -R "${ROOT_PATH}/External/libssh2" "${ROOT_PATH}/External/libssh2-ios/src/" - pushd "${ROOT_PATH}/External/libssh2-ios/src/libssh2" > /dev/null - - export CFLAGS="-arch ${ARCH} -pipe -no-cpp-precomp -isysroot ${SDKROOT} -miphoneos-version-min=${IPHONEOS_DEPLOYMENT_TARGET}" - export CPPFLAGS="-arch ${ARCH} -pipe -no-cpp-precomp -isysroot ${SDKROOT} -miphoneos-version-min=${IPHONEOS_DEPLOYMENT_TARGET}" - - mkdir -p "${ROOT_PATH}/External/libssh2-ios/bin/${SDKNAME}-${ARCH}.sdk" - LOG="${ROOT_PATH}/External/libssh2-ios/bin/${SDKNAME}-${ARCH}.sdk/build-libssh2.log" - - echo "${LOG}" + export CFLAGS="-arch ${ARCH} -fembed-bitcode -pipe -no-cpp-precomp -isysroot ${SDKROOT} -miphoneos-version-min=${IPHONEOS_DEPLOYMENT_TARGET}" + export CPPFLAGS="-arch ${ARCH} -fembed-bitcode -pipe -no-cpp-precomp -isysroot ${SDKROOT} -miphoneos-version-min=${IPHONEOS_DEPLOYMENT_TARGET}" ./buildconf >> "${LOG}" 2>&1 - ./configure --host=${HOST} --prefix="${ROOT_PATH}/External/libssh2-ios/bin/${SDKNAME}-${ARCH}.sdk" --with-openssl --with-libssl-prefix="${ROOT_PATH}/External/ios-openssl" --disable-shared --enable-static >> "${LOG}" 2>&1 + ./configure --host=${HOST} --prefix="${ARCH_INSTALL_PATH}" --with-openssl --with-libssl-prefix="${INSTALL_PATH}" --disable-shared --enable-static >> "${LOG}" 2>&1 make >> "${LOG}" 2>&1 make install >> "${LOG}" 2>&1 popd > /dev/null - BUILT_LIBS+=("${ROOT_PATH}/External/libssh2-ios/bin/${SDKNAME}-${ARCH}.sdk/lib/libssh2.a") + rm -rf "${ARCH_INSTALL_PATH}/libssh2" + + BUILT_LIBS+=("${ARCH_INSTALL_PATH}/lib/libssh2.a") } function fat_binary () { + echo "Copying headers & pkg-config files" + + cp -r "${ARCH_INSTALL_PATH}"/include/libssh*.h "${INSTALL_PATH}/include/" + cp "${ARCH_INSTALL_PATH}/lib/pkgconfig/libssh2.pc" "${INSTALL_PATH}/lib/pkgconfig/" + perl -i -pe "s|^(prefix=${INSTALL_PATH}).*$|\$1|g" "${INSTALL_PATH}/lib/pkgconfig/libssh2.pc" >> "${LOG}" 2>&1 + echo "Building fat binary..." - lipo -create "${BUILT_LIBS[@]}" -output "${ROOT_PATH}/External/libssh2-ios/lib/libssh2-ios.a" - mkdir -p "${ROOT_PATH}/External/libssh2-ios/include/libssh2" - cp -R "${ROOT_PATH}/External/libssh2-ios/bin/iphonesimulator${SDKVERSION}-i386.sdk/include/libssh2.h" "${ROOT_PATH}/External/libssh2-ios/include/libssh2/" + lipo -create "${BUILT_LIBS[@]}" -output "${INSTALL_PATH}/lib/libssh2.a" echo "Building done." } diff --git a/script/update_libssl_ios b/script/update_libssl_ios index 3d3a209dc..2b4593683 100755 --- a/script/update_libssl_ios +++ b/script/update_libssl_ios @@ -1,35 +1,28 @@ #!/bin/bash +set -e + # source the common build functions SCRIPT_DIR=$(dirname "$0") source "${SCRIPT_DIR}/ios_build_functions.sh" function setup () { - if [ -f "${ROOT_PATH}/External/ios-openssl/lib/libssl.a" ] && [ -f "${ROOT_PATH}/External/ios-openssl/lib/libcrypto.a" ] && [ -d "${ROOT_PATH}/External/ios-openssl/include" ] + if [ -f "${INSTALL_PATH}/lib/libssl.a" -a \ + -f "${INSTALL_PATH}/lib/libcrypto.a" -a \ + -d "${INSTALL_PATH}/include/openssl" ] then echo "No update needed." exit 0 fi LIBRARY_NAME="OpenSSL" - - rm -rf "${ROOT_PATH}/External/ios-openssl/include" "External/ios-openssl/lib" -} - -function cleanup () -{ - rm -rf "/tmp/openssl" - rm -rf "/tmp/openssl-*.log" } -function build_ssl () +function build_ssl () { - rm -rf "/tmp/openssl" - cp -r "${ROOT_PATH}/External/openssl" "/tmp/" - pushd "/tmp/openssl" > /dev/null - - LOG="/tmp/openssl-${ARCH}.log" + cp -r "${ROOT_PATH}/External/openssl" "${ARCH_INSTALL_PATH}/openssl" + pushd "${ARCH_INSTALL_PATH}/openssl" > /dev/null if [ "${ARCH}" == "arm64" ] || [ "${ARCH}" == "x86_64" ] then @@ -40,36 +33,36 @@ function build_ssl () CONFIG="no-gost no-asm" perl -i -pe 's|static volatile sig_atomic_t intr_signal|static volatile int intr_signal|' crypto/ui/ui_openssl.c fi - echo "$LOG" - ./Configure ${HOST} ${CONFIG} --openssldir="/tmp/openssl-${ARCH}" >> "${LOG}" 2>&1 - perl -i -pe "s|^CC= gcc|CC= ${CLANG} -miphoneos-version-min=${IPHONEOS_DEPLOYMENT_TARGET} -arch ${ARCH} |g" Makefile >> "${LOG}" 2>&1 + ./Configure ${HOST} ${CONFIG} --openssldir="${ARCH_INSTALL_PATH}" >> "${LOG}" 2>&1 + perl -i -pe "s|^CC= gcc|CC= ${CLANG} -miphoneos-version-min=${IPHONEOS_DEPLOYMENT_TARGET} -arch ${ARCH} -fembed-bitcode |g" Makefile >> "${LOG}" 2>&1 perl -i -pe "s|^CFLAG= (.*)|CFLAG= -isysroot ${SDKROOT} \$1|g" Makefile >> "${LOG}" 2>&1 make >> "${LOG}" 2>&1 make install_sw >> "${LOG}" 2>&1 popd > /dev/null - rm -rf "/tmp/openssl" - BUILT_CRYPTO_PATHS+=("/tmp/openssl-${ARCH}/lib/libcrypto.a") - BUILT_SSL_PATHS+=("/tmp/openssl-${ARCH}/lib/libssl.a") + rm -rf "${ARCH_INSTALL_PATH}/openssl" + + BUILT_CRYPTO_PATHS+=("${ARCH_INSTALL_PATH}/lib/libcrypto.a") + BUILT_SSL_PATHS+=("${ARCH_INSTALL_PATH}/lib/libssl.a") } function fat_binary () { - echo "Building fat binary..." + echo "Copying headers & pkg-config files" + cp -r "${ARCH_INSTALL_PATH}/include/openssl" "${INSTALL_PATH}/include/" + for pkgfile in "${ARCH_INSTALL_PATH}"/lib/pkgconfig/*.pc; do + cp "${pkgfile}" "${INSTALL_PATH}/lib/pkgconfig/" + perl -i -pe "s|^(prefix=${INSTALL_PATH}).*$|\$1|g" "${INSTALL_PATH}/lib/pkgconfig/$(basename "${pkgfile}")" >> "${LOG}" 2>&1 + done - mkdir -p "${ROOT_PATH}/External/ios-openssl/include" - cp -r /tmp/openssl-i386/include/openssl "${ROOT_PATH}/External/ios-openssl/include/" - - mkdir -p "${ROOT_PATH}/External/ios-openssl/lib" + echo "Building fat binary..." - lipo -create "${BUILT_CRYPTO_PATHS[@]}" -output "${ROOT_PATH}/External/ios-openssl/lib/libcrypto.a" - lipo -create "${BUILT_SSL_PATHS[@]}" -output "${ROOT_PATH}/External/ios-openssl/lib/libssl.a" + lipo -create "${BUILT_CRYPTO_PATHS[@]}" -output "${INSTALL_PATH}/lib/libcrypto.a" + lipo -create "${BUILT_SSL_PATHS[@]}" -output "${INSTALL_PATH}/lib/libssl.a" echo "Building done." } -cleanup build_all_archs setup build_ssl fat_binary -cleanup diff --git a/script/xcode_functions.sh b/script/xcode_functions.sh index e87697c90..2dc7e3b2c 100755 --- a/script/xcode_functions.sh +++ b/script/xcode_functions.sh @@ -14,13 +14,19 @@ function xcode_major_version () xcode_version | awk -F '.' '{ print $1 }' } -# Returns the latest iOS SDK version available -# via xcodebuild +# Returns the latest iOS SDK version available via xcodebuild. function ios_sdk_version () { - # This relies on the fact that the latest iPhone SDK - # is the last thing listed before the Xcode version. - /usr/bin/xcodebuild -version -sdk 2> /dev/null | grep SDKVersion | tail -n 1 | awk '{ print $2 }' + # The grep command produces output like the following, singling out the + # SDKVersion of just the iPhone* SDKs: + # + # iPhoneOS9.0.sdk - iOS 9.0 (iphoneos9.0) + # SDKVersion: 9.0 + # -- + # iPhoneSimulator9.0.sdk - Simulator - iOS 9.0 (iphonesimulator9.0) + # SDKVersion: 9.0 + + /usr/bin/xcodebuild -version -sdk 2> /dev/null | grep -A 1 '^iPhone' | tail -n 1 | awk '{ print $2 }' } # Returns the path to the specified iOS SDK name diff --git a/script/xcodebuild.awk b/script/xcodebuild.awk deleted file mode 100644 index c746b09aa..000000000 --- a/script/xcodebuild.awk +++ /dev/null @@ -1,35 +0,0 @@ -# Exit statuses: -# -# 0 - No errors found. -# 1 - Build or test failure. Errors will be logged automatically. -# 2 - Untestable target. Retry with the "build" action. - -BEGIN { - status = 0; -} - -{ - print; - fflush(stdout); -} - -/is not valid for Testing/ { - exit 2; -} - -/[0-9]+: (error|warning):/ { - errors = errors $0 "\n"; -} - -/(TEST|BUILD) FAILED/ { - status = 1; -} - -END { - if (length(errors) > 0) { - print "\n*** All errors:\n" errors; - } - - fflush(stdout); - exit status; -} diff --git a/script/xctool.awk b/script/xctool.awk deleted file mode 100644 index f6132589d..000000000 --- a/script/xctool.awk +++ /dev/null @@ -1,25 +0,0 @@ -# Exit statuses: -# -# 0 - No errors found. -# 1 - Wrong SDK. Retry with SDK `iphonesimulator`. -# 2 - Missing target. - -BEGIN { - status = 0; -} - -{ - print; -} - -/Testing with the '(.+)' SDK is not yet supported/ { - status = 1; -} - -/does not contain a target named/ { - status = 2; -} - -END { - exit status; -}