Collection of parameters controlling Fetch behavior.
Inheritance: LibGit2Sharp.FetchOptionsBase
Exemplo n.º 1
1
 /// <summary>
 /// Get's the latest and greatest from remote
 /// </summary>
 /// <param name="gitUser">
 /// The Git User.
 /// </param>
 /// <param name="gitPass">
 /// The Git Pass.
 /// </param>
 /// <returns>
 /// A boolean that signals success
 /// </returns>
 public bool Fetch(string gitUser, string gitPass)
 {
     log.Debug("Fetch on remote repo");
     if (File.Exists(ExternalGitPath))
     {
         string GitOutput = ExecuteGitCommand("pull");
         bool result = Regex.IsMatch(GitOutput, "\\bfatal\\b", RegexOptions.IgnoreCase);
         if (result == true)
         {
             return false;
         }
     }
     else
     {
         try
         {
             var signature = new Signature(
                 "pass4win",
                 "*****@*****.**",
                 new DateTimeOffset(2011, 06, 16, 10, 58, 27, TimeSpan.FromHours(2)));
             var fetchOptions = new FetchOptions
             {
                 CredentialsProvider =
                                            (url, user, cred) =>
                                            new UsernamePasswordCredentials
                                            {
                                                Username = gitUser,
                                                Password = gitPass
                                            }
             };
             var mergeOptions = new MergeOptions();
             var pullOptions = new PullOptions { FetchOptions = fetchOptions, MergeOptions = mergeOptions };
             this.gitRepo.Network.Pull(signature, pullOptions);
         }
         catch (Exception message)
         {
             log.Debug(message);
             return false;
         }
     }
     return true;
 }
        public void Fetch(string remoteName)
        {
            using var repository = new LibGit2Sharp.Repository(Module.WorkingDir);
            var options = new LibGit2Sharp.FetchOptions();

            Commands.Fetch(repository, remoteName, Array.Empty <string>(), options, null);
        }
Exemplo n.º 3
0
        public static void NormalizeGitDirectory(string gitDirectory)
        {
            using (var repo = new Repository(gitDirectory))
            {
                var remote = EnsureOnlyOneRemoteIsDefined(repo);

                Log.Info("Fetching from remote '{0}' using the following refspecs: {1}.",
                    remote.Name, string.Join(", ", remote.FetchRefSpecs.Select(r => r.Specification)));

                var fetchOptions = new FetchOptions();
                repo.Network.Fetch(remote, fetchOptions);

                CreateMissingLocalBranchesFromRemoteTrackingOnes(repo, remote.Name);

                if (!repo.Info.IsHeadDetached)
                {
                    Log.Info("HEAD points at branch '{0}'.", repo.Refs.Head.TargetIdentifier);
                    return;
                }

                Log.Info("HEAD is detached and points at commit '{0}'.", repo.Refs.Head.TargetIdentifier);

                CreateFakeBranchPointingAtThePullRequestTip(repo);
            }
        }
Exemplo n.º 4
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);
                }
            }
        }
Exemplo n.º 5
0
        public Task<List<ISourceItem>> FetchAllFiles(BuildConfig config)
        {

            string gitFolder = config.BuildFolder + "\\git";

            //// temporary hack...
            //// git-pull does not work
            //if (Directory.Exists(gitFolder)) {
            //    Directory.Delete(gitFolder, true);
            //}

            if (!Directory.Exists(gitFolder))
            {
                Directory.CreateDirectory(gitFolder);


                Console.WriteLine("Cloning repository " + config.SourceUrl);

                CloneOptions clone = new CloneOptions();
                clone.CredentialsProvider = CredentialsHandler;
                var rep = Repository.Clone(config.SourceUrl, gitFolder, clone);

                Console.WriteLine("Repository clone successful");
            }
            else {
                Console.WriteLine("Fetching remote Repository");
                var rep = new Repository(gitFolder);
                FetchOptions options = new FetchOptions();
                options.CredentialsProvider = CredentialsHandler;
                Remote remote = rep.Network.Remotes["origin"];

                //Commands.Fetch(rep,remote.Name,)

                //rep.Fetch(remote.Name, options);
                var master = rep.Branches["master"];
                Commands.Pull(rep, new Signature("IISCI", "*****@*****.**", DateTime.Now),  new PullOptions()
                {
                    FetchOptions = options,
                    MergeOptions = new MergeOptions() { 
                        MergeFileFavor = MergeFileFavor.Theirs,
                        CommitOnSuccess = true                        
                    }
                });
                Console.WriteLine("Fetch successful");
            }

            List<ISourceItem> files = new List<ISourceItem>();

            EnumerateFiles( new DirectoryInfo(gitFolder), files, "" );


            Parallel.ForEach(files, file =>
            {
                var md5 = System.Security.Cryptography.MD5.Create();
                ((GitSourceItem)file).Version = Convert.ToBase64String(md5.ComputeHash(File.ReadAllBytes(file.Url)));
            });


            return Task.FromResult(files);
        }
