Beispiel #1
0
        public void CloneRepo()
        {
            var scd = BuildSelfCleaningDirectory();
            CloneOptions options = new CloneOptions();
            var credentials = new UsernamePasswordCredentials();
            credentials.Username = Constants.Identity.Name;
            credentials.Password = "******";
            options.CredentialsProvider += (url, fromUrl, types) => credentials;

            string clonedRepoPath = Repository.Clone(testUrl, scd.DirectoryPath, options);
            string file = Path.Combine(scd.DirectoryPath, "testpush.txt");
            var rbg = new RandomBufferGenerator(30000);
            using (var repo = new Repository(clonedRepoPath)) {
                for (int i = 0; i < 1; i++) {
                    var network = repo.Network.Remotes.First();
                    FetchOptions fetchOptions = new FetchOptions();
                    fetchOptions.CredentialsProvider += (url, fromUrl, types) => credentials;
                    repo.Fetch(network.Name, fetchOptions);

                    File.WriteAllBytes(file, rbg.GenerateBufferFromSeed(30000));
                    repo.Stage(file);
                    Signature author = Constants.Signature;

                    Commit commit = repo.Commit($"Here's a commit {i + 1} i made!", author, author);
                    PushOptions pushOptions = new PushOptions();
                    pushOptions.CredentialsProvider += (url, fromUrl, types) => credentials;
                    repo.Network.Push(repo.Branches["master"], pushOptions);
                }
            }
        }
Beispiel #2
0
        private static void Main(string[] args)
        {
            var result = CommandLine.Parser.Default.ParseArguments<Options>(args);
              if (!result.Errors.Any())
              {
            string url = result.Value.Repository;

            var brancOption = result.Value.Branch;
            var branchSepIndex = brancOption.IndexOf('/');
            if (branchSepIndex > 0)
            {
              var credentials = new UsernamePasswordCredentials
            {
              Username = result.Value.UserName,
              Password = result.Value.Password
            };
              CredentialsHandler credHandler = (s, fromUrl, types) => credentials;

              var remote = brancOption.Substring(0, branchSepIndex);
              var branch = brancOption.Substring(branchSepIndex+1, brancOption.Length - branchSepIndex-1);

              var workingDirectory = result.Value.LocalRepoPath;

              var isLocalRepoExist = Repository.Discover(workingDirectory);
              if (isLocalRepoExist == null)
              {
            var cloneOptions = new CloneOptions {CredentialsProvider = credHandler};
            Repository.Clone(url, workingDirectory, cloneOptions);
              }

              Repository repo = null;
              try
              {
            var tagName = result.Value.TagName;
            repo = new Repository(workingDirectory);
            //repo.Fetch(remote, new FetchOptions(){CredentialsProvider = credHandler});
            repo.Network.Pull(new Signature(result.Value.UserName,result.Value.Email, new DateTimeOffset()),
              new PullOptions() { FetchOptions = new FetchOptions() { CredentialsProvider = credHandler } });
            repo.ApplyTag(tagName);
            PushChanges(repo, credHandler, remote, branch, tagName);
            Console.WriteLine("Tagged :{0}", result.Value.TagName);
              }
              catch (Exception ex)
              {
            Console.WriteLine("Error happened {0}", ex.Message);
              }
              finally
              {
            if (repo != null) repo.Dispose();
              }
            }
              }
              Console.ReadLine();
        }
