示例#1
0
        private static GitStatusOptions CreateStatusOptions(StatusOptions options)
        {
            var coreOptions = new GitStatusOptions
            {
                Version = 1,
                Show    = (GitStatusShow)options.Show,
                Flags   =
                    GitStatusOptionFlags.IncludeIgnored |
                    GitStatusOptionFlags.IncludeUntracked |
                    GitStatusOptionFlags.RecurseUntrackedDirs,
            };

            if (options.DetectRenamesInIndex)
            {
                coreOptions.Flags |=
                    GitStatusOptionFlags.RenamesHeadToIndex |
                    GitStatusOptionFlags.RenamesFromRewrites;
            }

            if (options.DetectRenamesInWorkDir)
            {
                coreOptions.Flags |=
                    GitStatusOptionFlags.RenamesIndexToWorkDir |
                    GitStatusOptionFlags.RenamesFromRewrites;
            }

            if (options.ExcludeSubmodules)
            {
                coreOptions.Flags |=
                    GitStatusOptionFlags.ExcludeSubmodules;
            }

            return(coreOptions);
        }
示例#2
0
        private void CommitCore(string message)
        {
            using var repo = new Git.Repository(Location);
            var statusOptions = new Git.StatusOptions
            {
                DetectRenamesInIndex   = true,
                DetectRenamesInWorkDir = true,
                IncludeIgnored         = false,
                IncludeUntracked       = true,
                RecurseUntrackedDirs   = true,
                RecurseIgnoredDirs     = false
            };

            if (!repo.RetrieveStatus(statusOptions).IsDirty)
            {
                return;
            }

            Git.Commands.Stage(repo, "*");

            var author    = new Git.Signature("JournalCli", "@journalCli", DateTime.Now);
            var committer = author;

            var options = new Git.CommitOptions {
                PrettifyMessage = true
            };
            var commit = repo.Commit(message, author, committer, options);
        }
示例#3
0
        internal RepositoryStatus(Repository repo, StatusOptions options)
        {
            statusEntries = new List <StatusEntry>();

            using (GitStatusOptions coreOptions = CreateStatusOptions(options ?? new StatusOptions()))
                using (StatusListSafeHandle list = Proxy.git_status_list_new(repo.Handle, coreOptions))
                {
                    int count = Proxy.git_status_list_entrycount(list);

                    for (int i = 0; i < count; i++)
                    {
                        StatusEntrySafeHandle e     = Proxy.git_status_byindex(list, i);
                        GitStatusEntry        entry = e.MarshalAsGitStatusEntry();

                        GitDiffDelta deltaHeadToIndex    = null;
                        GitDiffDelta deltaIndexToWorkDir = null;

                        if (entry.HeadToIndexPtr != IntPtr.Zero)
                        {
                            deltaHeadToIndex = entry.HeadToIndexPtr.MarshalAs <GitDiffDelta>();
                        }
                        if (entry.IndexToWorkDirPtr != IntPtr.Zero)
                        {
                            deltaIndexToWorkDir = entry.IndexToWorkDirPtr.MarshalAs <GitDiffDelta>();
                        }

                        AddStatusEntryForDelta(entry.Status, deltaHeadToIndex, deltaIndexToWorkDir);
                    }

                    isDirty = statusEntries.Any(entry => entry.State != FileStatus.Ignored);
                }
        }
示例#4
0
        private static GitStatusOptions CreateStatusOptions(StatusOptions options)
        {
            var coreOptions = new GitStatusOptions
            {
                Version = 1,
                Show    = (GitStatusShow)options.Show,
                Flags   =
                    GitStatusOptionFlags.IncludeIgnored |
                    GitStatusOptionFlags.IncludeUntracked |
                    GitStatusOptionFlags.RecurseUntrackedDirs,
            };

            if (options.DetectRenamesInIndex)
            {
                coreOptions.Flags |=
                    GitStatusOptionFlags.RenamesHeadToIndex |
                    GitStatusOptionFlags.RenamesFromRewrites;
            }

            if (options.DetectRenamesInWorkDir)
            {
                coreOptions.Flags |=
                    GitStatusOptionFlags.RenamesIndexToWorkDir |
                    GitStatusOptionFlags.RenamesFromRewrites;
            }

            if (options.ExcludeSubmodules)
            {
                coreOptions.Flags |=
                    GitStatusOptionFlags.ExcludeSubmodules;
            }

            if (options.RecurseIgnoredDirs)
            {
                coreOptions.Flags |=
                    GitStatusOptionFlags.RecurseIgnoredDirs;
            }

            if (options.PathSpec != null)
            {
                coreOptions.PathSpec = GitStrArrayManaged.BuildFrom(options.PathSpec);
            }

            if (options.DisablePathSpecMatch)
            {
                coreOptions.Flags |=
                    GitStatusOptionFlags.DisablePathspecMatch;
            }

            if (options.IncludeUnaltered)
            {
                coreOptions.Flags |=
                    GitStatusOptionFlags.IncludeUnmodified;
            }

            return(coreOptions);
        }
