Пример #1
0
 private static void AssertStage(bool?ignorecase, IRepository repo, string path)
 {
     try
     {
         repo.Stage(path);
         Assert.Equal(FileStatus.Added, repo.RetrieveStatus(path));
         repo.Reset();
         Assert.Equal(FileStatus.Untracked, repo.RetrieveStatus(path));
     }
     catch (ArgumentException)
     {
         Assert.False(ignorecase ?? true);
     }
 }
Пример #2
0
 private static void AssertStage(bool?ignorecase, IRepository repo, string path)
 {
     try
     {
         repo.Stage(path);
         Assert.Equal(FileStatus.NewInIndex, repo.RetrieveStatus(path));
         repo.Index.Replace(repo.Head.Tip);
         Assert.Equal(FileStatus.NewInWorkdir, repo.RetrieveStatus(path));
     }
     catch (ArgumentException)
     {
         Assert.False(ignorecase ?? true);
     }
 }
Пример #3
0
        public RepositoryStatus Commit()
        {
            UnstageAll();

            var status        = repo.RetrieveStatus();
            var filesToCommit = status.Where(f => f.State != FileStatus.Ignored);

            foreach (var entry in filesToCommit)
            {
                CommitFile(entry.FilePath);
            }

            return(status);
        }
Пример #4
0
        public IndexViewModel(IRepository repo)
        {
            this.repo = repo;
            this.refreshCommand = ReactiveCommand.Create();

            this.repositoryStatus = this.refreshCommand.Select(u =>
            {
                return repo.RetrieveStatus(new StatusOptions() { Show = StatusShowOption.IndexAndWorkDir });
            }).ToProperty(this, vm => vm.RepositoryStatus);

            this.statusEntries = this
                .WhenAny(vm => vm.RepositoryStatus, change =>
                {
                    var status = change.GetValue();

                    return status.CreateDerivedCollection(s => s, null, null, null, this.refreshCommand);
                }).ToProperty(this, vm => vm.StatusEntries);

            var resetSignal = this.WhenAny(vm => vm.StatusEntries, change =>
             {
                 return 0;
             });

            var allEntries = this.WhenAny(vm => vm.StatusEntries, change => change.GetValue());

            this.unstagedEntries = allEntries.Select(s =>
            {
                return s.CreateDerivedCollection(i => i, i => Unstaged(i.State), null, resetSignal);
            }).ToProperty(this, vm => vm.UnstagedEntries);

            this.stagedEntries = allEntries.Select(s =>
            {
                return s.CreateDerivedCollection(i => i, i => Staged(i.State), null, resetSignal);
            }).ToProperty(this, vm => vm.StagedEntries);
        }
Пример #5
0
        private Task Open(string filePath)
        {
            var status = repository.RetrieveStatus(new StatusOptions {
                PathSpec = new[] { filePath }
            })[filePath];

            if (status == null)
            {
                return(Task.CompletedTask);
            }

            switch (status.State)
            {
            case FileStatus.NewInIndex:
            case FileStatus.NewInWorkdir:
            case FileStatus.RenamedInIndex:
            case FileStatus.RenamedInWorkdir:
            case FileStatus.Unaltered:
                RunTool(editorTool, repository.GetFullPath(filePath));
                break;

            case FileStatus.ModifiedInIndex:
            case FileStatus.ModifiedInWorkdir:
                Diff(filePath);
                break;

            default:
                return(Task.CompletedTask);
            }

            return(Task.CompletedTask);
        }