Beispiel #3
0
        string GetGitInfoFromUrl()
        {
            var gitDirectory = Path.Combine(arguments.TargetPath, "_dynamicrepository", ".git");
            if (Directory.Exists(gitDirectory))
            {
                Logger.WriteInfo(string.Format("Deleting existing .git folder from '{0}' to force new checkout from url", gitDirectory));

                DeleteHelper.DeleteGitRepository(gitDirectory);
            }

            Credentials credentials = null;
            var authentication = arguments.Authentication;
            if (!string.IsNullOrWhiteSpace(authentication.Username) && !string.IsNullOrWhiteSpace(authentication.Password))
            {
                Logger.WriteInfo(string.Format("Setting up credentials using name '{0}'", authentication.Username));

                credentials = new UsernamePasswordCredentials
                    {
                        Username = authentication.Username,
                        Password = authentication.Password
                };
            }

            Logger.WriteInfo(string.Format("Retrieving git info from url '{0}'", arguments.TargetUrl));

            Repository.Clone(arguments.TargetUrl, gitDirectory,
                new CloneOptions { IsBare = true, Checkout = false, CredentialsProvider = (url, user, types) => credentials });

            if (!string.IsNullOrWhiteSpace(arguments.TargetBranch))
            {
                // Normalize (download branches) before using the branch
                GitHelper.NormalizeGitDirectory(gitDirectory, arguments.Authentication);

                using (var repository = new Repository(gitDirectory))
                {
                    var targetBranchName = string.Format("refs/heads/{0}", arguments.TargetBranch);
                    if (!string.Equals(repository.Head.CanonicalName, targetBranchName))
                    {
                        Logger.WriteInfo(string.Format("Switching to branch '{0}'", arguments.TargetBranch));

                        repository.Refs.UpdateTarget("HEAD", targetBranchName);
                    }

                    repository.CheckoutFilesIfExist("NextVersion.txt");
                }
            }

            DynamicGitRepositoryPath = gitDirectory;

            return gitDirectory;
        }
        /// <summary>
        /// Acquires credentials.
        /// </summary>
        /// <param name="cred">Receives the credentials if the operation is successful.</param>
        /// <param name="user">The username.</param>
        /// <param name="methods">The credential types allowed. The only supported one is <see cref="UsernamePasswordCredentials"/>. May be empty but should not be null.</param>
        /// <returns>0 if successful; a non-zero error code that came from <see cref="Proxy.git_transport_smart_credentials"/> otherwise.</returns>
        public int AcquireCredentials(out Credentials cred, string user, params Type[] methods)
        {
            // Convert the user-provided types to libgit2's flags
            int allowed = 0;
            foreach (var method in methods)
            {
                if (method == typeof(UsernamePasswordCredentials))
                {
                    allowed |= (int)GitCredentialType.UserPassPlaintext;
                }
                else if (method == typeof(DefaultCredentials))
                {
                    allowed |= (int)GitCredentialType.Default;
                }
                else
                {
                    throw new InvalidOperationException("Unknown type passes as allowed credential");
                }
            }

            IntPtr credHandle = IntPtr.Zero;
            int res = Proxy.git_transport_smart_credentials(out credHandle, Transport, user, allowed);
            if (res != 0)
            {
                cred = null;
                return res;
            }

            if (credHandle == IntPtr.Zero)
            {
                throw new InvalidOperationException("credentials callback indicated success but returned no credentials");
            }

            unsafe
            {
                var baseCred = (GitCredential*) credHandle;
                switch (baseCred->credtype)
                {
                    case GitCredentialType.UserPassPlaintext:
                        cred = UsernamePasswordCredentials.FromNative((GitCredentialUserpass*) credHandle);
                        return 0;
                    case GitCredentialType.Default:
                        cred = new DefaultCredentials();
                        return 0;
                    default:
                        throw new InvalidOperationException("User returned an unkown credential type");
                }
            }
        }