Exemplo n.º 6
0
 internal RemoteCallbacks(FetchOptions fetchOptions)
 {
     Ensure.ArgumentNotNull(fetchOptions, "fetchOptions");
     Progress = fetchOptions.OnProgress;
     DownloadTransferProgress = fetchOptions.OnTransferProgress;
     UpdateTips = fetchOptions.OnUpdateTips;
     Credentials = fetchOptions.Credentials;
 }
Exemplo n.º 7
0
        /// <summary>
        /// Fetch from the <see cref="Remote"/>.
        /// </summary>
        /// <param name="remote">The remote to fetch</param>
        /// <param name="options"><see cref="FetchOptions"/> controlling fetch behavior</param>
        public virtual void Fetch(Remote remote, FetchOptions options = null)
        {
            Ensure.ArgumentNotNull(remote, "remote");

            using (RemoteSafeHandle remoteHandle = Proxy.git_remote_load(repository.Handle, remote.Name, true))
            {
                DoFetch(remoteHandle, options);
            }
        }
Exemplo n.º 8
0
        /// <summary>
        /// Fetch from the <see cref="Remote"/>.
        /// </summary>
        /// <param name="remote">The remote to fetch</param>
        /// <param name="options"><see cref="FetchOptions"/> controlling fetch behavior</param>
        /// <param name="signature">Identity for use when updating the reflog.</param>
        /// <param name="logMessage">Message to use when updating the reflog.</param>
        public virtual void Fetch(Remote remote, FetchOptions options = null,
            Signature signature = null,
            string logMessage = null)
        {
            Ensure.ArgumentNotNull(remote, "remote");

            using (RemoteSafeHandle remoteHandle = Proxy.git_remote_load(repository.Handle, remote.Name, true))
            {
                DoFetch(remoteHandle, options, signature.OrDefault(repository.Config), logMessage);
            }
        }
Exemplo n.º 9
0
 public void Fetch(string remoteName)
 {
     var fetchOptions = new FetchOptions()
     {
         CredentialsProvider = (url, usernameFromUrl, types) => new UsernamePasswordCredentials()
         {
             Username = UserName,
             Password = Password
         }
     };
     Repository.Fetch(remoteName, fetchOptions);
 }
Exemplo n.º 10
0
        static FetchOptions BuildFetchOptions(string username, string password)
        {
            var fetchOptions = new FetchOptions();

            if (!string.IsNullOrEmpty(username))
            {
                fetchOptions.Credentials = new UsernamePasswordCredentials
                {
                    Username = username,
                    Password = password
                };
            }

            return fetchOptions;
        }
        public static FetchOptions ToFetchOptions(this AuthenticationInfo authenticationInfo)
        {
            var fetchOptions = new FetchOptions();

            if (authenticationInfo != null)
            {
                if (!string.IsNullOrEmpty(authenticationInfo.Username))
                {
                    fetchOptions.CredentialsProvider = (url, user, types) => new UsernamePasswordCredentials
                    {
                        Username = authenticationInfo.Username,
                        Password = authenticationInfo.Password
                    };
                }
            }

            return fetchOptions;
        }
Exemplo n.º 12
0
        /// <summary>
        /// Perform a fetch
        /// </summary>
        /// <param name="repository">The repository in which to fetch.</param>
        /// <param name="remote">The remote to fetch from. Either as a remote name or a URL</param>
        /// <param name="options">Fetch options.</param>
        /// <param name="logMessage">Log message for any ref updates.</param>
        /// <param name="refspecs">List of refspecs to apply as active.</param>
        public static void Fetch(Repository repository, string remote, IEnumerable<string> refspecs, FetchOptions options, string logMessage)
        {
            Ensure.ArgumentNotNull(remote, "remote");

            options = options ?? new FetchOptions();
            using (var remoteHandle = RemoteFromNameOrUrl(repository.Handle, remote))
            {

                var callbacks = new RemoteCallbacks(options);
                GitRemoteCallbacks gitCallbacks = callbacks.GenerateCallbacks();

                // It is OK to pass the reference to the GitCallbacks directly here because libgit2 makes a copy of
                // the data in the git_remote_callbacks structure. If, in the future, libgit2 changes its implementation
                // to store a reference to the git_remote_callbacks structure this would introduce a subtle bug
                // where the managed layer could move the git_remote_callbacks to a different location in memory,
                // but libgit2 would still reference the old address.
                //
                // Also, if GitRemoteCallbacks were a class instead of a struct, we would need to guard against
                // GC occuring in between setting the remote callbacks and actual usage in one of the functions afterwords.
                var fetchOptions = new GitFetchOptions
                {
                    RemoteCallbacks = gitCallbacks,
                    download_tags = Proxy.git_remote_autotag(remoteHandle),
                };

                if (options.TagFetchMode.HasValue)
                {
                    fetchOptions.download_tags = options.TagFetchMode.Value;
                }

                if (options.Prune.HasValue)
                {
                    fetchOptions.Prune = options.Prune.Value ? FetchPruneStrategy.Prune : FetchPruneStrategy.NoPrune;
                }
                else
                {
                    fetchOptions.Prune = FetchPruneStrategy.FromConfigurationOrDefault;
                }

                fetchOptions.ProxyOptions = new GitProxyOptions { Version = 1 };

                Proxy.git_remote_fetch(remoteHandle, refspecs, fetchOptions, logMessage);
            }
        }