Пример #6
0
        public Task <bool> IsModified(IRepository repository, string path, byte[] contents)
        {
            Guard.ArgumentNotNull(repository, nameof(repository));
            Guard.ArgumentNotEmptyString(path, nameof(path));

            return(Task.Factory.StartNew(() =>
            {
                if (repository.RetrieveStatus(path) == FileStatus.Unaltered)
                {
                    var treeEntry = repository.Head[path];
                    if (treeEntry?.TargetType != TreeEntryTargetType.Blob)
                    {
                        return false;
                    }

                    var blob1 = (Blob)treeEntry.Target;
                    using (var s = contents != null ? new MemoryStream(contents) : new MemoryStream())
                    {
                        var blob2 = repository.ObjectDatabase.CreateBlob(s, path);
                        var diff = repository.Diff.Compare(blob1, blob2);
                        return diff.LinesAdded != 0 || diff.LinesDeleted != 0;
                    }
                }

                return true;
            }));
        }
Пример #7
0
        private static IEnumerable <string> RemoveStagedItems(IRepository repository, IEnumerable <string> paths, bool removeFromWorkingDirectory = true, ExplicitPathsOptions explicitPathsOptions = null)
        {
            var removed = new List <string>();

            using (var changes = repository.Diff.Compare <TreeChanges>(DiffModifiers.IncludeUnmodified | DiffModifiers.IncludeUntracked, paths, explicitPathsOptions))
            {
                var index = repository.Index;

                foreach (var treeEntryChanges in changes)
                {
                    var status = repository.RetrieveStatus(treeEntryChanges.Path);

                    switch (treeEntryChanges.Status)
                    {
                    case ChangeKind.Added:
                    case ChangeKind.Deleted:
                        removed.Add(treeEntryChanges.Path);
                        index.Remove(treeEntryChanges.Path);
                        break;

                    case ChangeKind.Unmodified:
                        if (removeFromWorkingDirectory && (
                                status.HasFlag(FileStatus.ModifiedInIndex) ||
                                status.HasFlag(FileStatus.NewInIndex)))
                        {
                            throw new RemoveFromIndexException("Unable to remove file '{0}', as it has changes staged in the index. You can call the Remove() method with removeFromWorkingDirectory=false if you want to remove it from the index only.",
                                                               treeEntryChanges.Path);
                        }
                        removed.Add(treeEntryChanges.Path);
                        index.Remove(treeEntryChanges.Path);
                        continue;

                    case ChangeKind.Modified:
                        if (status.HasFlag(FileStatus.ModifiedInWorkdir) && status.HasFlag(FileStatus.ModifiedInIndex))
                        {
                            throw new RemoveFromIndexException("Unable to remove file '{0}', as it has staged content different from both the working directory and the HEAD.",
                                                               treeEntryChanges.Path);
                        }
                        if (removeFromWorkingDirectory)
                        {
                            throw new RemoveFromIndexException("Unable to remove file '{0}', as it has local modifications. You can call the Remove() method with removeFromWorkingDirectory=false if you want to remove it from the index only.",
                                                               treeEntryChanges.Path);
                        }
                        removed.Add(treeEntryChanges.Path);
                        index.Remove(treeEntryChanges.Path);
                        continue;

                    default:
                        throw new RemoveFromIndexException("Unable to remove file '{0}'. Its current status is '{1}'.",
                                                           treeEntryChanges.Path,
                                                           treeEntryChanges.Status);
                    }
                }

                index.Write();

                return(removed);
            }
        }