Beispiel #5
0
        /// <summary>
        ///     Pull changes from remote to local, cross fingers no merge pls.
        /// </summary>
        /// <param name="credentials">User:Pass credentials</param>
        public void Pull(UsernamePasswordCredentials credentials)
        {
            using (var repo = new Repository(_LocalRepo))
            {
                var pullOptions = new PullOptions
                {
                    FetchOptions = new FetchOptions
                    {
                        CredentialsProvider = (url, username, types) => credentials
                    }
                };

                repo.Network.Pull(new Signature("Chuck Interface","--", new DateTimeOffset(DateTime.Now)), pullOptions);
            }
        }
        public int AcquireCredentials(out Credentials cred, string user, params Type[] methods)
        {
            // Convert the user-provided types to libgit2's flags
            int allowed = 0;

            foreach (var method in methods)
            {
                if (method == typeof(UsernamePasswordCredentials))
                {
                    allowed |= (int)GitCredentialType.UserPassPlaintext;
                }
                else
                {
                    throw new InvalidOperationException("Unknown type passes as allowed credential");
                }
            }

            IntPtr credHandle = IntPtr.Zero;
            int    res        = Proxy.git_transport_smart_credentials(out credHandle, Transport, user, allowed);

            if (res != 0)
            {
                cred = null;
                return(res);
            }

            var baseCred = credHandle.MarshalAs <GitCredential>();

            switch (baseCred.credtype)
            {
            case GitCredentialType.UserPassPlaintext:
                cred = UsernamePasswordCredentials.FromNative(credHandle.MarshalAs <GitCredentialUserpass>());
                return(0);

            default:
                throw new InvalidOperationException("User returned an unkown credential type");
            }
        }
		public static Credentials TryGet (string url, string userFromUrl, SupportedCredentialTypes types, GitCredentialsType type)
		{
			bool result = true;
			Uri uri = null;

			GitCredentialsState state;
			if (!credState.TryGetValue (type, out state))
				credState [type] = state = new GitCredentialsState ();
			state.UrlUsed = url;

			// We always need to run the TryGet* methods as we need the passphraseItem/passwordItem populated even
			// if the password store contains an invalid password/no password
			if ((types & SupportedCredentialTypes.UsernamePassword) != 0) {
				uri = new Uri (url);
				string username;
				string password;
				if (!state.NativePasswordUsed && TryGetUsernamePassword (uri, out username, out password)) {
					state.NativePasswordUsed = true;
					return new UsernamePasswordCredentials {
						Username = username,
						Password = password
					};
				}
			}

			Credentials cred;
			if ((types & SupportedCredentialTypes.UsernamePassword) != 0)
				cred = new UsernamePasswordCredentials ();
			else {
				// Try ssh-agent on Linux.
				if (!Platform.IsWindows && !state.AgentUsed) {
					bool agentUsable;
					if (!state.AgentForUrl.TryGetValue (url, out agentUsable))
						state.AgentForUrl [url] = agentUsable = true;

					if (agentUsable) {
						state.AgentUsed = true;
						return new SshAgentCredentials {
							Username = userFromUrl,
						};
					}
				}

				int key;
				if (!state.KeyForUrl.TryGetValue (url, out key)) {
					if (state.KeyUsed + 1 < Keys.Count)
						state.KeyUsed++;
					else {
						SelectFileDialog dlg = null;
						bool success = false;

						DispatchService.GuiSyncDispatch (() => {
							dlg = new SelectFileDialog (GettextCatalog.GetString ("Select a private SSH key to use."));
							dlg.ShowHidden = true;
							dlg.CurrentFolder = Environment.GetFolderPath (Environment.SpecialFolder.Personal);
							success = dlg.Run ();
						});
						if (!success || !File.Exists (dlg.SelectedFile + ".pub"))
							throw new VersionControlException (GettextCatalog.GetString ("Invalid credentials were supplied. Aborting operation."));

						cred = new SshUserKeyCredentials {
							Username = userFromUrl,
							Passphrase = "",
							PrivateKey = dlg.SelectedFile,
							PublicKey = dlg.SelectedFile + ".pub",
						};

						if (KeyHasPassphrase (dlg.SelectedFile)) {
							DispatchService.GuiSyncDispatch (delegate {
								using (var credDlg = new CredentialsDialog (url, types, cred))
									result = MessageService.ShowCustomDialog (credDlg) == (int)Gtk.ResponseType.Ok;
							});
						}

						if (result)
							return cred;
						throw new VersionControlException (GettextCatalog.GetString ("Invalid credentials were supplied. Aborting operation."));
					}
				} else
					state.KeyUsed = key;

				cred = new SshUserKeyCredentials {
					Username = userFromUrl,
					Passphrase = "",
					PrivateKey = Keys [state.KeyUsed],
					PublicKey = Keys [state.KeyUsed] + ".pub",
				};
				return cred;
			}

			DispatchService.GuiSyncDispatch (delegate {
				using (var credDlg = new CredentialsDialog (url, types, cred))
					result = MessageService.ShowCustomDialog (credDlg) == (int)Gtk.ResponseType.Ok;
			});

			if (result) {
				if ((types & SupportedCredentialTypes.UsernamePassword) != 0) {
					var upcred = (UsernamePasswordCredentials)cred;
					if (!string.IsNullOrEmpty (upcred.Password)) {
						PasswordService.AddWebUserNameAndPassword (uri, upcred.Username, upcred.Password);
					}
				}
			}

			return cred;
		}