示例#5
0
        void CheckChangesInGitRepo(DirectoryInfo rootFolder)
        {
            try
            {
                var repo = new Repository(rootFolder.FullName);
                var options = new StatusOptions();
                var repositoryStatus = repo.RetrieveStatus(options);

                if (repositoryStatus.IsDirty)
                    Console.WriteLine("Repo [{0} in {1}] is dirty", rootFolder.Name, rootFolder.Parent.FullName);
            }
            catch (Exception ex)
            {
                Console.WriteLine("Repo [{0}] cannot be read: [{1}]", rootFolder.Name, ex.Message);
            }
        }
示例#6
0
        internal unsafe RepositoryStatus(Repository repo, StatusOptions options)
        {
            statusEntries = new List <StatusEntry>();

            using (GitStatusOptions coreOptions = CreateStatusOptions(options ?? new StatusOptions()))
                using (StatusListHandle list = Proxy.git_status_list_new(repo.Handle, coreOptions))
                {
                    int count = Proxy.git_status_list_entrycount(list);

                    for (int i = 0; i < count; i++)
                    {
                        git_status_entry *entry = Proxy.git_status_byindex(list, i);
                        AddStatusEntryForDelta(entry->status, entry->head_to_index, entry->index_to_workdir);
                    }

                    isDirty = statusEntries.Any(entry => entry.State != FileStatus.Ignored && entry.State != FileStatus.Unaltered);
                }
        }
        /// <summary>
        /// Muestra el estado del indice del control de versiones
        /// </summary>
        /// <returns></returns>
        public RepositoryStatus getStatus()
        {
            //feed.Logs.WriteText("Get status", "Se obtiene el status de " + NombreProyecto);
            try
            {
                if (esRepositorioIniciado())
                {
                    Repo = new Repository(Path);
                    StatusOptions op = new StatusOptions();
                   

                    return Repo.Index.RetrieveStatus();
                }
                else return null;
            }
            catch(Exception ex) {
                return null;
            }
        }
示例#8
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 };
 }
示例#9
0
        /// <summary>
        /// Retrieves the state of all files in the working directory, comparing them against the staging area and the latest commmit.
        /// </summary>
        /// <param name="options">If set, the options that control the status investigation.</param>
        /// <returns>A <see cref="RepositoryStatus"/> holding the state of all the files.</returns>
        public virtual RepositoryStatus RetrieveStatus(StatusOptions options = null)
        {
            ReloadFromDisk();

            return(new RepositoryStatus(repo, options));
        }
示例#10
0
 public virtual RepositoryStatus RetrieveStatus(StatusOptions options = null)
 {
     return(repo.RetrieveStatus(options));
 }