Exemplo n.º 13
0
        private static void DoFetch(FetchOptions options, RemoteSafeHandle remoteHandle, string logMessage, IEnumerable <string> refspecs)
        {
            Debug.Assert(remoteHandle != null && !remoteHandle.IsClosed && !remoteHandle.IsInvalid);

            options = options ?? new FetchOptions();

            var callbacks = new RemoteCallbacks(options);
            GitRemoteCallbacks gitCallbacks = callbacks.GenerateCallbacks();

            // It is OK to pass the reference to the GitCallbacks directly here because libgit2 makes a copy of
            // the data in the git_remote_callbacks structure. If, in the future, libgit2 changes its implementation
            // to store a reference to the git_remote_callbacks structure this would introduce a subtle bug
            // where the managed layer could move the git_remote_callbacks to a different location in memory,
            // but libgit2 would still reference the old address.
            //
            // Also, if GitRemoteCallbacks were a class instead of a struct, we would need to guard against
            // GC occuring in between setting the remote callbacks and actual usage in one of the functions afterwords.
            var fetchOptions = new GitFetchOptions
            {
                RemoteCallbacks = gitCallbacks,
                download_tags   = Proxy.git_remote_autotag(remoteHandle),
            };

            if (options.TagFetchMode.HasValue)
            {
                fetchOptions.download_tags = options.TagFetchMode.Value;
            }

            if (options.Prune.HasValue)
            {
                fetchOptions.Prune = options.Prune.Value ? FetchPruneStrategy.Prune : FetchPruneStrategy.NoPrune;
            }
            else
            {
                fetchOptions.Prune = FetchPruneStrategy.FromConfigurationOrDefault;
            }

            Proxy.git_remote_fetch(remoteHandle, refspecs, fetchOptions, logMessage);
        }
        public static void BUYLCloneOrUpdateRepository()
        {
            if (!CheckForContentRepositoryDirectory())
            {
                //prg.ShowDialog();
                Directory.CreateDirectory(pathToLocalContentRepository);

                CloneOptions op = new CloneOptions();

                Repository.Clone(urlContentRepository, pathToLocalContentRepository, op);
                //prg.Close();
            }
            else
            {
                using (var repo = new Repository(pathToLocalContentRepository))
                {
                    Remote remote = repo.Network.Remotes["origin"];
                    FetchOptions op = new FetchOptions();
                    repo.Network.Fetch(remote);
                }
            }
        }
Exemplo n.º 15
0
        static void DoFetch(RemoteSafeHandle remoteHandle, FetchOptions options)
        {
            if (options == null)
            {
                options = new FetchOptions();
            }

            if (options.TagFetchMode.HasValue)
            {
                Proxy.git_remote_set_autotag(remoteHandle, options.TagFetchMode.Value);
            }

            var callbacks = new RemoteCallbacks(options);
            GitRemoteCallbacks gitCallbacks = callbacks.GenerateCallbacks();

            // It is OK to pass the reference to the GitCallbacks directly here because libgit2 makes a copy of
            // the data in the git_remote_callbacks structure. If, in the future, libgit2 changes its implementation
            // to store a reference to the git_remote_callbacks structure this would introduce a subtle bug
            // where the managed layer could move the git_remote_callbacks to a different location in memory,
            // but libgit2 would still reference the old address.
            //
            // Also, if GitRemoteCallbacks were a class instead of a struct, we would need to guard against
            // GC occuring in between setting the remote callbacks and actual usage in one of the functions afterwords.
            Proxy.git_remote_set_callbacks(remoteHandle, ref gitCallbacks);

            try
            {
                Proxy.git_remote_connect(remoteHandle, GitDirection.Fetch);
                Proxy.git_remote_download(remoteHandle);
                Proxy.git_remote_update_tips(remoteHandle);
            }
            finally
            {
                Proxy.git_remote_disconnect(remoteHandle);
            }
        }
Exemplo n.º 16
0
        static void DoFetch(RemoteSafeHandle remoteHandle, FetchOptions options, Signature signature, string logMessage)
        {
            if (options == null)
            {
                options = new FetchOptions();
            }

            if (options.TagFetchMode.HasValue)
            {
                Proxy.git_remote_set_autotag(remoteHandle, options.TagFetchMode.Value);
            }

            var callbacks = new RemoteCallbacks(options);
            GitRemoteCallbacks gitCallbacks = callbacks.GenerateCallbacks();

            // It is OK to pass the reference to the GitCallbacks directly here because libgit2 makes a copy of
            // the data in the git_remote_callbacks structure. If, in the future, libgit2 changes its implementation
            // to store a reference to the git_remote_callbacks structure this would introduce a subtle bug
            // where the managed layer could move the git_remote_callbacks to a different location in memory,
            // but libgit2 would still reference the old address.
            //
            // Also, if GitRemoteCallbacks were a class instead of a struct, we would need to guard against
            // GC occuring in between setting the remote callbacks and actual usage in one of the functions afterwords.
            Proxy.git_remote_set_callbacks(remoteHandle, ref gitCallbacks);

            Proxy.git_remote_fetch(remoteHandle, signature, logMessage);
        }