Пример #8
0
        public Model(IRepository repository)
        {
            mRepository = repository;

            mShortHash      = new Lazy <string>(() => mRepository.Commits.First().Sha.Substring(0, 7));
            mBranch         = new Lazy <string>(() => mRepository.Head.CanonicalName);
            mHasLocalChange = new Lazy <string>(() => mRepository.RetrieveStatus().IsDirty.ToString(CultureInfo.InvariantCulture));
#if DEBUG
            mBuildConfig = "DEBUG";
#else
            mBuildConfig = "RELEASE";
#endif

            var commit = mRepository.Commits.First();

            string hash = mRepository.Commits.First().Sha.Substring(0, 7);

            string tag = String.Empty;
            try {
                tag = repository.Describe(commit,
                                          new DescribeOptions {
                    Strategy = DescribeStrategy.Tags
                });
            } catch (LibGit2SharpException) {
                // use default gitDescription value
            }

            string dirty = mRepository.RetrieveStatus().IsDirty ? "-dirty" : String.Empty;

            Match descMatch = Regex.Match(tag, @"(\d+)\.(\d+)\.(\d+)");
            if (descMatch.Success)
            {
                mMajor = new Lazy <string>(() => descMatch.Groups[1].Value.ToString(CultureInfo.InvariantCulture));
                mMinor = new Lazy <string>(() => descMatch.Groups[2].Value.ToString(CultureInfo.InvariantCulture));
                mBuild = new Lazy <string>(() => descMatch.Groups[3].Value.ToString(CultureInfo.InvariantCulture));
            }
            else
            {
                mMajor = new Lazy <string>(() => "0".ToString(CultureInfo.InvariantCulture));
                mMinor = new Lazy <string>(() => "0".ToString(CultureInfo.InvariantCulture));
                mBuild = new Lazy <string>(() => "0".ToString(CultureInfo.InvariantCulture));
            }
            mRevision    = new Lazy <string>(() => mRepository.Commits.Count().ToString(CultureInfo.InvariantCulture));
            mDescription = $"{mMajor.Value}.{mMinor.Value}.{mBuild.Value}.{mRevision.Value}{dirty}";
        }
Пример #9
0
        public FileStatus Get(string filePath)
        {
            if (string.IsNullOrEmpty(filePath))
            {
                throw new ArgumentException(nameof(filePath));
            }

            return(_repo.RetrieveStatus(filePath));
        }
Пример #10
0
        public IEnumerable <RepositoryStatus> GetRepositoryStatus()
        {
            var retrivedStatus = _repository.RetrieveStatus();

            return(retrivedStatus.Where(x => x.State != FileStatus.Ignored)
                   .Select(d => new RepositoryStatus()
            {
                FilePath = d.FilePath, FileStatus = (int)d.State
            }));
        }
        public IEnumerable <StatusItem> GetAll()
        {
            var retrivedStatus = repository.RetrieveStatus();

            return(retrivedStatus.Where(x => x.State != FileStatus.Ignored)
                   .Select(d => new StatusItem()
            {
                Path = d.FilePath, Status = d.State
            }).ToList());
        }
Пример #12
0
 public IEnumerable <StatusEntry> Status()
 {
     try
     {
         return(_repo.RetrieveStatus());
     }
     catch (LibGit2SharpException ex)
     {
         throw new GitException("Failed to retrieve repository status.", ex);
     }
 }
Пример #13
0
 private static void AssertStatus(bool shouldIgnoreCase, FileStatus expectedFileStatus, IRepository repo, string path)
 {
     try
     {
         Assert.Equal(expectedFileStatus, repo.RetrieveStatus(path));
     }
     catch (ArgumentException)
     {
         Assert.False(shouldIgnoreCase);
     }
 }
Пример #14
0
        public Model(IRepository repository)
        {
            mRepository = repository;

            mRevision       = new Lazy <string>(() => mRepository.Commits.Count().ToString(CultureInfo.InvariantCulture));
            mShortHash      = new Lazy <string>(() => mRepository.Commits.First().Sha.Substring(0, 7));
            mBranch         = new Lazy <string>(() => mRepository.Head.CanonicalName);
            mHasLocalChange = new Lazy <string>(() => mRepository.RetrieveStatus().IsDirty.ToString(CultureInfo.InvariantCulture));
#if DEBUG
            mBuildConfig = "DEBUG";
#else
            mBuildConfig = "RELEASE";
#endif
        }
        private static List <string> GetUncommitedFiles(IRepository repository)
        {
            var newInIndex = new List <string>();

            foreach (var item in repository.RetrieveStatus(new StatusOptions()))
            {
                if (FileIsNotCommited(item))
                {
                    newInIndex.Add(item.FilePath);
                }
            }

            return(newInIndex);
        }