Beispiel #8
0
        static void CloneRepository(string repositoryUrl, string gitDirectory, AuthenticationInfo authentication)
        {
            Credentials credentials = null;
            if (!string.IsNullOrWhiteSpace(authentication.Username) && !string.IsNullOrWhiteSpace(authentication.Password))
            {
                Logger.WriteInfo(string.Format("Setting up credentials using name '{0}'", authentication.Username));

                credentials = new UsernamePasswordCredentials
                {
                    Username = authentication.Username,
                    Password = authentication.Password
                };
            }

            Logger.WriteInfo(string.Format("Retrieving git info from url '{0}'", repositoryUrl));

            try
            {
                var cloneOptions = new CloneOptions
                {
                    Checkout = false,
                    CredentialsProvider = (url, usernameFromUrl, types) => credentials
                };
                var returnedPath = Repository.Clone(repositoryUrl, gitDirectory, cloneOptions);
                Logger.WriteInfo(string.Format("Returned path after repository clone: {0}", returnedPath));
            }
            catch (LibGit2SharpException ex)
            {
                var message = ex.Message;
                if (message.Contains("401"))
                {
                    throw new Exception("Unauthorised: Incorrect username/password");
                }
                if (message.Contains("403"))
                {
                    throw new Exception("Forbidden: Possbily Incorrect username/password");
                }
                if (message.Contains("404"))
                {
                    throw new Exception("Not found: The repository was not found");
                }

                throw new Exception("There was an unknown problem with the Git repository you provided", ex);
            }
        }
        private static IGitRepositoryContextFactory GetRepositoryFactory(bool isRemote, string workingDir, Context context, IFileSystem fileSystem)
        {
            IGitRepositoryContextFactory gitRepoFactory = null;
            if (isRemote)
            {
                // clone repo from the remote url
                var cloneRepoArgs = new GitRemoteRepositoryContextFactory.RemoteRepoArgs();
                cloneRepoArgs.Url = context.Repository.Url;
                cloneRepoArgs.Branch = context.Repository.Branch;

                var credentials = new UsernamePasswordCredentials();
                credentials.Username = context.Repository.Username;
                credentials.Password = context.Repository.Password;

                cloneRepoArgs.Credentials = credentials;
                cloneRepoArgs.DestinationPath = workingDir;

                Log.WriteLine("Cloning a git repo from {0}", cloneRepoArgs.Url);
                gitRepoFactory = new GitRemoteRepositoryContextFactory(cloneRepoArgs, fileSystem);
            }
            else
            {
                gitRepoFactory = new GitLocalRepositoryContextFactory(workingDir, fileSystem);
            }

            return gitRepoFactory;
        }