Exemplo n.º 17
0
        /// <summary>
        /// Fetch from the <see cref="Remote"/>, using custom refspecs.
        /// </summary>
        /// <param name="remote">The remote to fetch</param>
        /// <param name="refspecs">Refspecs to use, replacing the remote's fetch refspecs</param>
        /// <param name="options"><see cref="FetchOptions"/> controlling fetch behavior</param>
        public virtual void Fetch(Remote remote, IEnumerable<string> refspecs, FetchOptions options = null)
        {
            Ensure.ArgumentNotNull(remote, "remote");
            Ensure.ArgumentNotNull(refspecs, "refspecs");

            using (RemoteSafeHandle remoteHandle = Proxy.git_remote_load(repository.Handle, remote.Name, true))
            {
                Proxy.git_remote_set_fetch_refspecs(remoteHandle, refspecs);

                DoFetch(remoteHandle, options);
            }
        }
Exemplo n.º 18
0
        /// <summary>
        /// Fetch from a url with a set of fetch refspecs
        /// </summary>
        /// <param name="url">The url to fetch from</param>
        /// <param name="refspecs">The list of resfpecs to use</param>
        /// <param name="options"><see cref="FetchOptions"/> controlling fetch behavior</param>
        /// <param name="signature">Identity for use when updating the reflog.</param>
        /// <param name="logMessage">Message to use when updating the reflog.</param>
        public virtual void Fetch(
            string url,
            IEnumerable<string> refspecs,
            FetchOptions options = null,
            Signature signature = null,
            string logMessage = null)
        {
            Ensure.ArgumentNotNull(url, "url");
            Ensure.ArgumentNotNull(refspecs, "refspecs");

            using (RemoteSafeHandle remoteHandle = Proxy.git_remote_create_anonymous(repository.Handle, url, null))
            {
                Proxy.git_remote_set_fetch_refspecs(remoteHandle, refspecs);

                DoFetch(remoteHandle, options, signature.OrDefault(repository.Config), logMessage);
            }
        }
Exemplo n.º 19
0
 /// <summary>
 /// Fetch from the <see cref="Remote"/>, using custom refspecs.
 /// </summary>
 /// <param name="remote">The remote to fetch</param>
 /// <param name="refspecs">Refspecs to use, replacing the remote's fetch refspecs</param>
 /// <param name="options"><see cref="FetchOptions"/> controlling fetch behavior</param>
 public virtual void Fetch(Remote remote, IEnumerable <string> refspecs, FetchOptions options)
 {
     Fetch(remote, refspecs, options, null);
 }
Exemplo n.º 20
0
 /// <summary>
 /// Fetch from a url with a set of fetch refspecs
 /// </summary>
 /// <param name="url">The url to fetch from</param>
 /// <param name="refspecs">The list of resfpecs to use</param>
 /// <param name="options"><see cref="FetchOptions"/> controlling fetch behavior</param>
 public virtual void Fetch(string url, IEnumerable <string> refspecs, FetchOptions options)
 {
     Fetch(url, refspecs, options, null);
 }
Exemplo n.º 21
0
 public GitClient(IGitHubCredentialProvider credentialProvider)
 {
     pushOptions = new PushOptions { CredentialsProvider = credentialProvider.HandleCredentials };
     fetchOptions = new FetchOptions { CredentialsProvider = credentialProvider.HandleCredentials };
 }
Exemplo n.º 22
0
 /// <summary>
 /// Fetch from the <see cref="Remote"/>.
 /// </summary>
 /// <param name="remote">The remote to fetch</param>
 /// <param name="options"><see cref="FetchOptions"/> controlling fetch behavior</param>
 public virtual void Fetch(Remote remote, FetchOptions options)
 {
     Fetch(remote, options, null);
 }
Exemplo n.º 23
0
 public virtual void Fetch(Remote remote, IEnumerable <string> refspecs, FetchOptions options)
 {
     Commands.Fetch(repository, remote.Name, refspecs, options, null);
 }
Exemplo n.º 24
0
 public virtual void Fetch(Remote remote, FetchOptions options, string logMessage)
 {
     Commands.Fetch(repository, remote.Name, new string[0], options, logMessage);
 }