Пример #16
0
        public Model(IRepository repository)
        {
            mRepository = repository;

            mRevision = new Lazy<string>(() => mRepository.Commits.Count().ToString(CultureInfo.InvariantCulture));
            mShortHash = new Lazy<string>(() => mRepository.Commits.Last().Sha.Substring(0, 7));
            mBranch = new Lazy<string>(() => mRepository.Head.CanonicalName);
            mHasLocalChange = new Lazy<string>(() => mRepository.RetrieveStatus().IsDirty.ToString(CultureInfo.InvariantCulture));
            #if DEBUG
            mBuildConfig = "DEBUG";
            #else
            mBuildConfig = "RELEASE";
            #endif
        }
Пример #17
0
        public ChangesView(IRepository repository, IEventStream eventStream)
            : base("Changes")
        {
            this.repository  = repository;
            this.eventStream = eventStream;

            var status = repository.RetrieveStatus(new StatusOptions());

            view = new ListView <FileStatus>()
            {
                AllowsMarking = true
            };
            view.SelectedChanged += OnSelectedChanged;

            Content = view;
        }
Пример #18
0
 public static GitRepository FromRepository(IRepository repository) =>
 new GitRepository(
     repository.Branches.Select(
         branch => new GitBranch(
             branch.IsRemote,
             branch.RemoteName,
             branch.FriendlyName,
             branch.IsCurrentRepositoryHead,
             branch.Commits.Select(
                 commit => new GitCommit(commit.Sha)).ToList())).ToList(),
     repository.Commits.OrderTopological().Select(
         commit => new GitCommit(commit.Sha)).ToList(),
     repository.Tags.Select(
         tag => new GitTag(
             tag.FriendlyName,
             tag.PeeledTarget.Sha)).ToList(),
     repository.RetrieveStatus().IsDirty);
Пример #19
0
        private static void FeedTheRepository(IRepository repo)
        {
            string fullPath = Touch(repo.Info.WorkingDirectory, "a.txt", "Hello\n");

            repo.Stage(fullPath);
            repo.Commit("Initial commit", Constants.Signature, Constants.Signature);
            repo.ApplyTag("mytag");

            File.AppendAllText(fullPath, "World\n");
            repo.Stage(fullPath);

            Signature shiftedSignature = Constants.Signature.TimeShift(TimeSpan.FromMinutes(1));

            repo.Commit("Update file", shiftedSignature, shiftedSignature);
            repo.CreateBranch("mybranch");

            repo.Checkout("mybranch");

            Assert.False(repo.RetrieveStatus().IsDirty);
        }
Пример #20
0
 private static Tuple<string, FileStatus> BuildFrom(IRepository repository, string path)
 {
     string relativePath = repository.BuildRelativePathFrom(path);
     return new Tuple<string, FileStatus>(relativePath, repository.RetrieveStatus(relativePath));
 }
Пример #21
0
 public FileStatus RetrieveStatus(string filePath) =>
 repository.RetrieveStatus(filePath);
Пример #22
0
 private static void AssertStatus(bool shouldIgnoreCase, FileStatus expectedFileStatus, IRepository repo, string path)
 {
     try
     {
         Assert.Equal(expectedFileStatus, repo.RetrieveStatus(path));
     }
     catch (ArgumentException)
     {
         Assert.False(shouldIgnoreCase);
     }
 }
Пример #23
0
        private static Tuple <string, FileStatus> BuildFrom(IRepository repository, string path)
        {
            string relativePath = repository.BuildRelativePathFrom(path);

            return(new Tuple <string, FileStatus>(relativePath, repository.RetrieveStatus(relativePath)));
        }