Beispiel #10
0
        static string CreateDynamicRepository(string targetPath, Authentication authentication, string repositoryUrl, string targetBranch, bool noFetch)
        {
            Logger.WriteInfo(string.Format("Creating dynamic repository at '{0}'", targetPath));

            var gitDirectory = Path.Combine(targetPath, ".git");
            if (Directory.Exists(targetPath))
            {
                Logger.WriteInfo("Git repository already exists");
                GitHelper.NormalizeGitDirectory(gitDirectory, authentication, noFetch);
                Logger.WriteInfo(string.Format("Updating branch '{0}'", targetBranch));
                using (var repo = new Repository(targetPath))
                {
                    if (string.IsNullOrWhiteSpace(targetBranch))
                    {
                        throw new Exception("Dynamic Git repositories must have a target branch (/b)");
                    }
                    var targetGitBranch = repo.Branches[targetBranch];
                    var trackedBranch = targetGitBranch.TrackedBranch;
                    if (trackedBranch == null)
                        throw new InvalidOperationException(string.Format("Expecting {0} to have a remote tracking branch", targetBranch));

                    targetGitBranch.Checkout();
                    repo.Reset(ResetMode.Hard, trackedBranch.Tip);
                }

                return gitDirectory;
            }

            Credentials credentials = null;
            if (!string.IsNullOrWhiteSpace(authentication.Username) && !string.IsNullOrWhiteSpace(authentication.Password))
            {
                Logger.WriteInfo(string.Format("Setting up credentials using name '{0}'", authentication.Username));

                credentials = new UsernamePasswordCredentials
                {
                    Username = authentication.Username,
                    Password = authentication.Password
                };
            }

            Logger.WriteInfo(string.Format("Retrieving git info from url '{0}'", repositoryUrl));

            CloneRepository(repositoryUrl, gitDirectory, credentials);

            // Normalize (download branches) before using the branch
            GitHelper.NormalizeGitDirectory(gitDirectory, authentication, noFetch);

            using (var repository = new Repository(gitDirectory))
            {
                if (string.IsNullOrWhiteSpace(targetBranch))
                {
                    targetBranch = repository.Head.Name;
                }

                Reference newHead = null;

                var localReference = GetLocalReference(repository, targetBranch);
                if (localReference != null)
                {
                    newHead = localReference;
                }

                if (newHead == null)
                {
                    var remoteReference = GetRemoteReference(repository, targetBranch, repositoryUrl, authentication);
                    if (remoteReference != null)
                    {
                        repository.Network.Fetch(repositoryUrl, new[]
                            {
                                string.Format("{0}:{1}", remoteReference.CanonicalName, targetBranch)
                            });

                        newHead = repository.Refs[string.Format("refs/heads/{0}", targetBranch)];
                    }
                }

                if (newHead != null)
                {
                    Logger.WriteInfo(string.Format("Switching to branch '{0}'", targetBranch));

                    repository.Refs.UpdateTarget(repository.Refs.Head, newHead);
                }
            }

            return gitDirectory;
        }
Beispiel #11
0
        private string GetGitInfoFromUrl(Context context, string gitDirectory)
        {
            gitDirectory = Path.Combine(gitDirectory, ".git");
            if (Directory.Exists(gitDirectory))
            {
                Log.Info("Deleting existing .git folder from '{0}' to force new checkout from url", gitDirectory);

                DeleteHelper.DeleteGitRepository(gitDirectory);
            }

            Log.Info("Retrieving git info from url '{0}'", context.TargetUrl);

            Credentials credentials = null;
            var authentication = context.Authentication;
            if (!string.IsNullOrWhiteSpace(authentication.Username) && !string.IsNullOrWhiteSpace(authentication.Password))
            {
                Log.Info("Setting up credentials using name '{0}'", authentication.Username);

                credentials = new UsernamePasswordCredentials
                {
                    Username = authentication.Username,
                    Password = authentication.Password
                };
            }

            var cloneOptions = new CloneOptions
            {
                Checkout = false,
                IsBare = true,
                CredentialsProvider = (url, username, supportedTypes) => credentials
            };

            Repository.Clone(context.TargetUrl, gitDirectory, cloneOptions);

            if (!string.IsNullOrWhiteSpace(context.TargetBranch))
            {
                using (var repository = new Repository(gitDirectory))
                {
                    Reference newHead = null;

                    var localReference = GetLocalReference(repository, context.TargetBranch);
                    if (localReference != null)
                    {
                        newHead = localReference;
                    }

                    if (newHead == null)
                    {
                        var remoteReference = GetRemoteReference(repository, context.TargetBranch, context.TargetUrl);
                        if (remoteReference != null)
                        {
                            repository.Network.Fetch(context.TargetUrl, new[]
                            {
                                string.Format("{0}:{1}", remoteReference.CanonicalName, context.TargetBranch)
                            });

                            newHead = repository.Refs[string.Format("refs/heads/{0}", context.TargetBranch)];
                        }
                    }

                    if (newHead != null)
                    {
                        Log.Info("Switching to branch '{0}'", context.TargetBranch);

                        repository.Refs.UpdateTarget(repository.Refs.Head, newHead);
                    }
                }
            }

            return gitDirectory;
        }
 private CredentialsHandler GetSourceCredentialsHandler()
 {
     var credentials = new UsernamePasswordCredentials()
     {
         Username = SourceUserName,
         Password = SourcePassword
     };
     CredentialsHandler credentialHandler = (_url, _user, _cred) => credentials;
     return credentialHandler;
 }