Exemplo n.º 25
0
        // private helper methods.
        private void NormalizeGitDirectory()
        {
            var remote = EnsureSingleRemoteIsDefined();
            EnsureRepoHasRefSpecs(remote);

            Log.WriteLine("Fetching from remote '{0}' using the following refspecs: {1}.",
                remote.Name, string.Join(", ", remote.FetchRefSpecs.Select(r => r.Specification)));

            var fetchOptions = new FetchOptions();
            fetchOptions.CredentialsProvider = (url, user, types) => credentials;
            Repository.Network.Fetch(remote, fetchOptions);

            CreateMissingLocalBranchesFromRemoteTrackingOnes(remote.Name);
            var headSha = Repository.Refs.Head.TargetIdentifier;

            if (!Repository.Info.IsHeadDetached)
            {
                Log.WriteLine("HEAD points at branch '{0}'.", headSha);
                return;
            }

            Log.WriteLine("HEAD is detached and points at commit '{0}'.", headSha);

            // In order to decide whether a fake branch is required or not, first check to see if any local branches have the same commit SHA of the head SHA.
            // If they do, go ahead and checkout that branch
            // If no, go ahead and check out a new branch, using the known commit SHA as the pointer
            var localBranchesWhereCommitShaIsHead = Repository.Branches.Where(b => !b.IsRemote && b.Tip.Sha == headSha).ToList();

            if (localBranchesWhereCommitShaIsHead.Count > 1)
            {
                var names = string.Join(", ", localBranchesWhereCommitShaIsHead.Select(r => r.CanonicalName));
                var message = string.Format("Found more than one local branch pointing at the commit '{0}'. Unable to determine which one to use ({1}).", headSha, names);
                throw new InvalidOperationException(message);
            }

            if (localBranchesWhereCommitShaIsHead.Count == 0)
            {
                Log.WriteLine("No local branch pointing at the commit '{0}'. Fake branch needs to be created.", headSha);
                CreateFakeBranchPointingAtThePullRequestTip();
            }
            else
            {
                Log.WriteLine("Checking out local branch 'refs/heads/{0}'.", localBranchesWhereCommitShaIsHead[0].Name);
                Repository.Branches[localBranchesWhereCommitShaIsHead[0].Name].Checkout();
            }
        }
Exemplo n.º 26
0
 public virtual void Fetch(Remote remote, FetchOptions options, string logMessage)
 {
     Commands.Fetch(repository, remote.Name, new string[0], options, logMessage);
 }
Exemplo n.º 27
0
        /// <summary>
        /// Fetch from the <see cref="Remote"/>, using custom refspecs.
        /// </summary>
        /// <param name="remote">The remote to fetch</param>
        /// <param name="refspecs">Refspecs to use, replacing the remote's fetch refspecs</param>
        /// <param name="options"><see cref="FetchOptions"/> controlling fetch behavior</param>
        /// <param name="signature">Identity for use when updating the reflog.</param>
        /// <param name="logMessage">Message to use when updating the reflog.</param>
        public virtual void Fetch(Remote remote, IEnumerable<string> refspecs, FetchOptions options = null,
            Signature signature = null,
            string logMessage = null)
        {
            Ensure.ArgumentNotNull(remote, "remote");
            Ensure.ArgumentNotNull(refspecs, "refspecs");

            using (RemoteSafeHandle remoteHandle = Proxy.git_remote_lookup(repository.Handle, remote.Name, true))
            {
                Proxy.git_remote_set_fetch_refspecs(remoteHandle, refspecs);

                DoFetch(remoteHandle, options, signature.OrDefault(repository.Config), logMessage);
            }
        }