Пример #24
0
        private static IEnumerable<string> RemoveStagedItems(IRepository repository, IEnumerable<string> paths, bool removeFromWorkingDirectory = true, ExplicitPathsOptions explicitPathsOptions = null)
        {
            var removed = new List<string>();
            using (var changes = repository.Diff.Compare<TreeChanges>(DiffModifiers.IncludeUnmodified | DiffModifiers.IncludeUntracked, paths, explicitPathsOptions))
            {
                var index = repository.Index;

                foreach (var treeEntryChanges in changes)
                {
                    var status = repository.RetrieveStatus(treeEntryChanges.Path);

                    switch (treeEntryChanges.Status)
                    {
                        case ChangeKind.Added:
                        case ChangeKind.Deleted:
                            removed.Add(treeEntryChanges.Path);
                            index.Remove(treeEntryChanges.Path);
                            break;

                        case ChangeKind.Unmodified:
                            if (removeFromWorkingDirectory && (
                                status.HasFlag(FileStatus.ModifiedInIndex) ||
                                status.HasFlag(FileStatus.NewInIndex)))
                            {
                                throw new RemoveFromIndexException("Unable to remove file '{0}', as it has changes staged in the index. You can call the Remove() method with removeFromWorkingDirectory=false if you want to remove it from the index only.",
                                    treeEntryChanges.Path);
                            }
                            removed.Add(treeEntryChanges.Path);
                            index.Remove(treeEntryChanges.Path);
                            continue;

                        case ChangeKind.Modified:
                            if (status.HasFlag(FileStatus.ModifiedInWorkdir) && status.HasFlag(FileStatus.ModifiedInIndex))
                            {
                                throw new RemoveFromIndexException("Unable to remove file '{0}', as it has staged content different from both the working directory and the HEAD.",
                                    treeEntryChanges.Path);
                            }
                            if (removeFromWorkingDirectory)
                            {
                                throw new RemoveFromIndexException("Unable to remove file '{0}', as it has local modifications. You can call the Remove() method with removeFromWorkingDirectory=false if you want to remove it from the index only.",
                                    treeEntryChanges.Path);
                            }
                            removed.Add(treeEntryChanges.Path);
                            index.Remove(treeEntryChanges.Path);
                            continue;

                        default:
                            throw new RemoveFromIndexException("Unable to remove file '{0}'. Its current status is '{1}'.",
                                treeEntryChanges.Path,
                                treeEntryChanges.Status);
                    }
                }

                index.Write();

                return removed;
            }
        }
Пример #25
0
 private static void AssertStage(bool? ignorecase, IRepository repo, string path)
 {
     try
     {
         Commands.Stage(repo, path);
         Assert.Equal(FileStatus.NewInIndex, repo.RetrieveStatus(path));
         repo.Index.Replace(repo.Head.Tip);
         Assert.Equal(FileStatus.NewInWorkdir, repo.RetrieveStatus(path));
     }
     catch (ArgumentException)
     {
         Assert.False(ignorecase ?? true);
     }
 }
Пример #26
0
 private static void AssertStage(bool? ignorecase, IRepository repo, string path)
 {
     try
     {
         repo.Stage(path);
         Assert.Equal(FileStatus.Added, repo.RetrieveStatus(path));
         repo.Reset();
         Assert.Equal(FileStatus.Untracked, repo.RetrieveStatus(path));
     }
     catch (ArgumentException)
     {
         Assert.False(ignorecase ?? true);
     }
 }
Пример #27
0
 public FileStatus RetrieveStatus(string filePath)
 {
     return(repositoryInstance.RetrieveStatus(filePath));
 }