Beispiel #13
0
        /// <summary>
        ///     Push local changes to remote, no merge conflicts pls....
        /// </summary>
        /// <param name="credentials">The credentials of the user who is pushing this.</param>
        public string Push(UsernamePasswordCredentials credentials)
        {
            using (var repo = new Repository(_LocalRepo))
            {
                var pushOptions = new PushOptions
                {
                    CredentialsProvider = (url, username, types) => credentials
                };

                //: TODO - Add support for choosing which branch
                try
                {
                    repo.Network.Push(repo.Branches["master"], pushOptions);
                }
                catch (LibGit2SharpException e)
                {
                    return e.Message;
                }
            }

            //: No errors!
            return string.Empty;
        }
Beispiel #14
0
        /// <summary>Fetches the latest from the remote, and checks out the remote branch (ie. does not attempt to merge).</summary>
        /// <param name="remoteName">'origin' by default.</param>
        /// <param name="branch">'master' by default</param>
        /// <param name="username">null by default</param>
        /// <param name="password">null by default</param>
        public void FetchLatest(string remoteName="origin", string branch = "master", string username=null, string password=null)
        {
            if (HasChanges) {
                // uh oh ... something has gone awry. We should reset before attempting to fetch changes
                Reset();
            }

            var remote = repository.Network.Remotes[remoteName];

            var options = new FetchOptions() { TagFetchMode = TagFetchMode.None };
            if (!string.IsNullOrWhiteSpace(username)) {
                var creds = new UsernamePasswordCredentials { Username = username, Password = password };
                options.CredentialsProvider = (_url, _user, _cred) => creds;
                repository.Network.Fetch(remote, options: options);
            }
            else {
                repository.Network.Fetch(remote, options:options);
            }

            var remoteBranch = repository.Branches.Single(b => b.Name == string.Format("{0}/{1}", remoteName, branch));

            repository.Checkout(remoteBranch);
        }
Beispiel #15
0
        static string CreateDynamicRepository(string targetPath, Authentication authentication, string repositoryUrl, string targetBranch, bool noFetch)
        {
            var gitDirectory = Path.Combine(targetPath, ".git");
            if (Directory.Exists(targetPath))
            {
                Logger.WriteInfo("Git repository already exists at {0}, skipping clone");

                return gitDirectory;
            }

            Credentials credentials = null;
            if (!string.IsNullOrWhiteSpace(authentication.Username) && !string.IsNullOrWhiteSpace(authentication.Password))
            {
                Logger.WriteInfo(string.Format("Setting up credentials using name '{0}'", authentication.Username));

                credentials = new UsernamePasswordCredentials
                {
                    Username = authentication.Username,
                    Password = authentication.Password
                };
            }

            Logger.WriteInfo(string.Format("Retrieving git info from url '{0}'", repositoryUrl));

            Repository.Clone(repositoryUrl, gitDirectory,
                new CloneOptions
                {
                    IsBare = true,
                    Checkout = false,
                    CredentialsProvider = (url, usernameFromUrl, types) => credentials
                });

            // Normalize (download branches) before using the branch
            GitHelper.NormalizeGitDirectory(gitDirectory, authentication, noFetch);

            using (var repository = new Repository(gitDirectory))
            {
                if (string.IsNullOrWhiteSpace(targetBranch))
                {
                    targetBranch = repository.Head.Name;
                }

                Reference newHead = null;

                var localReference = GetLocalReference(repository, targetBranch);
                if (localReference != null)
                {
                    newHead = localReference;
                }

                if (newHead == null)
                {
                    var remoteReference = GetRemoteReference(repository, targetBranch, repositoryUrl);
                    if (remoteReference != null)
                    {
                        repository.Network.Fetch(repositoryUrl, new[]
                            {
                                string.Format("{0}:{1}", remoteReference.CanonicalName, targetBranch)
                            });

                        newHead = repository.Refs[string.Format("refs/heads/{0}", targetBranch)];
                    }
                }

                if (newHead != null)
                {
                    Logger.WriteInfo(string.Format("Switching to branch '{0}'", targetBranch));

                    repository.Refs.UpdateTarget(repository.Refs.Head, newHead);
                }
            }

            return gitDirectory;
        }