Exemplo n.º 28
0
        public frmMain()
        {
            InitializeComponent();
            // Checking for appsettings

            // Do we have a valid password store
            if (Properties.Settings.Default.PassDirectory == "firstrun")
            {
                if (folderBrowserDialog1.ShowDialog() == DialogResult.OK)
                {
                    Properties.Settings.Default.PassDirectory = folderBrowserDialog1.SelectedPath;
                }
                else
                {
                    MessageBox.Show("We need a place to store stuff. Restart the program and try again.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    System.Environment.Exit(1);
                }
            }

            // GPG exe location
            if (Properties.Settings.Default.GPGEXE == "firstrun")
            {
                if (openFileDialog1.ShowDialog() == DialogResult.OK)
                {
                    Properties.Settings.Default.GPGEXE = openFileDialog1.FileName;
                }
                else
                {
                    MessageBox.Show("We really need GPG2.exe. Restart the program and try again.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    System.Environment.Exit(1);
                }
            }

            //checking git status
            if (!Repository.IsValid(Properties.Settings.Default.PassDirectory))
            {
                string value = "";
                // Do we have a remote
                if (InputBox.Show("Enter the remote git repo or blank for no remote", "Remote Git (HTTPS):", ref value) == DialogResult.OK)
                {
                    Properties.Settings.Default.GitRemote = value;
                    if (Properties.Settings.Default.GitRemote != "")
                    {
                        // Get username and password
                        value = "";
                        if (InputBox.Show("Username", "Remote Username:"******"";
                            if (InputBox.Show("Password", "Remote Password:"******"Couldn't connect to remote git repository. Restart the program and try again.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                                    System.Environment.Exit(1);
                                }
                                // save encrypted version of user and pass for git
                                Properties.Settings.Default.GitUser = EncryptConfig(GitUsername, "pass4win");
                                Properties.Settings.Default.GitPass = EncryptConfig(GitPassword, "pass4win");
                            }
                        }
                    }
                }
                // Checking if the remote is cloned succesfull
                if (!Repository.IsValid(Properties.Settings.Default.PassDirectory))
                {
                    // creating new Git
                    Repository.Init(Properties.Settings.Default.PassDirectory);
                    Properties.Settings.Default.GitUser = EncryptConfig("RandomGarbage", "pass4win");
                    Properties.Settings.Default.GitPass = EncryptConfig("RandomGarbage", "pass4win");
                }
            }
            else
            {
                // so we have a repository let's load the user/pass
                if (Properties.Settings.Default.GitUser != "")
                {
                    GitUsername = DecryptConfig(Properties.Settings.Default.GitUser, "pass4win");
                    GitPassword = DecryptConfig(Properties.Settings.Default.GitPass, "pass4win");
                }
                else
                {
                    string value = "";
                    if (InputBox.Show("Username", "Remote Username:"******"";
                        if (InputBox.Show("Password", "Remote Password:"******"We really need a username. Restart the program and try again.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        System.Environment.Exit(1);
                    }
                    if (GitPassword == null)
                    {
                        MessageBox.Show("We really need a password. Restart the program and try again.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        System.Environment.Exit(1);
                    }
                    Properties.Settings.Default.GitUser = EncryptConfig(GitUsername, "pass4win");
                    Properties.Settings.Default.GitPass = EncryptConfig(GitPassword, "pass4win");
                }

                // Check if we have the latest
                using (var repo = new Repository(Properties.Settings.Default.PassDirectory))
                {
                    Signature Signature = new Signature("pass4win","*****@*****.**", new DateTimeOffset(2011, 06, 16, 10, 58, 27, TimeSpan.FromHours(2)));
                    FetchOptions fetchOptions = new FetchOptions();
                    fetchOptions.CredentialsProvider = (_url, _user, _cred) => new UsernamePasswordCredentials
                                        {
                                            Username = GitUsername,
                                            Password = GitPassword
                                        };
                    MergeOptions mergeOptions = new MergeOptions();
                    PullOptions pullOptions = new PullOptions();
                    pullOptions.FetchOptions = fetchOptions;
                    pullOptions.MergeOptions = mergeOptions;
                    MergeResult mergeResult = repo.Network.Pull(Signature, pullOptions);
                }

            }

            // Init GPG if needed
            string gpgfile = Properties.Settings.Default.PassDirectory;
            gpgfile += "\\.gpg-id";
            // Check if we need to init the directory
            if (!File.Exists(gpgfile))
            {
                Directory.CreateDirectory(Path.GetDirectoryName(gpgfile));
                KeySelect newKeySelect = new KeySelect();
                if (newKeySelect.ShowDialog() == DialogResult.OK)
                {
                    using (StreamWriter w = new StreamWriter(gpgfile))
                    {
                        w.Write(newKeySelect.gpgkey);
                    }
                    using (var repo = new Repository(Properties.Settings.Default.PassDirectory))
                    {
                        repo.Stage(gpgfile);
                        repo.Commit("gpgid added", new Signature("pass4win", "pass4win", System.DateTimeOffset.Now), new Signature("pass4win", "pass4win", System.DateTimeOffset.Now));
                    }
                }
                else
                {
                    MessageBox.Show("Need key...... Restart the program and try again.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    System.Environment.Exit(1);
                }
            }
            // Setting the exe location for the GPG Dll
            GpgInterface.ExePath = Properties.Settings.Default.GPGEXE;

            // saving settings
            Properties.Settings.Default.Save();

            // Setting up datagrid
            dt.Columns.Add("colPath", typeof(string));
            dt.Columns.Add("colText", typeof(string));

            ListDirectory(new DirectoryInfo(Properties.Settings.Default.PassDirectory), "");

            dataPass.DataSource = dt.DefaultView;
            dataPass.Columns[0].Visible=false;
        }
Exemplo n.º 29
0
        /// <summary>
        /// Fetch from a url with a set of fetch refspecs
        /// </summary>
        /// <param name="url">The url to fetch from</param>
        /// <param name="refspecs">The list of resfpecs to use</param>
        /// <param name="options"><see cref="FetchOptions"/> controlling fetch behavior</param>
        public virtual void Fetch(
            string url,
            IEnumerable<string> refspecs,
            FetchOptions options = null)
        {
            Ensure.ArgumentNotNull(url, "url");
            Ensure.ArgumentNotNull(refspecs, "refspecs");

            using (RemoteSafeHandle remoteHandle = Proxy.git_remote_create_inmemory(repository.Handle, null, url))
            {
                Proxy.git_remote_set_fetch_refspecs(remoteHandle, refspecs);

                DoFetch(remoteHandle, options);
            }
        }
Exemplo n.º 30
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);
        }
Exemplo n.º 31
0
 public virtual void Fetch(Remote remote, IEnumerable<string> refspecs, FetchOptions options)
 {
     Commands.Fetch(repository, remote.Name, refspecs, options, null);
 }
Exemplo n.º 32
0
        public ModificationViewModel(IScreen screen, ICredentialStore store, IObservable<RepositoryModel> repository)
        {
            this.disposables = new List<IDisposable>();
            this.fileSystem = new FileSystemObservable();

            this.refreshCommand = ReactiveCommand.Create();

            var samples =
                Observable.Interval(TimeSpan.FromSeconds(60))
                .Select(i => new object())
                .Merge(this.refreshCommand.Select(i => new object()))
                .Merge(repository.Delay(TimeSpan.FromSeconds(1)).Select(i => new object()));

            var distinctRepository = repository.DistinctUntilChanged(r => r.Path);

            distinctRepository.MapToMember(this, vm => vm.currentRepositoryModel);
            distinctRepository.Select(_ => _.Path).MapToMember(this, vm => vm.fileSystem.Path);

            var activeBranch = repository
                .SelectMany(rm => rm.WhenAny(vm => vm.CurrentBranch, change => change.GetValue()))
                .SampleEx(samples);

            activeBranch
                .ObserveOn(System.Reactive.Concurrency.TaskPoolScheduler.Default)
                .SubscribeOn(System.Reactive.Concurrency.TaskPoolScheduler.Default)
                .Subscribe(branch =>
                {
                    if (branch.IsTracking)
                    {
                        //Fetch repository status.
                        var currentRemote = branch.Remote;

                        var refSpecs = this.currentRepositoryModel.Repository.Network.Remotes.Select(r =>
                                    new
                                    {
                                        FetchRefSpecs = r.FetchRefSpecs
                                                            .Where(frs => frs.Direction == RefSpecDirection.Fetch)
                                                            .Select(frs => frs.Specification),
                                        Remote = r
                                    }
                                );
                        var credentialProvider = new CredentialProvider(screen, store);

                        foreach (var item in refSpecs)
                        {
                            FetchOptions options = new FetchOptions() { CredentialsProvider = credentialProvider.CredentialHandler };
                            try
                            {
                                this.currentRepositoryModel.Repository.Network.Fetch(item.Remote, item.FetchRefSpecs, options);
                            }
                            catch { }
                        }
                    }
                });

            activeBranch
                .Select(b => b.TrackingDetails).Subscribe(_ =>
                {
                    this.Ahead = (_.AheadBy.HasValue) ? _.AheadBy.Value : 0;
                    this.Behind = (_.BehindBy.HasValue) ? _.BehindBy.Value : 0;
                });

            var activeBranchFileStatus =
                activeBranch.AnonymousMerge(fileSystem, 0)
                .AnonymousMerge(this.refreshCommand.AsObservable(), 0)
                .Throttle(TimeSpan.FromSeconds(5))
                .Select(branch =>
                {
                    var opts = new LibGit2Sharp.StatusOptions();

                    opts.DetectRenamesInIndex = true;
                    opts.DetectRenamesInWorkDir = true;
                    opts.Show = StatusShowOption.IndexAndWorkDir;

                    return this.currentRepositoryModel.Repository.RetrieveStatus(opts);
                });

            this.files = new DeltaViewModel<int>
            (
                activeBranchFileStatus.Select(s => s.Modified.Count()),
                activeBranchFileStatus.Select(s => s.Added.Count() + s.Untracked.Count()),
                activeBranchFileStatus.Select(s => s.Removed.Count())
            );

            ConfigureLineChanges(activeBranch);

            ConfigureCommitCommands();

            this.thresholds = new Thresholds(
                this.ObservableForProperty(vm => vm.Behind, false, false).Select(change => change.GetValue()),
                this.ObservableForProperty(vm => vm.Ahead).Select(change => change.GetValue()),
                this.ObservableForProperty(vm => vm.LinesAdded).Select(change => change.GetValue()),
                this.ObservableForProperty(vm => vm.LinesRemoved).Select(change => change.GetValue()),
                this.Files.ObservableForProperty(vm => vm.Added).Select(change => change.GetValue()),
                this.Files.ObservableForProperty(vm => vm.Removed).Select(change => change.GetValue()));
        }
Exemplo n.º 33
0
        public virtual void Fetch(Remote remote, IEnumerable<string> refspecs, FetchOptions options, string logMessage)
        {
            Ensure.ArgumentNotNull(remote, "remote");
            Ensure.ArgumentNotNull(refspecs, "refspecs");

            Commands.Fetch(repository, remote.Name, refspecs, options, logMessage);
        }
Exemplo n.º 34
0
 /// <summary>
 ///     Get's the latest and greatest from remote
 /// </summary>
 /// <returns></returns>
 public bool GitFetch()
 {
     if (Cfg["UseGitRemote"] == true && this.gitRepoOffline == false)
     {
         toolStripOffline.Visible = false;
         using (var repo = new Repository(Cfg["PassDirectory"]))
         {
             var signature = new Signature("pass4win", "*****@*****.**",
                 new DateTimeOffset(2011, 06, 16, 10, 58, 27, TimeSpan.FromHours(2)));
             var fetchOptions = new FetchOptions
             {
                 CredentialsProvider = (url, user, cred) => new UsernamePasswordCredentials
                 {
                     Username = Cfg["GitUser"],
                     Password = DecryptConfig(Cfg["GitPass"], "pass4win")
                 }
             };
             var mergeOptions = new MergeOptions();
             var pullOptions = new PullOptions
             {
                 FetchOptions = fetchOptions,
                 MergeOptions = mergeOptions
             };
             try
             {
                 repo.Network.Pull(signature, pullOptions);
             }
             catch (Exception)
             {
                 return false;
             }
         }
     }
     return true;
 }
Exemplo n.º 35
0
 /// <summary>
 /// Fetch from a url with a set of fetch refspecs
 /// </summary>
 /// <param name="url">The url to fetch from</param>
 /// <param name="refspecs">The list of resfpecs to use</param>
 /// <param name="options"><see cref="FetchOptions"/> controlling fetch behavior</param>
 public virtual void Fetch(string url, IEnumerable<string> refspecs, FetchOptions options)
 {
     Fetch(url, refspecs, options, null);
 }
Exemplo n.º 36
0
        /// <summary>
        /// Fetch from the <see cref="Remote"/>.
        /// </summary>
        /// <param name="remote">The remote to fetch</param>
        /// <param name="options"><see cref="FetchOptions"/> controlling fetch behavior</param>
        /// <param name="logMessage">Message to use when updating the reflog.</param>
        public virtual void Fetch(Remote remote, FetchOptions options, string logMessage)
        {
            Ensure.ArgumentNotNull(remote, "remote");

            DoFetch(repository.Handle, remote, options, logMessage, new string[0]);
        }
Exemplo n.º 37
0
        /// <summary>
        /// Fetch from a url with a set of fetch refspecs
        /// </summary>
        /// <param name="url">The url to fetch from</param>
        /// <param name="refspecs">The list of resfpecs to use</param>
        /// <param name="options"><see cref="FetchOptions"/> controlling fetch behavior</param>
        /// <param name="logMessage">Message to use when updating the reflog.</param>
        public virtual void Fetch(
            string url,
            IEnumerable<string> refspecs,
            FetchOptions options,
            string logMessage)
        {
            Ensure.ArgumentNotNull(url, "url");
            Ensure.ArgumentNotNull(refspecs, "refspecs");

            Commands.Fetch(repository, url, refspecs, options, logMessage);
        }
Exemplo n.º 38
0
 private void setupOptions(string Username, SecureString SecurePassword, string RepoPath, string RepoUrl)
 {
     credentials = new SecureUsernamePasswordCredentials() { Username = Username, Password = SecurePassword };
     var credentialsProvider = new CredentialsHandler((_url, _user, _cred) => new SecureUsernamePasswordCredentials
     {
         Username = Username,
         Password = SecurePassword
     });
     fetchOptions = new FetchOptions() { CredentialsProvider = credentialsProvider };
     pullOptions = new PullOptions() { FetchOptions = fetchOptions };
     pushOptions = new PushOptions() { CredentialsProvider = credentialsProvider };
     cloneOptions = new CloneOptions() { CredentialsProvider = credentialsProvider };
     statusOptions = new StatusOptions() { ExcludeSubmodules = true, IncludeUnaltered = false };
 }
Exemplo n.º 39
0
 public virtual void Fetch(Remote remote, FetchOptions options)
 {
     Commands.Fetch(repository, remote.Name, new string[0], options, null);
 }
Exemplo n.º 40
0
 public virtual void Fetch(Remote remote, FetchOptions options)
 {
     Commands.Fetch(repository, remote.Name, new string[0], options, null);
 }
Exemplo n.º 41
0
        /// <summary>
        /// Perform a fetch
        /// </summary>
        /// <param name="repository">The repository in which to fetch.</param>
        /// <param name="remote">The remote to fetch from. Either as a remote name or a URL</param>
        /// <param name="options">Fetch options.</param>
        /// <param name="logMessage">Log message for any ref updates.</param>
        /// <param name="refspecs">List of refspecs to apply as active.</param>
        public static void Fetch(Repository repository, string remote, IEnumerable <string> refspecs, FetchOptions options, string logMessage)
        {
            Ensure.ArgumentNotNull(remote, "remote");

            options = options ?? new FetchOptions();
            using (var remoteHandle = RemoteFromNameOrUrl(repository.Handle, remote))
            {
                var callbacks = new RemoteCallbacks(options);
                GitRemoteCallbacks gitCallbacks = callbacks.GenerateCallbacks();

                // It is OK to pass the reference to the GitCallbacks directly here because libgit2 makes a copy of
                // the data in the git_remote_callbacks structure. If, in the future, libgit2 changes its implementation
                // to store a reference to the git_remote_callbacks structure this would introduce a subtle bug
                // where the managed layer could move the git_remote_callbacks to a different location in memory,
                // but libgit2 would still reference the old address.
                //
                // Also, if GitRemoteCallbacks were a class instead of a struct, we would need to guard against
                // GC occuring in between setting the remote callbacks and actual usage in one of the functions afterwords.
                var fetchOptions = new GitFetchOptions
                {
                    RemoteCallbacks = gitCallbacks,
                    download_tags   = Proxy.git_remote_autotag(remoteHandle),
                };

                if (options.TagFetchMode.HasValue)
                {
                    fetchOptions.download_tags = options.TagFetchMode.Value;
                }

                if (options.Prune.HasValue)
                {
                    fetchOptions.Prune = options.Prune.Value ? FetchPruneStrategy.Prune : FetchPruneStrategy.NoPrune;
                }
                else
                {
                    fetchOptions.Prune = FetchPruneStrategy.FromConfigurationOrDefault;
                }

                fetchOptions.ProxyOptions = new GitProxyOptions {
                    Version = 1
                };

                Proxy.git_remote_fetch(remoteHandle, refspecs, fetchOptions, logMessage);
            }
        }