Пример #28
0
        public async Task ExecuteAsync(object?parameter = null, CancellationToken cancellation = default)
        {
            var repositoryStatus = repository.RetrieveStatus();

            var localBranch  = repository.Head;
            var targetBranch = repository.Head.TrackedBranch ?? repository.Head;

            var dialog = new PullDialog(
                targetBranch.RemoteName ?? repository.GetDefaultRemoteName(),
                targetBranch.GetName(),
                showStashWarning: repositoryStatus.IsDirty,
                trackRemoteBranch: false,
                remotes: repository.GetRemoteNames(),
                branches: repository.GetBranchNames());

            if (mainThread.Invoke(() => dialog.ShowDialog()) == true && !string.IsNullOrEmpty(dialog.Branch))
            {
                var targetBranchFriendlyName = string.IsNullOrEmpty(dialog.Remote) ?
                                               dialog.Branch : $"{dialog.Remote}/{dialog.Branch}";

                targetBranch = repository.Branches.FirstOrDefault(x => x.FriendlyName == targetBranchFriendlyName);

                if (targetBranch == null)
                {
                    throw new InvalidOperationException(string.Format("Branch {0} not found", targetBranchFriendlyName));
                }

                eventStream.Push(Status.Start("Pull {0} {1}", targetBranchFriendlyName, dialog.IsFastForward ? "With Fast Fordward" : string.Empty));

                var stash       = default(Stash);
                var mergeResult = default(MergeResult);
                var stashResult = default(StashApplyStatus);

                // 1. Fetch
                if (targetBranch.IsRemote)
                {
                    TryFetch(targetBranch);
                }

                // 2. Stash (optional, if the repo is dirty) and Merge
                try
                {
                    if (repositoryStatus.IsDirty)
                    {
                        stash = repository.Stashes.Add(Signatures.GetStashSignature(), StashModifiers.IncludeUntracked);
                    }

                    mergeResult = Merge(targetBranch, dialog.IsFastForward);
                }
                finally
                {
                    if (stash != null && repository.Stashes.Contains(stash) && !repository.RetrieveStatus().IsDirty)
                    {
                        stashResult = repository.Stashes.Pop(repository.Stashes.ToList().IndexOf(stash));
                    }
                }

                // 3. Resolve conflicts
                if (mergeResult?.Status == MergeStatus.Conflicts)
                {
                    await commandService.RunAsync("ResolveConflicts");
                }

                // 4. Track
                if (dialog.TrackRemoteBranch)
                {
                    localBranch.Track(repository, targetBranch);
                }

                // 5. Update submodules
                if (dialog.UpdateSubmodules)
                {
                    eventStream.Push(Status.Create(0.8f, "Updating submodules..."));
                    repository.UpdateSubmodules(eventStream: eventStream);
                }

                eventStream.Push(Status.Finish(mergeResult.Status.ToString()));

                mainThread.Invoke(() => view.Refresh());
            }
        }
Пример #29
0
 /// <summary>
 /// Get a value indicating if there are modifications in the current working directory.
 /// </summary>
 private void GitModifications(IRepository repo)
 {
     var status = repo.RetrieveStatus(new StatusOptions());
     this.gitInfo.Added = status.Added.Count();
     this.gitInfo.Missing = status.Missing.Count();
     this.gitInfo.Modified = status.Modified.Count();
     this.gitInfo.Removed = status.Removed.Count();
     this.gitInfo.Staged = status.Staged.Count();
     this.gitInfo.Changes = this.gitInfo.Added + this.gitInfo.Missing + this.gitInfo.Modified
                            + this.gitInfo.Removed + this.gitInfo.Staged;
     this.gitInfo.HasModifications = Convert.ToBoolean(this.gitInfo.Changes);
 }
Пример #30
0
        private static void FeedTheRepository(IRepository repo)
        {
            string fullPath = Touch(repo.Info.WorkingDirectory, "a.txt", "Hello\n");
            repo.Stage(fullPath);
            repo.Commit("Initial commit", Constants.Signature, Constants.Signature);
            repo.ApplyTag("mytag");

            File.AppendAllText(fullPath, "World\n");
            repo.Stage(fullPath);

            Signature shiftedSignature = Constants.Signature.TimeShift(TimeSpan.FromMinutes(1));
            repo.Commit("Update file", shiftedSignature, shiftedSignature);
            repo.CreateBranch("mybranch");

            repo.Checkout("mybranch");

            Assert.False(repo.RetrieveStatus().IsDirty);
        }