示例#11
0
 public RepositoryStatus RetrieveStatus(StatusOptions options)
 {
     throw new NotImplementedException();
 }
        public void ProcessDirectory(RepositoryConfigurationInfo config)
        {
            if (!Repository.IsValid(config.BaseDir))
            {
                Repository.Init(config.BaseDir);
            }

            using (var repo = new Repository(config.BaseDir))
            {
                // todo, if user.name or user.email are not set in config, set them now!
                if (string.IsNullOrEmpty(repo.Config.Get<string>("user.name").Value))
                    repo.Config.Set("user.name", "gitpusher");

                if (string.IsNullOrEmpty(repo.Config.Get<string>("user.email").Value))
                    repo.Config.Set("user.email", "*****@*****.**");

                repo.Config.Set("diff.renames", "copies");
				repo.Config.Set("http.postBuffer", 524288000);
				
				var retrievalOptions = new StatusOptions {DetectRenamesInWorkDir = true, DetectRenamesInIndex = true};
                RepositoryStatus status = repo.RetrieveStatus(retrievalOptions);
                if (status.IsDirty)
                {
                    bool toCommit = false;
                    foreach (var renamed in status.RenamedInWorkDir)
                    {
                        var oldFileName = renamed.IndexToWorkDirRenameDetails.OldFilePath;
                        repo.Stage(renamed.FilePath);
                        repo.Stage(oldFileName);
                        toCommit = true;
                    }
                    foreach (var untracked in status.Untracked)
                    {
                        repo.Stage(untracked.FilePath);
                        toCommit = true;
                    }
                    foreach (var modified in status.Modified)
                    {
                        repo.Stage(modified.FilePath);
                        toCommit = true;
                    }
                    foreach (var added in status.Added)
                    {
                        repo.Stage(added.FilePath);
                        toCommit = true;
                    }
                    foreach (var missing in status.Missing)
                    {
                        repo.Remove(missing.FilePath);
                        toCommit = true;
                    }

                    if (toCommit || status.Staged.Any())
                    {
                        repo.Commit("GitPusher commit.");
	                    foreach (var rmt in config.Remotes)
	                    {
		                    if (!repo.Network.Remotes.Any(r => r.Name == rmt))
		                    {
			                    FormatLoggerAccessor.Instance().Error($"Remote '{rmt}' not found in git repository. Please check the name with 'git remote -v' and try again.");
			                    continue;
		                    }
	                        var remote = repo.Network.Remotes[rmt];
							var options = new PushOptions();

							//options.CredentialsProvider = new CredentialsHandler((url, usernameFromUrl, types) =>
							//	new DefaultCredentials());

							//new UsernamePasswordCredentials()
							//{
							//    Username = "******",
							//    Password = "******"
							//});

							var pushRefSpec = @"refs/heads/master";
							repo.Network.Push(remote, pushRefSpec, options, null, "GitPusher push");
						}
                    }
                }
            }
        }
        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()));
        }
        private void ConfigureCommitCommands()
        {
            var canCommit = this.Files.WhenAny(vm => vm.Modified, vm => vm.Added, vm => vm.Removed, (mod, add, rem) =>
            {
                return mod.GetValue() > 0 || add.GetValue() > 0 || rem.GetValue() > 0;
            });

            this.commitUntrackedChanges = ReactiveCommand.CreateAsyncTask<CommitResultModel>(canCommit, async x =>
            {
                throw new NotImplementedException();
            });

            this.commitTrackedChanges = ReactiveCommand.CreateAsyncTask<CommitResultModel>(canCommit, async x =>
            {
                //Commit every modified file (tracked)
                StatusOptions status;
                StageOptions stage;
                IRepository repo;
                IList<string> committedFiles;
                IEnumerable<StatusEntry> modifiedFiles;

                committedFiles = new List<string>();
                stage = new StageOptions();
                status = new StatusOptions()
                {
                    DetectRenamesInIndex = true,
                    DetectRenamesInWorkDir = true
                };

                repo = this.currentRepositoryModel.Repository;

                modifiedFiles = await Task.Run<IEnumerable<StatusEntry>>(() => repo.RetrieveStatus(status).Modified);

                //Now stage all modified files
                foreach (var file in modifiedFiles)
                {
                    if (file.State.HasFlag(FileStatus.ModifiedInWorkdir) && file.State.HasFlag(FileStatus.ModifiedInIndex) == false)
                    {
                        await Task.Run(() => repo.Stage(file.FilePath, stage));
                        committedFiles.Add(file.FilePath);
                    }
                }

                return new CommitResultModel() { Files = committedFiles.AsEnumerable() };
            });
        }
示例#15
-1
        public GitBackupStatus InPlaceGitBackup(string repositoryFolder)
        {
            var isValidGitRepository = LibGit2Sharp.Repository.IsValid(repositoryFolder);
            var createdRepository = false;
            if (!isValidGitRepository)
            {
                _logger.InfoFormat("Initializing git repository in folder '{0}'...", repositoryFolder);
                repositoryFolder = LibGit2Sharp.Repository.Init(repositoryFolder, false);
                createdRepository = true;
            }
            var numberOfFilesAdded = 0;
            var numberOfFilesChanged = 0;
            var numberOfFilesRemoved = 0;
            using (var repository = new LibGit2Sharp.Repository(repositoryFolder))
            {
                var options = new StatusOptions();
                var status = repository.RetrieveStatus(options);
                _logger.Debug("Repository Status: " + JsonConvert.SerializeObject(status));
                if (status.IsDirty)
                {
                    var untractedFiles = status.Untracked;
                    foreach (var untrackedFile in untractedFiles)
                    {
                        _logger.Info("Added: " + untrackedFile.FilePath);
                        var stageOptions = new StageOptions();
                        repository.Stage(untrackedFile.FilePath, stageOptions);
                        numberOfFilesAdded++;
                    }

                    var modifiedFiles = status.Modified;
                    foreach (var modifiedFile in modifiedFiles)
                    {
                        _logger.Info("Modified: " + modifiedFile.FilePath);
                        var stageOptions = new StageOptions();
                        repository.Stage(modifiedFile.FilePath, stageOptions);
                        numberOfFilesChanged++;
                    }

                    var removedFiles = status.Missing;
                    foreach (var removedFile in removedFiles)
                    {
                        _logger.Info("Removed: " + removedFile.FilePath);
                        var stageOptions = new StageOptions();
                        repository.Stage(removedFile.FilePath, stageOptions);
                        numberOfFilesRemoved++;
                    }
                    var author = new Signature(Environment.UserName, "*****@*****.**", System.DateTimeOffset.Now);
                    var committer = new Signature(Environment.UserName, "*****@*****.**", System.DateTimeOffset.Now);
                    var commitOptions = new CommitOptions();
                    _logger.Info("Commiting...");
                    repository.Commit(DateTime.Now.ToString(CultureInfo.InvariantCulture), author, committer, commitOptions);
                }
            }
            var gitBackupStatus = new GitBackupStatus(createdRepository, numberOfFilesAdded, numberOfFilesChanged, numberOfFilesRemoved);
            return gitBackupStatus;
        }